Hello everyone I want to post image and other data through Retrofit2 please guide me where I am lacking in my code
#Multipart
#POST(HttpConstants.FILEUPLOADJSON1)
Call<Result>uploadImage(#Part MultipartBody.Part file,#Query("stdID")int stdID);
php part
$stdID=$_POST['stdID'];
$file_path = "profile_images/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
$actualpath="http://myservices.96.lt/$file_path";
$sql = "UPDATE testuser SET profile_photo = '".$actualpath."' WHERE user_id = '".$stdID."'";
if(mysqli_query($conn,$sql))
{
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path))
{
$result = array("result" => "success", "value" => $sql);
}
else
{
$result = array("result" => "error file transfer");
}
}else{
$result = array("result" => "error mysql");
}
echo json_encode($result);
use #Part instead of #Query in Multipart request
In your Retrofit api interface pass your parameter as followws.
#Multipart
#POST(HttpConstants.FILEUPLOADJSON1)
Call<Result>uploadImage(#Part MultipartBody.Part file, #Part("stdID") stdID);
I hope its work for you
Related
I am setting up a payout process for a driver in my app with Firebase Cloud Functions and Paypal. The url to be posted is the url of the actual cloud function in Firebase:
https://us-central1-ryyde-sj.cloudfunctions.net/payout
When trying to send an HTTP Post Request, it doesn't seem to be working. See the payoutRequest() and the Response code below:
payoutRequest()
let email = txtPayoutEmail.text!
let uid = self.uid!
// Prepare URL:
let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object:
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Headers
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Your Token", forHTTPHeaderField: "Authorization")
request.setValue("no-cache", forHTTPHeaderField: "cache-control")
print("request = \(request)")
// HTTP Request Parameters which will be sent in HTTP Request Body:
let postString = "uid=\(uid)&email=\(email)"
print("postString = \(postString)")
// Set HTTP Request Body
request.httpBody = postString.data(using: String.Encoding.utf8)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in
print("data: \(String(describing: data))")
print("response: \(String(describing: response))")
print("error: \(String(describing: error))")
if let response = response as? HTTPURLResponse {
// Read all HTTP Response Headers
print("All headers: \(response.allHeaderFields)")
// Read a specific HTTP Response Header by name
if #available(iOS 13.0, *) {
print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
} else {
// Fallback on earlier versions
}
}
// Check for Errors
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string: \(dataString)")
}
}
task.resume()
Response
request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
postString = uid=kv8JRVBwAfS1tgD04lNeM9esVzI2&email=myiosapp#me.com
data: Optional(138 bytes)
response: Optional(<NSHTTPURLResponse: 0x6000037d1c20> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 400, Headers {
"Content-Length" = (
138
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Thu, 17 Sep 2020 01:00:50 GMT"
);
Server = (
"Google Frontend"
);
"alt-svc" = (
"h3-Q050=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"content-security-policy" = (
"default-src 'none'"
);
"function-execution-id" = (
cmrwbktlroxl
);
"x-cloud-trace-context" = (
"a85aaacd578e60690581aa64ead13b23;o=1"
);
"x-content-type-options" = (
nosniff
);
"x-powered-by" = (
Express
);
} })
error: nil
All headers: [AnyHashable("content-security-policy"): default-src 'none',
AnyHashable("Date"): Thu, 17 Sep 2020 01:00:50 GMT, AnyHashable("alt-svc"): h3-Q050=":443";
ma=2592000,h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-
T050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443";
ma=2592000; v="46,43", AnyHashable("Content-Type"): text/html; charset=utf-8,
AnyHashable("Content-Length"): 138, AnyHashable("x-cloud-trace-context"):
a85aaacd578e60690581aa64ead13b23;o=1, AnyHashable("Server"): Google Frontend,
AnyHashable("x-powered-by"): Express, AnyHashable("x-content-type-options"): nosniff,
AnyHashable("function-execution-id"): cmrwbktlroxl]
Specific header: text/html; charset=utf-8
Response data string: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Bad Request</pre>
</body>
</html>
If the request is successful, then it would show up in the PayPal Notifications for PayPal Sandbox at the below link, but it isn't.
PayPal developer notifications link
I don't have much experience in PayPal HTTP requests.
I have done the same thing as I am trying to do here but in Android and it works perfectly so I know this should work, other than the Post Request (I tried using examples online to match what i had for the Android app)
Edit
updated payoutRequest():
Code surrounded in ** ** is new code
let email = txtPayoutEmail.text!
let uid = self.uid!
// Prepare URL:
let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object:
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Headers
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Your Token", forHTTPHeaderField: "Authorization")
request.setValue("no-cache", forHTTPHeaderField: "cache-control")
print("request = \(request)")
// HTTP Request Parameters which will be sent in HTTP Request Body:
**let body = ["uid": uid, "email": email]**
print("body = \(body)")
// Set HTTP Request Body
**request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])**
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in
print("data: \(String(describing: data))")
print("response: \(String(describing: response))")
print("error: \(String(describing: error))")
if let response = response as? HTTPURLResponse {
// Read all HTTP Response Headers
print("All headers: \(response.allHeaderFields)")
// Read a specific HTTP Response Header by name
if #available(iOS 13.0, *) {
print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
} else {
// Fallback on earlier versions
}
}
// Check for Errors
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string: \(dataString)")
}
}
task.resume()
Response:
request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
body = ["uid": "kv8JRVBwAfS1tgD04lNeM9esVzI2", "email": "driver#ryyde.com"]
data: Optional(0 bytes)
response: Optional(<NSHTTPURLResponse: 0x600001f0d6a0> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 200, Headers {
"Content-Length" = (
0
);
"Content-Type" = (
"text/html"
);
Date = (
"Thu, 17 Sep 2020 04:41:29 GMT"
);
Server = (
"Google Frontend"
);
"alt-svc" = (
"h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"function-execution-id" = (
cmrwtq89fdsr
);
"x-cloud-trace-context" = (
"f3fe884ca8499e7a10c7081ce222876e;o=1"
);
"x-powered-by" = (
Express
);
} })
error: nil
All headers: [AnyHashable("Content-Length"): 0, AnyHashable("x-cloud-trace-context"): f3fe884ca8499e7a10c7081ce222876e;o=1, AnyHashable("Server"): Google Frontend, AnyHashable("x-powered-by"): Express, AnyHashable("function-execution-id"): cmrwtq89fdsr, AnyHashable("alt-svc"): h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43", AnyHashable("Date"): Thu, 17 Sep 2020 04:41:29 GMT, AnyHashable("Content-Type"): text/html]
Specific header: text/html
Response data string:
EDIT 2
When I run my code, I check the function logs in firebase/functions (read from bottom up - seems to go ok with the function activity)
EDIT 3 - Charles Session results
URL https://us-central1-ryyde-sj.cloudfunctions.net Status Sending
request body… Notes Transaction began prior to session being cleared,
body content transmitted before the session clear has not been
captured Response Code 200 Connection established Protocol HTTP/1.1
TLS TLSv1.2 (TLS_AES_128_GCM_SHA256) Protocol TLSv1.2 Session
Resumed Yes Cipher Suite TLS_AES_128_GCM_SHA256 ALPN - Client
Certificates - Server Certificates - Extensions Method CONNECT Kept
Alive No Content-Type Client Address 127.0.0.1:57209 Remote
Address us-central1-ryyde-sj.cloudfunctions.net/216.239.36.54:443
Tags - Connection WebSockets - Timing Size Request 1.77 KB (1,817
bytes) Response 1.35 KB (1,379 bytes)
EDIT 4 - Android code
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-ryyde-sj.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
try this:
let body = ["uid": uid,
"email": email]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
im working in uploading image in mysql database with android studio
my function in laravel
public function ajouter(Request $req){
try {
$produit= new Produit;
$produit->name= $req->name;
if($req->file('name')){
$path = Storage::disk('produits')->putFile('',$req->file('name'));
$produit->name = $path;
}
$produit->description= $req->description;
$produit->poids= $req->poids;
$produit->category_id= $req->category_id;
$produit->user_id= $req->user_id;
$produit->volume= $req->volume;
$produit->save();
return response()->json([
'status' => 'success',
'data' => $produit
]);
} catch (Exception $e) {
return response()->json([
'status' => 'error',
'data' => 'error'
]);
}
i have tested it with postman and it works.
i have created an interface in android
public interface AjouterProduit {
String AJOPROD = "http://IP/AnnocesPFE/public/api/";
#Multipart
#POST("produits")
Call<String> getAjoutProd(
#Part MultipartBody.Part name,
#Part("description") String description,
#Part("poids") String poids,
#Part("volume") String volume,
#Part("category_id") int category_id,
#Part("user_id") int user_id
);
}
im blocked how to send all the informations to the database any help ?
My Retrofit should recieve a List of Bookmarks, and everything worked while I was using WAMP server. When I changed server to external (nothing else changed, just ip address of the server and retrieving of everything else works) I have an error:
java.io.EOFException: End of input at line 1 column 1
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1407)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:553)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:74)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:116)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
My Retrofit code:
public void init() {
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
HttpLoggingInterceptor debugger =
new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient
.addInterceptor(debugger);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient.build())
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
String email = pref.getString(Constants.EMAIL, "");
System.out.println(email);
String id_group = pref.getString(Constants.ID_GROUP, "");
System.out.println(id_group);
String nazwa = pref.getString(Constants.NAZWA, "");
Integer id_int_group = Integer.parseInt(id_group);
Bookmark bookmark = new Bookmark(email, id_int_group, nazwa);
ServerRequest request2 = new ServerRequest();
request2.setOperation(Constants.GET_MY_GROUPS);
request2.setBookmark(bookmark);
Call<List<Bookmark>> response2 = requestInterface.operation2(request2);
response2.enqueue(new Callback<List<Bookmark>>() {
#Override
public void onResponse(Call<List<Bookmark>> call, retrofit2.Response<List<Bookmark>> response2) {
listOfBookmarks = response2.body();
bookmarkToString();
simpleAdapter.notifyDataSetChanged(); // refresh listivew
}
#Override
public void onFailure(Call<List<Bookmark>> call, Throwable t) {
Log.d(Constants.TAG, "Nie zaladowano!", t);
}
});
}
EDIT://
PHP code:
<?php
class Bookmark {
private $host = 'localhost';
private $user = 'nwbrn_root';
private $db = 'nwbrn_app';
private $pass = 'zxs#1208NMLK';
private $conn;
public function __construct() {
$this -> conn = new PDO("mysql:host=".$this -> host.";dbname=".$this -> db, $this -> user, $this -> pass);
}
public function checkBookmarkExist($email, $id_group){
try {
$query = $this->conn->prepare("SELECT COUNT(*) from bookmarks WHERE email =:email AND id_group =:id_group");
// $query = $this -> conn -> prepare($sql);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':id_group', $id_group, PDO::PARAM_INT);
$query->execute(array('email' => $email, 'id_group' => $id_group));
$row_count = $query -> fetchColumn();
if ( $row_count>0 ) {
$response["result"] = "success";
$response["message"] = "Your favourite!";
return json_encode($response);
}
else {
$response["result"] = "failure";
$response["message"] = "Not in your favourite!";
return json_encode($response);
}
} catch (PDOException $e) {
die ($e->getMessage());
}
}
public function fullStarSelected($email, $id_group, $nazwa){
try {
$query = $this->conn->prepare("DELETE from bookmarks WHERE email =:email AND id_group =:id_group AND nazwa =:nazwa");
// mysqli_set_charset($this->conn, "utf8");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':id_group', $id_group, PDO::PARAM_INT);
$query->bindParam(':nazwa', $nazwa, PDO::PARAM_STR);
$query->execute();
if ( $query ->rowCount() > 0 ) {
$response["result"] = "failure";
$response["message"] = "Row not deleted!";
return json_encode($response);
}
else {
$response["result"] = "success";
$response["message"] = "Row deleted successfully!";
return json_encode($response);
}
} catch (PDOException $e) {
die ($e->getMessage());
}
}
public function blankStarSelected($email, $id_group, $nazwa){
try {
$query = $this->conn->prepare("INSERT INTO bookmarks (email, id_group, nazwa) VALUES (:email, :id_group, :nazwa)");
// mysqli_set_charset($this->conn, "utf8");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':id_group', $id_group, PDO::PARAM_INT);
$query->bindParam(':nazwa', $nazwa, PDO::PARAM_STR);
$query->execute();
if (!$query) {
printf("Error: %s\n", mysqli_error($this->conn));
exit();
}
$result = array();
// $query1 = $this->conn->prepare("SELECT COUNT(*) from bookmarks WHERE email =:email AND id_group =:id_group LIMIT 1");
if ( $query->rowCount() > 0 ) {
$response["result"] = "success";
$response["message"] = "Row added successfully!";
return json_encode($response);
}
else {
$response["result"] = "failure";
$response["message"] = "Row not added!";
return json_encode($response);
}
} catch (PDOException $e) {
die ($e->getMessage());
}
}
public function getMyGroups($email, $id_group){
try {
$con = mysqli_connect($this->host,$this->user,$this->pass,$this->db);
$sql = "SELECT * FROM bookmarks WHERE email = '$email'";
$res = mysqli_query($con,$sql);
$result = array();
if (!$res) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
while($row = mysqli_fetch_array($res)){
$temp = array();
$temp['id_group']=$row['id_group'];
$temp['email']=$row['email'];
$temp['nazwa']=$row['nazwa'];
array_push($result,$temp);
}
echo json_encode($result);
} catch (PDOException $e) {
die ($e->getMessage());
}
}
}
When you see
java.io.EOFException: End of input at line 1 column 1
it indicates a problem with parsing something. It's expecting some text to parse but it got End of File (EOF).
Then you said:
When I changed server to external (nothing else changed)
If this worked before, your problem is definitely not on your code and it is on the data you're retrieving. Your new server is either rejecting your requests or returning blank data. Try doing the same request manually (via postman or some other api client) and see what the response is. It'll very likely tell you where the error is.
I had this error because the body of the answer was passing an empty text "", I solved it by passing it a body null since certain methods that depend on the value of the body are being used. And when having an empty value, the necessary check-ups are not made, instead with the null value of the body, the flow is conditioned by the nullity.
In the declaration I went on to define a null value by default fun response(httpCode: Int, body: String? = null): Response<T>
In the invocation I went from Request#response(200, "") to Request#response(200)
According to the http code protocol, only 204 can allow the body to be null although this may vary depending on the particular service of the needs of one.
GL
i am sending ajax request to server to get the database. But if i enter incorrect data (which is to be sent over server) nothing is happening, error function is not working, all i am doing is to verify credentials from the server
here is my code
$.ajax
({
url: "URL",
type: "GET",
datatype: "jsonp",
data: {type: 'login', id: C_id},
ContentType: "application/json",
success: function(res)
{
var simpleJson = JSON.parse(res);
myDB.transaction(function (txe1)
{
for (var i = 0; i < simpleJson.User.length; i++)
{
var Cli_id= simpleJson.User[i].id;
myDB.transaction(function (txe)
{
txe.executeSql('CREATE TABLE Client_data(Mobile integer , C_id integer, U_id integer , name text , ip integer )');
});
myDB.transaction(function (txe1)
{
var data_ins = 'INSERT INTO Client_data (Mobile,C_id,U_id) VALUES (?,?,?)';
txe1.executeSql(data_ins, [p,C_id,U_id]
,function(tx, result)
{
navigator.notification.alert('Inserted' , onSignup, 'Info', 'ok');
},
function(error)
{
navigator.notification.alert('Already Registered');
});
});
}
});
},
});
});
my PHP code
<?php
header('Access-Control-Allow-Origin:*');
$conn = mysql_connect("***", "***", "****");
if (!$conn)
{
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekspeser_pro"))
{
echo "Unable to select mydbname: " . mysql_error();
exit;
}
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$id=$_GET['id'];
$sql = "SELECT * from client_master WHERE id='$id'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
if($num_rows!=0)
{
while($myrow = mysql_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('User' => $recipes));
echo $output;
}
else
{
print "invalid key";
}
}
else
{
print "invalid login";
}
}
else
{
echo "invalid";
}
mysql_close();
?>
You should implement the error callback to perform some operation when the request fails. This is how you can implement request failure callback.
$.ajax({
url: "/save/author",
type: "POST",
dataType: "json",
data: { name: "John", age: "35" },
success: function (data, status, jqXHR) {
alert("request succeed");
},
error: function (jqXHR, status, err) {
alert("request failed");
}
})
as per this example, we are just showing an alert with text request failed. You can implement it accordingly as per your requirement.
If i get you correct,you want to validate the data passed to your url, if i am getting you correct you want to handle,please refer below:
Ajax error function will only be called if the request fails, see http://api.jquery.com/jQuery.ajax/
So if you return any response from your PHP server/API, the error function won't be triggered as The "error" setting of the ajax method is fired when the calls fails in the sending process. Errors like "timeout", "404", etc...
However, you can return a key from your PHP code as below to handle success and error in your ajax code:
$data['error'] = $success ? 0:1;// If success than set error to 0 else 1;
and in AJAX success you can handle it as :
success: function (data, status, jqXHR) {
if(data.error)
//do something
else
//do something else
}
Let me know if any queries
------EDIT------------------
<?php
header('Access-Control-Allow-Origin:*');
$conn = mysql_connect("***", "***", "****");
if (!$conn)
{
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekspeser_pro"))
{
echo "Unable to select mydbname: " . mysql_error();
exit;
}
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$id=$_GET['id'];
$sql = "SELECT * from client_master WHERE id='$id'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$is_error=0;
if($num_rows!=0)
{
while($myrow = mysql_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('User' => $recipes,'is_error'=>$is_error));
echo $output;
}
else
{
$is_error=1;
$error_message = "Invalid Key";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
}
else
{
$is_error=1;
$error_message = "Invalid Login";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
}
else
{
$is_error=1;
$error_message = "Invalid";
$output = json_encode(array('is_error'=>$is_error,'error_message'=>$error_message));
echo $output;
}
mysql_close();
?>
In AJAX Code access it like this :
Check for following in success
if(simpleJson.is_error!=1)
//do your processing
else
alert(simpleJson.error_message);
Let me know if anything unclear
My environment is Android and i use Xamarin for do my project.
I have a problem with my connection to server, for that i use Json my error is :
`Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2. at Newtonsoft.Json.Linq.JObject.Load`
so my code app side is :
public async Task Login (string user_email, string user_password)
{
var content = new Dictionary<string, string> { {
"user_email",
user_email
},
{
"user_password",
user_password
}
};
String str = await ProcessPOST ("/api/login", content);
JObject data = JObject.Parse (str);
if (data ["success"] != null)
return (string)data ["success"];
throw new Exception ((string)data ["error"]);
}
and server side is :
So login
public function login() {
if ($this->method == "POST") {
if ($this->_data("user_email") && $this->_data("user_password")) {
$u_dao = new UserDAO();
$users = $u_dao->executeSelect("WHERE user_email = :user_email", array("user_email" => $this->_data("user_email")));
if (!isset($users[0]))
return $this->_response(array("error" => "User not found"), 403);
$user = $users[0];
if ($user && crypt($this->_data("user_password"), $user->user_password) == $user->user_password) {
$token = bin2hex(openssl_random_pseudo_bytes(16));
$user->user_token = $token;
$u_dao->update($user);
return $this->_response(array("success" => $token));
}
return $this->_response(array("error" => "Bad login"), 403);
}
return $this->_response(array("error" => "Missing data"), 500);
}
return $this->_response(array("error" => "Wrong method"), 405);
}
and code of _response
protected function _response($data, $status = 200) {
header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
return json_encode($data);
}
and now of _requestStatus
private function _requestStatus($code) {
$status = array(
200 => 'OK',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Internal Server Error',
);
return ($status[$code]) ? $status[$code] : $status[500];
}
and when i try to connect my web service is online , but i forget to said when i have error like "Missing Data" i haven't error of JObject but when i have success i have error.
so i show to all two str one of error:
"{\"error\":\"Missing data\"}"
and one of succes:
"''{\"success\":\"db035db78a9f1e64d71c83bcbb45ffa5\"}"
i want to said thanks to all people which help me . And i'm sorry for my bad english but i'm french .
i hope to be clear but if u have question u can ask them.
I don't see any necessary use for Json.net here. I would simplify and just check if the response contains "success" or "error".