JQuery gives JSON syntax error when using PHP's json_encode - javascript

I have an application that uses JQuery $.ajax to send JSON encoded data to server where I process it and then send back the results also JSON encoded. The problem is that JQuery gives a parse error when I want to process the response. (As if PHP's json_encode function outputs an invalid JSON format).
Here comes the code:
The Javascript code:
$.ajax({
type: 'POST',
url: URL+'pages/processListUIAjaxRequest',
data:{filters: filters, rebuild_params: $('#rebuild_params\\['+unique+'\\]').val()},
dataType: 'json',
success: function(response){
alert(response);
},
error: function(request, status, error){
alert('Unable to update table contents');
console.log(request);
console.log(status);
console.log(error);
}
});
This is a piece of the PHP code which outputs the response:
$response->addResult($uFilters);
header('Content-Type: application/json');
$response->toJSON(true);
The $uFilters is a simple array, and the toJSON method of the $response object is here:
public function toJSON($output = false){
$out = array();
if($this->hasErrors()){
$out['has_error'] = true;
$out['errors'] = $this->getErrors();
} else $out['has_error'] = false;
$out['result'] = $this->_result;
if($output){
echo json_encode($out);
}else{
return json_encode($out);
}
}// toJSON
Every time I run the code i get the 'Unable to update table contents', and on JavaScript console I have:
'SyntaxError: JSON.parse: unexpected character'
despite I defined dataType: as 'json' and the output is json_encode'd by PHP. On the JavaScript console I can see that the response text is:
"{"has_error":false,"result":{"page_id":"xxx"}}"
Tried copy this and validate with online JSON validator tools, the interesting thing is it was valid a few times and it was invalid a few times (without any consistency) Im a bit confused.
Tried to use other headers like:
header('Content-Type: text/json');
header('Content-Type:javascript/json');
header('Content-Type: application/json');
or with no header, but nothing.
If I edit the JQuery ajax request's dataType to 'text' (despite the output is JSON formatted and and even the header says it is a JSON content), then the success handler runs and I got the response correctly. In this case the same problem comes when I try to $.parseJSON(response).
What went wrong? Is my JSON string really invalid?

Debug your response to see what characters are there that is making it not valid. Set the dataType to text and escape the text that is returned.
dataType: 'text',
success: function(response){
console.log(escape(response));
},
You will see the characters that are returned, there is probably some weird return character that is cauing the problem.

Related

Why are my PHP/AJAX with JSONP scripts returning HTML, JSON, and invalid JSON?

I am having some trouble with communication between my php script and my javascript file. It seems the javascript is receiving html, json, and "invalid json" from the php script that I have written.
In the Javascript code, the data variable evaluates to:
{"readyState":4,"status":200,"statusText":"success"}
This is not of the JSON format that I echo below (in either spot in the code where I do so). Based on my research, this is because the JSON echo in the PHP code is returning invalid JSON (which causes the PHP to return this as a result instead). However, when I check the console, I find the following:
<br />
<b>Warning</b>: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for ... in <b>..../.php</b> on line <b>xx</b><br />
{"status":"failure","message":"Access denied for ...."}
This is not printed because of any console.log statements I have in my code, this is printed as a result of Firefox's automatic console entry from the GET http://...../.php call.
The top line of code is the html that the PHP would return if this were not a JSON return, and the bottom line of the code above is the actual JSON object that I have created, and that I want to work with.
The reason I am posting here is because I cannot think of why the PHP would return html, my JSON, and JSON indicating invalid JSON.
I should also mention that I am receiving another error on the console:
SyntaxError: expected expression, got '<' --> file.php:1
This suggests to me that the browser is trying to interpret the php on the client end for some reason, but I'm not sure if that's accurate or not.
I think that I have an error somewhere that is the root of all of these symptoms, but after some time and research, I have not been able to find this error on my own.
The code I am using is shown below:
Javascript AJAX:
$.ajax({
url: "...url.../file.php",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data: {
name: email,
email: email
},
complete: function(data) {
console.log(JSON.stringify(data));
//this is where the {"readyState":4,"status":200,"statusText":"success"} appears
}
});
PHP (contents reduced to scope of this problem):
<?php
header("Content-type: application/json");
header("Content-Disposition: attachment;Filename=\"gamesUser.json\"");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
.........
$data = array();
$conn = #new mysqli($servername, $username, $password, $dbname, $port);
//check the connection
if ($conn->connect_error) {
$data['status'] = 'failure';
$data['message'] = $conn->connect_error;
echo json_encode($data);
} else {
.........
$data['status'] = 'success';
$data['message'] = 'operations complete';
$data['fileURL'] = $fileURL;
echo json_encode($data);
.........
}
.........
?>
SOLVED!
The code:
echo $_GET['callback'].'('.json_encode($data).')';
along with changing ajax parameters:
type: "GET",
dataType: 'jsonp',
jsonpCallback: 'handleResponse',
data: data
Have fixed the problems. Thanks to everyone who assisted in the discussion.
I think , what you need is the callback function from jsonp , please go through the below example , you will get the idea
function myfunc(json) {
alert(json);
}
$.ajax({
type: "GET",
url: "http://example.com?keyword=r&callback=jsonp",
dataType: 'jsonp',
jsonpCallback: 'myfunc', // the function to call
jsonp: 'callback', // name of the var specifying the callback in the request
})
;
When an error happens in PHP, it displays the error information using HTML so you can see it properly in the browser. That's why you get the unexpected HTML, so you should make sure the PHP script doesn't show errors
You can suppress warnings for mysqli constructor (which I think is the one causing the problem) by prepending the at (#) sign:
...
#mysqli(...)
...
There are other ways of avoid showing errors, check http://php.net/manual/es/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/es/errorfunc.configuration.php#ini.error-reporting

Better way to response to AJAX from php

I have one javascript file which sends AJAX request to php file, which fetch some data from database. If php finds any data it return it as json object in response, but when it does not find any recrod in database based on query, it return a message something like "not match found".
It means javascript either get string message in "not match found" or json object.
I am trying to check if xmlhttp.responseText is json object or a string, but have not been succedeed. Any idea about how to solve this problem?
Should I convert "not match found" string into a json and send back to javascript and then parse it or there is any better way to solve this?
Thank you
BR
I don't think you need to parse your error message "No match found". There's two options: either create an if/else statement in the PHP file that the ajax calls, or you can attempt to encode the JSON in the php file and if it's unsuccessful, you can just write out a "No match found" message in the error part. I highly recommend using the $.ajax call because it can handle the responses better.
JS
$.ajax({
url: "myFile.php",
dataType: "json",
success: function(data) {
var myNewJsonData = data;
alert(myNewJsonData);
},
error: function() {
alert("No match found.");
}
});
PHP (myFile.php)
<?php
//Do your query business and stuff here
//Now let's say you get back or store some array that looks like this for example
$myArray = array('name' => 'Mike', 'age' => 20);
/* Now attempt to create a JSON representation of the array using json_encode() */
echo json_encode($myArray);
?>
When you echo it out, it gets sent back through either the $.ajax's call success or error function as a parameter (which I named data), depending on whether or not there was an error reported back. If there was not, then success is called, and if there is an error, well then you can guess which one gets called. json_encode will create a JSON representation of the array of data that you get back from your query.
Maybe I'm not understanding your question, can't you just print out an error using something like this:
$.ajax({
url: "myphpfile.php",
dataType: "json",
success: function(data){
alert(data.info);
},
error: function(xhr, status, error) {
alert(status);
alert(xhr.responseText);
alert(xhr);
}
});
Then do something inside of the error block?
Even though I totally agree with Patrick Q's comment, there is another option that has not been mentioned. You could also set the Content-Type of the response to indicate if it's json or text:
#header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
and
#header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) );
or even,
#header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
Then you could check the response's content type to make a decision:
$.ajax({
type: "POST",
url: "xxx",
data: "xxx",
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//do something
} else
if (ct.indexOf('json') > -1) {
// handle json here
}
}
});
A.

