Debugging invisible JSON errors using php encoded variables, parsed with jQuery - javascript

I'm using php json_encode to send a bunch of values to a client, where jquery
{"data":{"application":{"basics":{"email":"jepp#mily.com","name_first":"Step","name_last":"Bob","phone":"9210938102938","occupation":"unemployed","website":"wwwcom"},"application":{"title":"Default title","guid":"9as8ua9sd8ua9sdu","language":"sv"},"job":{"title":"joburl","url":"joburl"},"letter":{"letter":"abadbabkbakbakbakbakbakbabk"},"work-experiences":[{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"}],"educations":{"title":"Default Education","url":"ixi","date_from":"1970-01-01","date_to":"1999-12-31"},"skills":{"title":"Defailt SKILL","url":"wwwsdcom","date_from":"ixi","date_to":"ixi"},"work-samples":{"title":"A sample of my work","url":"wwwsdcom","date_from":"ixi","date_to":"1999-12-31"}}},"error":[],"warning":[]}
If I try to parse this with $.parseJSON in a script I get no object. However, if I copy/paste it directly into the console (and add ' in the beginning and end), it works. There are no error codes and I can see no linebreaks. JSON lint-tools returns no errors...
I have set the correct content type and tried the different json parsers that jquery provides.
What have I missed?
The code was cut/pasted from the jQuery tutorials. I tried some different examples but they all failed.
var jqxhr = $.getJSON( "application_controller.php", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function(data) {
console.log( "complete" );
application = data;
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function() {
console.log( "second complete" );
});
});
It's true, I decoded it in the console. this is a snippet that does in in-script (it also won't work):
$.ajax({
dataType: "json",
contentType: "application/json",
url: 'application_controller.php',
data: '{id:id}',
success: function( data ) {
application = data.responseText;
application = $.parseJSON(application);/* < string */
},
fail: console.log("fail"),
complete: function(data) {
console.log(data.responseText);
application = data.responseText;
}
});

Answering my own question:
To solve this error I had to change all my php files from "utf8" encoding to "utf8 without BOM". Then it worked.
When a file without utf8 encoding was included (low in the hierarchy of course) it tainted all the other files and corrupted the output.

use JSON.parse(jsonString) function.
var jsonString = '{"data":{"application":{"basics":{"email":"jepp#mily.com","name_first":"Step","name_last":"Bob","phone":"9210938102938","occupation":"unemployed","website":"wwwcom"},"application":{"title":"Default title","guid":"9as8ua9sd8ua9sdu","language":"sv"},"job":{"title":"joburl","url":"joburl"},"letter":{"letter":"abadbabkbakbakbakbakbakbabk"},"work-experiences":[{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"},{"title":"Default WORK Experience Title","url":"wwwsscom","date_from":"1970-01-01","date_to":"1999-12-31"}],"educations":{"title":"Default Education","url":"ixi","date_from":"1970-01-01","date_to":"1999-12-31"},"skills":{"title":"Defailt SKILL","url":"wwwsdcom","date_from":"ixi","date_to":"ixi"},"work-samples":{"title":"A sample of my work","url":"wwwsdcom","date_from":"ixi","date_to":"1999-12-31"}}},"error":[],"warning":[]}';
var myData = JSON.parse(jsonString);
Fiddle

Related

How to iterate with javascript a json response from symfony2

i want to itarate a json response from symfony and put it in a table td>
my action :
$search = $this->getDoctrine->...;
$serializer = $this->get('serializer');
foreach ($search as $key => $value) {
$search[$key] = $serializer->serialize($value, "json");
}
$reponse = new JsonResponse($search);
return $reponse;
this is what i have in my twig ( i examine it with Firebug ):
i have a to display at least something but sometimes i have undefined or nothing ... this my javascript function
$(document).ready(function () {
var dataString = $("form").serialize();
var typerequest = $("form").find('input[name="typerequest"]').val();
$('#filtreperseance').ajaxForm({
type: "POST",
url: Routing.generate('myroute'),
data: dataString,
success: function (response) {
$.each(response, function (cle, valeur) {
$("#test").html(valeur);
});
}
});
});
EDIT 1 : Console.log
EDIT 2 :
I'd try to cut down the problem. First make sure, the JSON is valid and looks the way you expect. Don't use jQuery at this point. Call the symfony controller in your browser directly. Then check the json. http://jsonviewer.stack.hu might be of use.
Once you verfified that the JSON itself is valid and contains what you need, we can look at the jQuery part. Then we'd need the code and the errors you get.
i have done a mistake when i returned the JSOn from Controller . its Ok now

Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript

In a webpage that uses javascript, I pass data to a hidden input field using
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
and then later access that data using
waypts_input = $.parseJSON($("#waypt_sel").val())
This works, except that sometimes it gives a
Uncaught SyntaxError: Unexpected end of input
. I tracked the error to this line with the json parsing. but I am baffled because this works sometimes but sometimes it doesn't for the same, identical string.
I checked the values that are passed to the html inputs and it works and doesn't work for the same values.
Here's an example of the json string I am passing:
"[{\"location\":\"8.3353156, 80.3329846\",\"stopover\":true}, {\"location\":\"8.0326424, 80.7446666\",\"stopover\":true}, {\"location\":\"7.9577778, 80.667518\",\"stopover\":true}, {\"location\":\"7.953208, 81.006675\",\"stopover\":true}, {\"location\":\"7.885949, 80.651479\",\"stopover\":true},{\"location\":\"7.2905425, 80.5986581\",\"stopover\":true},{\"location\":\"7.300322, 80.386362\",\"stopover\":true}]"
Here's the structure of the code I use.
$(document).ready(function() {
$.ajax({
url: "aa.php",
type: "POST",
data: {
id: selected_i
},
success: function(result) {
itins = $.parseJSON(result);
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
}
});
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function(result) {
locations = $.parseJSON(result);
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
waypts_input = $.parseJSON($("#waypt_sel").val());
waypts_json_input = $.parseJSON(waypts_input);
//other code
}
}
});
And here is the detailed error message I get on firefox developer edition browser.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
calculateAndDisplayRoute() map.js:366
initializeMap() map.js:290
.success() map.js:62
m.Callbacks/j() jquery-1.11.3.min.js:2
m.Callbacks/k.fireWith() jquery-1.11.3.min.js:2
x() jquery-1.11.3.min.js:5
.send/b() jquery-1.11.3.min.js:5
Thanks in advance.
"\" is unnecessary when deserialize json string in javascript .
what json tools you used?
you serialize in one tool , and deserialize with other , may get this scene .
The issue was that I was using an asynchronous ajax request to retrieve json data. by the time the data had been retrieved and pasted to the html, the execution of the code that used the html data had happened, and thus gave an error. I used a callback function for the ajax query and this did the job.
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
and in the code where this is called:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
Alternatively you may also try async: false in the ajax query parameters. But this can cause browser freezing and is not recommended.

Parsing JSON returns cryptic error

I have some JSON (https://gist.github.com/tekknolagi/8526671) that I am requesting for a list of my blog posts.
I got some funky errors in the console:
And also in JSONLint:
I cannot figure out what's wrong. My code:
$(document).ready(function () {
$.ajax({
url: '/posts.json',
type: "GET",
dataType: "text",
success: function(data) {
// data = data.replace(/(\r\n|\n|\r)/gm,"");
console.log(data);
var parsed = JSON.parse(data);
var parsed = data;
var names = []
for (var post in parsed) names.push(post.title);
console.log(names);
$('#page_holder').pagify({
pages: data,
default: null
});
},
fail: function (err) {
console.log(err);
}
});
});
And it always fails on the parse. This has been killing me for weeks.
The line that throws the error has this inside the string:
Type \"help\", \"copyright\", \"credits\" or \"license\"
\& is not a valid escape sequence in JSON strings values:
(source: json.org)
"Proof":
["\&foo"]
results in the same error
Since I don't know how the \ got there in the first place, it's not really possible to provide a solution. But to make the JSON valid, you have to remove those (or double them as Pointy pointed out (no pun intended)) (before you generate the JSON). A proper JSON library should actually take care of escaping the \ correctly.

Seems that no response received on getJSON

I am sending the jsonp request as:
var jsoncallback = "?jsoncallback=?"
$.getJSON( reportURL + jsoncallback, {
tags: "",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
alert( item );
});
});
I have put an alert to see if the request works. On server side, in node js file I am responding to request as:
..
console.log("request received");
response.writeHead( 200, { "Content-Type": "application/json" } );
..
response.end();
In the logs I can see that the request received. The problem is that no alert windows pops up.
What could be the reason to this?
I just reponse.writeHead(...) and (for testing reasons - just the head and end) response.end()
With the jsoncallback=? in the URL, jQuery is expecting a JSONP <script> as a response. For this to work, the server should at the very least write out the "padding."
That is a call to the function named by jsoncallback. And it won't be just ? -- jQuery replaces that with a pseudo-random function name along the lines of jQuery1910123456789_0123456789. For that, the response should at least be:
jQuery1910123456789_0123456789();
You'll need to get the value from the request.url:
var parsedUrl = url.parse(request.url, true);
var query = parsedUrl.query || {};
if ('jsoncallback' in query) {
response.write(query.jsoncallback + '();');
}
// ...
And, once you have data to output with it:
if ('jsoncallback' in query) {
response.write(query.jsoncallback + '(' + JSON.stringify(data) + ');');
} else {
response.write(JSON.stringify(data));
}
Have you confirmed the JSON is correctly formatted? Check it against http://jsonlint.com/.
From the getJSON() docs:
As of jQuery 1.4, if the JSON file contains a syntax error, the
request will usually fail silently.

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources