Jquery: JSON parsing always gets unexpected character error - javascript

I'm trying to parse data from the server. Though I'm working on a valid JSON, I always get the JSON unexpected character error.
Please consider this code:
var shows = $.parseJSON(fetchData('contentShows', this.id)); // Returns a valid JSON data
$.each(shows, function(index, value) {
console.log(value.id);
});
fetchData = function(dataRequest, id) {
var data = $.ajax({
url: '/shows.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(dataRequest);
console.log(data);
}
});
return data;
}
This is the sample JSON:
[
{"shows":[],"spool":"/home","name":"Test Name","id":2}
]

The problem is that your fetchData function doesn't return the JSON text, it returns a jqXHR object. (And so when you pass that into $.parseJSON, it gets turned into a string like [object Object], which is of course invalid JSON.)
The reason is that you set the data variable to the result of $.ajax call and return it. The return value of $.ajax is a jqXHR object.
But just changing that isn't sufficient, because the call is asynchronous; it completes after the function has already returned.
Your best bet is to modify fetchData to accept a callback, and then use the fetched data within the callback. Something like this:
fetchData = function(dataRequest, id, callback) {
$.ajax({
url: '/shows.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(dataRequest);
console.log(data);
callback(data);
}
});
}
Used like this:
fetchData('contentShows', this.id, function(showData) {
var shows = $.parseJSON(showData);
$.each(shows, function(index, value) {
console.log(value.id);
});
});

Related

Stumped why Javascript AJAX Success: JSON data is "invalid"

I'm stumped why my Flask called JSON data is not being read by ajax success wait statement that works very well elsewhere. I realize the Success: statement is supposed to wait for data to returned and it does, but then the data returned isn't accessible as any JSON. There are no console nor browser console errors to indicate why data is considered 'invalid'
Flask Function
#blueprint.route('/target_liner')
def target_liner():
ind_id = int(request.args.get('ind_id'))
label = "1508 Loss Correction"
data = '[{"Program_Name":"' + label + '"}]'
return data
JSON Data
[{"Program_Name":"1508 Loss Correction"}] // This is confirmed legal JSON
Javascript
function updates() {
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
console.log(data);
alert(data); // This shows the JSON string correctly in Chrome Inspect console
alert(data.Program_Name);
alert(data[0]['Program_Name']);
alert(data[0].Program_Name );
}
});
};
updates();
The data retuned is a String. You can either do a JSON.parse(data) after the success or you can use dataType: 'json' in your ajax request. you might get a parse error if your JSON String is not formed properly when you use dataType: 'json' .
You have three possibilities:
in your flask change return data to return jsonify(data);
add dataType: "json", to your ajax call as per comment by #Rocket Hazmat;
add to the succes response a conversion from string to json: data = JSON.parse(data);
$.ajax({
url: "/target_line",
method: "GET",
data: {
ind_id: 1508
},
success: function (data) {
data = JSON.parse(data);
console.log(data);
console.log(Object.keys(data[0])[0]); // print: Program_Name
console.log(data[0].Program_Name ); // print: 1508 Loss Correction
}
});

jquery ajax return function not working [duplicate]

I am sending a post data to get a json string back:
My JSON string:
{"error":false,"success":"Added Website","website_id":"12"}
My Ajax request:
$('.publsher_add_website').on("submit", function() {
show_loader();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
if (data.success == false) {
ajax_error(data.error);
hide_loader();
} else {
console.debug(data);
console.log(data.error);
console.log(data.success);
console.log(data.website_id);
location.href = site_url + "publisher/websites?added=" + data.website_id + "#modal-verify";
hide_loader();
}
},
error: function() {
hide_loader();
}
});
return false;
});
Now, when I go to use the returned data all of them are undefined.I have used:
console.debug(data);
Which returns the json string above, but if I try to access them individually:
data.error;
data.success;
data.website_id;
They all return as undefined Why is this? How can I fix it?
You haven't provided a dataType in your $.ajax, so AJAX treats the response as a string, not an object. So, inside the success function, do this first:
success: function(data) {
data = JSON.parse(data);
Try parsing your json string to a json object to get your values:
data = JSON.parse(data);

I am Unable to Parse a JSON in JQuery

I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});

How to set returned JSON Array to variable in jquery using AJAX

I'm trying to save my returned JSON Array to variable in jQuery.
I was looking for solution and I found this one:
var ajaxjson = [];
$.ajax({
async: "false",
dataType: "json",
url: "http://localhost:8080/mywebapp/getJSONFromCity",
data: {miasto: miasto},
success: function(result) {
ajaxjson = result;
}
});
also solutions from here: load json into variable, and here jQuery. Assign JSON as a result to a variable are not working for me:
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': my_url,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
AJAX call is working fine, I can show my 'result' data inside my success call, but I can't assign that data to variable any way. After that AJAX call my var is still null, when I'm trying to show some object from that, e.g. if I try to log "json[0].id" I get error " Uncaught TypeError: Cannot read property 'id' of undefined"
Any ideas how to fix it?
try
'success': function (data) {
json = $.parseJSON(data);
return json;
}

jsfiddle jquery ajax not returning data as expected

I'm trying to a jquery ajax call on jsfiddle but am having an issue:
var ajax1 = function () {
return $.ajax({
type: "post",
url: "/echo/json/",
data: {
name: "thomas!"
},
dataType: 'json'
});
};
var res = ajax1();
console.log(res);
prints an entire deferred object to the console. It includes responseText which I thought perhaps is what I should try to access, but I get undefined.
console.log(res.responseText);
I tried this once before with HTML and everything seemed to work, but the JSON is failing for some reason.
ajax returns a promise object, not the result of the ajax request. You need to register a success callback to get the value returned by the ajax request
It should be
var ajax1 = function () {
return $.ajax({
type: "post",
url: "/echo/json/",
//also the format for json request is as follows
data: {
json: JSON.stringify({
name: "thomas!"
})
},
dataType: 'json'
});
};
var res = ajax1();
res.done(function (data) {
console.log(data)
})
Demo: Fiddle
You are correct, JQuery returns a Deferred object instance.
You should therefore be calling done() on the object to get the data:
var res = ajax1();
res.done(function(data) { console.log(data); });
$.ajax() returns a jqHXR instance (which implements the Deferred pattern). When you return this from the function you are returning the jqHXR object. This implements a done() method which is passed a callback function.

Categories

Resources