JSON response from Python json.dumps

I am trying to send a Django HttpResponse encoded as JSON to Javascript.
Python:
response_data = {}
response_data['status'] = 'incomplete'
return HttpResponse(json.dumps(response_data), content_type="application/json")
Jquery:
function auth_request(){
$.ajax({
url: AUTH_ENDPOINT + "myid0001",
context: document.body,
success: function(response){
console.log(response);
console.log(response.status);
if(response.status == "incomplete"){
//do something here
}
}
}
});
}
The console prints {"status": "incomplete"} for the first console log and undefined for the console.log function accessing the status element.
I tried using JSON.parse(response) but I get the error
Uncaught SyntaxError: Unexpected token a in the jquery.js file which I believe is indicating that the object is already a JSON object. However, if I check the type of the object, it displays string. How can I access the elements of the response JSON object?
You need to parse the Json back into a JS object when it's received. Otherwise, it's just text.
jQuery will do that for you if you specify dataType: "json" in the Ajax call.
I found the solution. It turns out that my Django setup was returning some additional string items so when I tried to set dataType: "json" (as #Daniel Roseman suggested) or in the jQuery function or use JSON.parse(response) I received an error. I was able to remove the extra string and it worked properly.

Using AJAX to call a php function keeps failing

im having a problem trying to get an ajax call to trigger a php function and then return successfully. As far as i can see my syntax is correct.
But all i get back is failed! Any ideas?
EDIT
I have changed my AJAX request to send without using data, just to rule out that being a problem and i have implemented some of the things people suggested below but to no avail, heres what my 2 files look like now:
ship.js:
function set_ship()
{
//var datastring = {'ship':'true'};
$.ajax({
type:'POST',
url:'soap/classes/class.ship.php',
success: function(success){
alert('success');
},
error: function(fail){
console.log(fail);
}
});
}
And my PHP class.ship.php:
<?php
var_dump("hello");
header('Content-type: application/json');
echo json_encode(array("result"=>"true"));
From the var_dump on my PHP script i can see that the class.ship.php isnt even being called for some reason.
Thanks
Please try this
json_encode(array("result"=>"true"));
because
json_encode(true) // will return just "true" which is not a valid json
Also try serializing the dataString , by doing
data: datastring.serialize();
lowercase JSON_ENCODE
success: function(success), error: function(fail)
check what is returned in network tab of firebug.
You need to set the content header to json header('Content-type: application/json'); and make sure you request return only json coz ajax is waiting only for "JSON" and it will throw parse error
if(isset($_POST['ship']) && $_POST['ship'] == "true"){
$result = "result";
header('Content-type: application/json');
echo json_encode(true);
}
I would suggest that you check what it being actually returned by the server.
The error callback receives one argument representing the xhr object, so you can inspect that directly by placing a breakpoint or using console logging, like this
error: function(xhr) {
console.log(xhr);
}
Likewise, the success callback receives three parameters: the status, the returned data and the XMLHTTPRequest Object, so you can check those in the very same way:
success: function(status, data, xhr) {
console.log(status, data, xhr);
}
You should look for the response status code and the response text in the xhr object to understand what is going wrong. If you're seeing a 200 OK response status, the data returned from the server is probably not being interpreted correctly as JSON data, so you should try setting the response header server side to application/json.
An error might occur also if something else is appended or prepended to your response. This happens especially when warnings occur in the code before returning and you have error reporting set to ON.

Ajax request returns 200 OK, but an error event is fired instead of success

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

Categories

Resources