1

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]
asked Apr 8, 2017 at 14:37
0

1 Answer 1

6

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.

answered Apr 8, 2017 at 14:38
Sign up to request clarification or add additional context in comments.

3 Comments

thanks you so much new in ajax best answer but i'll wait till 12mins :)
{"success":true,"message":[{"id":"2","firstname":"john","lastname":"doe"},[{"id":"3","firstname":"jane","lastname":"doe"}]} using multiple array how would i echo this?
@RaizeTech: I only see one array in that. To loop through that array (which is response.message), use any of the techniques covered in this question's answers, such as response.message.forEach(function(entry) { alert(entry.firstname); });

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.