executing ajax success function- jQUERY - javascript

I've searched around for this error and none of the solutions appear to help me with what I am getting. I am doing an ajax request, and I am trying to retrieve the json output released by the server. I can print out the json that i am trying to capture (via console.log()) not process it in the jQuery.parsejson(). I keep getting a "Uncaught SyntaxError: Unexpected token o" error. Please can someone advise?
my code:
// Make ajax request
$.ajax({
url: 'http://localhost/multipleFileUpload_adam/webservice/delete_pdf.php',
data: {delete_array: jsonString},
dataType: 'json',
type: 'POST',
success: function(data){
console.log(data);
var x = jQuery.parseJSON(data);
},
console.log(data) gives the following ( am trying to retrieve the 'success_deleted' array:
Object {success_delete: Array[2], unsuccess_delete: Array[0], input array: Object}
if I remove the line of code :
var x = jQuery.parseJSON(data);
Then I am able to get the console.log(data) to work. if i add it i get the error mentioned above.

This line:
dataType: 'json',
tells jQuery to ignore the content-type returned by the server and always parse the response as if it was JSON.
Then:
success: function(data){
The JavaScript value (which is an object) that you get from parsing the JSON is passed into data.
This line:
jQuery.parseJSON(data);
Takes the value of data (an object)
Converts it into a string (which will be "[object Object]")
Tries to parse that string as JSON (which it isn't).
Then I am able to get the console.log(data) to work. if i add it i get the error mentioned above.
Yes. That is the expected behaviour. Don't do that. Just work with the already parsed data in data.

there is a parse error because data is already an object so it is expecting json and getting Object. 'O' is the unexpected character. Try without the parseJSON function.

Related

AJAX JSON "string" returns null in Javascript/Console

I have a very large dataset (30,000+ rows) as JSON getting returned via an Ajax call in my script.
However, when the data returns, just one property of the returned objects is wrong.
A property called date is returning null in the Javascript/Console log, but if you go to the Chrome response returned from the Ajax call, the date is a string as intended.
Any reasons why this string would be parsing to null in the response?
My code:
$.ajax({
...
dataType: 'json',
success: function (json) {
console.log('This is literally the first line:', json);
...
},
...
});
This is what the data "should" look like (this screenshot is from the "Network" tab of Chrome, it is the "Preview" of the request):
And yet this is what Javascript returns in Console/scripting:
Any help would be amazing.
Cheers.

Request issue: Uncaught SyntaxError: Unexpected token /

I am developing i small app that displays some JSON data
inside of a listview. To receive the data I am using a simple request.
And I am getting always the same issue:
Uncaught SyntaxError: Unexpected token :
my code:
$.ajax({
url: 'http://localhost/documents.json',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
// do something with the data
},
type: 'GET'
});
});
My JSON file is valid. I checked it with a JSON validator.
Invalid JSON (no matter how mangled) cannot generate a JavaScript syntax error if you parse it with JSON.parse() or any decent dedicated parser (and that's what jQuery does). The same happens with all other standard data types (XML, HTML, plain text...). All symptoms suggest you're expecting JSONP but getting some other data type. The builtin browser network pane should reveal what you're getting exactly.
Whatever, if you only want JSON and nothing but JSON you should simplify your code as follows:
Omit protocol and host:
url: 'http://localhost/documents.json',
should be:
url: '/documents.json',
(Probably not required, but will help to void errors.)
Ask for the correct data type:
dataType: 'jsonp',
should be:
dataType: 'json',
Do not parse again what jQuery already parsed for you:
var json = $.parseJSON(data);
should be:
var json = data; // Yeah, nothing :)
This should be enough for local AJAX. If you really need a cross-site request (I asked twice and never got an answer) you have to tweak your server to either return the appropriate CORS headers or implement JSONP data type and change your client-side code accordingly because you'll no longer have JSON—because JSONP is not JSON!
Check if your json is valid by using jsonlint.com or you can use jsonmate.com. These are very helpful to me when I'm debugging json.
Also - it would help to have a link to the full code. Use jsfiddle.net to put your code into - then link it to this post. This will help the community debug your code.

Why do I get Uncaught SyntaxError: Unexpected token ILLEGAL

I want to use AJAX and the SoundCloud API to get the tracks of a user.
jQuery.ajax({
url: 'http://api.soundcloud.com/resolve?url=http://soundcloud.com/[SOME USER]/tracks/&format=json&consumer_key=[MY KEY]&callback=?'
, dataType: 'jsonp'
, success: function( data ) {
console.log( data );
}
});
I can see that chrome gets the json data but I get the error
Uncaught SyntaxError: Unexpected token ILLEGAL
in the console.
The issue is probably that the json file is an json array. Could that be the error?
And if yes, how can I convert the array into single objects?
The problem is that the description field in track id #159500192 ('Summer Chords Pt. 2' (Electro House Mix)) has invisible characters that are not legal inside of JavaScript strings, so the JavaScript parser chokes when trying to the run the JSONP response as a script. SoundCloud should encode these values when serving content via JSONP.
Because SoundCloud supports CORS, you don't need to use JSONP at all. You can simply request the file directly, by removing the callback=? parameter and using dataType: json (not jsonp):
jQuery.ajax({ url: "https://api.soundcloud.com/resolve?url=http://soundcloud.com/[USER]/tracks/&format=json&consumer_key=[KEY]",
dataType: 'json',
success: function(d) { console.log(d); }
});

Ajax response succeeds, but cannot use data (Uncaught SyntaxError: Unexpected identifier)

I am trying to retrieve data from a web service using an ajax call. The call is succeeding, because I am able to successfully print the data in the console using console.log(). However when I attempt to take my data, and convert from a string into an array, the code fails. I am currently trying to use eval, but have also tried to use JSON.parse. Both fail with an error of Uncaught SyntaxError: Unexpected identifier. Any ideas on how to get around this?
$.ajax({
type: "POST",
url: (redacted)
data: (redacted)
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response.d);
var data = eval("[" + response.d + "]");
This is where my code fails. Like I said, console.log(response.d) works, with an output simlilar to this: { 'code':'1234', 'description':'Record 1'}, { 'code':'1234', 'description':'Record 2'}, { 'code':'1234', 'description':'Record 3'}
Is my problem the use of eval? Any input would be greatly appreciated
First, I would use JSON.parse() here instead of eval for decoding JSON strings.
However in this case I believe the return data has already been decoded by jQuery. console.log(response.d) returns a nice looking object and not a "{...}...." string correct?

JSON.parse not parsing Json string. Serializing with JavaScriptSerializer

I have a serialized string comming from the controller to a view:
Controller:
var serialize = new JavaScriptSerializer();
return Json(new
{
data = serialize.Serialize(obj)
}, JsonRequestBehavior.AllowGet);
Json string:
[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},
{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},
{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]
As far as I know, modern browser should be able to parse that string with a simple
Json.parse()
View:
success: function (data)
{
$('.dinamic').remove();
console.log(data);
var obj2 = JSON.parse(data);
console.log(obj2);
}
I am able to see that string in the first console.log, but I get nothing from the second.
Is there any thing else I should be looking at because all the post I have read people only do it as simple as it is with a single JSON.parse.
I am using latest version of google chrome ,firefox and IE so it should work.
Although your success function is not shown in context of the other AJAX options being given, I would guess you are passing a dataType option of "json", or are using $.getJSON or something similar.
If that is the case, jQuery has already parsed the JSON for you by the time it passes it into success so you do not need to (and cannot) parse it again. You can simply use your data structure (data[0]. indiceName and etc).
(The below code is running live at http://jaaulde.com/test_bed/GuilhermeLongo/ )
Consider the following PHP (stored in json.php):
<?php
exit('[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]');
And the following JS:
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json',
success: function (data) {
console.log(data[0]);
console.log(data[0].indiceName);
},
error: function () {
throw new Error('AJAX request error occurred.');
}
});
</script>
It results in the following outputted log info:
GET http://jaaulde.com/test_bed/GuilhermeLongo/json.php
200 OK
99ms
jquery.min.js (line 3)
Object
{indiceName="Caracter", indiciId=24, indiceId=1, more...}/test_...eLongo/
(line 8)
Caracter

Categories