How to parse Json object in Jquery - javascript

I have a little experience in JSON I did it on my Android application now using JSON again in my webpage as AJAX reponse, I did research about ajax and found a tutorial to get my data in database using JSON so I tried but I didn't know how to parse the object.
My Jquery Code.
$.ajax({
type: 'GET',
dataType: 'json',
url: 'functions/json.php',
success: function(response){
var json = $.parseJSON(response);
alert(json.firstname) //where my response is $response['firstname']
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
}
});
Using the php I echo the jsonArray as json_encode and heres the json output
{"id":"2","firstname":"john","lastname":"Doe"}
using google chrome console i got this error
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
when the function response output as alert(reponse)
output was
[object Object]

Don't parse it. You've told jQuery to:
dataType: "json"
So response is the parsed object, not JSON. Just use it directly:
$.ajax({
type: 'GET',
dataType: 'json',
url: 'functions/json.php',
success: function(response){
alert(response.firstname);
},
error: function(data) {
// `data` will not be JSON
}
});
Also note that the first parameter to the error callback will not be JSON or the result of parsing JSON in the error callback.
See the documentation for details.

Related

Uncaught Syntax Error Unexpected token : , but the server received a valid json object from the server

I am trying to do a GET request to solr search engine using $.ajax() from jQuery. This is the code I am using for doing an ajax call:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
So I am getting a valid json object in the response but somehow the browser throws an Uncaught Syntax Error. The actual error is:
Uncaught SyntaxError: Unexpected token :
select?indent=on&q=myparam:value&wt=json&callback=…....somevalue...
The tricky part is that the response header is text/plain when I checked in the browser. How can I solve this? Please help me...
Colons require encoding in query strings.
Your url should look like this:
http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam%3Avalue&wt=json
If you're generating the query string dynamically, use encodeURIComponent() to correctly encode special characters.
I got this solved. Actually I had to use jsonpCallback:"mysuccesscallbackfunction" in the ajax call and json.wrf=mysuccesscallbackfunction in the URL. It looks like this now:
$.ajax({
url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=myparam:value&wt=json&json.wrf=mysuccesscallbackfunction',
type: "GET",
dataType: "jsonp",
jsonp : "callback",
jsonpCallback:"mysuccesscallbackfunction",
success: function(data) {
console.log("Success", data);
},
error: function(data) { alert("Error"); }
});
and my mysuccesscallbackfunction is:
function mysuccesscallbackfunction(resp) {
console.log('inside mysuccesscallbackfunction: ', resp );
}
Now, first it executes whatever is inside mysuccesscallbackfunction and then goes to default success callback. I found it somewhere on web. I would still like to know why it worked now.

Reading JSON data with jquery. Uncaught SyntaxError: Unexpected token :

I'm trying to read JSON data using jquery. Specifically I'm trying to read the JSON from this url: http://mkweb.bcgsc.ca/color-summarizer/?url=http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10643840_701797013239098_657737630_a.jpg&precision=low&num_clusters=3&json=1&callback=?
However I keep getting this error:
Uncaught SyntaxError: Unexpected token :
Here is my jquery:
$(document).ready(function () {
var one = "1"
$.getJSON('http://mkweb.bcgsc.ca/color-summarizer/?url=http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10643840_701797013239098_657737630_a.jpg&precision=low&num_clusters=3&json=1&callback=?', function(result) {
document.write(result.clusters.one.rgb[0]);
});
});
I'm getting the error at the very first colon in the JSON code.
From what I understand, the JSON data is actually being read as Javascript. How can I fix this.
Reading the API Docs I found that you need to specify a jsnop=1 parameter in order to retrieve data via JSONP.
Tthe correct code would be something like this:
$(document).ready(function () {
$.ajax({
url: 'http://mkweb.bcgsc.ca/color-summarizer/',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'colorsummary',
data:{
url: 'http://scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10643840_701797013239098_657737630_a.jpg',
precision: 'low',
num_clusters: '3',
jsonp: '1'
},
success: function(result){
document.write(result.clusters['1'].rgb[0]);
}
});
});
I also structured the request so you can change parameters easily.
PS: watch out with that JSON notation ( the ['1'] in clusters and so)

Cross Domain Ajax get Request

I'd like to ask a question for cross-domain Get request via Ajax.
My ajax request is Like that
var currency_path="http://forex.cbm.gov.mm/api/latest";
$.ajax({
url: currency_path,
crossDomain:true,
type:"GET",
dataType:'jsonp',
async:false,
success: function(data){
console.log(data);
},
error: function(){
alert('failure');
}
}).done(function(msg) {
console.log(msg);
});
I got the response but i can't trace that
Any Suggestion ?
Look in your JavaScript error console:
Uncaught SyntaxError: Unexpected token :
You have dataType:'jsonp', but the URL is returning JSON.
You can't parse JSON as JSONP, there are different data formats.
Use some other technique to access the data.

SyntaxError: missing ; before statement jquery jsonp

I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON

jQuery Handling JSON responses

I have the following from the server response:
{"invalid_emails":["adsasdasd"],"result":"success","valid_emails":["jobs#apple.com"]}
But this errors?
$.ajax({
type: 'POST',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(e) {
jsonObject = jQuery.parseJSON(e);
jsonObject.valid_emails
jsonObject.invalid_emails
I get the following error: Uncaught TypeError: Cannot read property 'valid_emails' of null
As Jason and Jonathon mentioned, you should not manually deserialize the JSON. Depending on what version of jQuery you're using, jQuery will automatically deserialize JSON based on the response's content-type header. So, you're probably trying to $.parseJSON() something that's already an object, not a JSON string.
To be sure that jQuery does this automatic deserialization for you, add a dataType parameter to the $.ajax() call:
$.ajax({
type: 'POST',
dataType: 'json',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(response) {
console.log(response.valid_emails);
console.log(response.invalid_emails);
}
});
You may not have to parse that JSON, as it is already a JSON object. try doing
var emails = e.valid_emails;
If this still does not work, include dataType: 'json' in your .ajax() declaration.
If your server responds with the JSON then you should have to run jQuery.parseJSON(e);. The e parameter might already be the about so try this for your success handler:
success: function(e)
var valEmails = e.valid_emails,
invalEmails = e.invalid_emails;
};
Just try including
dataType: 'json',

Categories