Array of objects not getting parsed as javascript array of native objects? - javascript

I am receiving following data from server
"[{\"role_id\":\"1\",\"name\":\"administrator\",\"created_by_user_id\":\"2\",\"time_created_on\":null,\"is_user_based\":\"0\"},{\"role_id\":\"2\",\"name\":\"manager\",\"created_by_user_id\":null,\"time_created_on\":null,\"is_user_based\":\"0\"}]"
which is simply an array of two objects . Even after setting 'dataType' to json I am not receiving native javascript array inside my success callback function but if I use
$.ajaxSetup({
url:'/public/admin/role/list',
dataType:'json'
});
$.ajax({
success:function(data) {
alert(data[0].name); // alert box pop up as 'undefined '
var data = $.parseJSON(data);
alert(data[0].name) ; //works
}
});

Don't escape the ". They're required for JSON parsing.
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]

You have a trailing comma when setting dataType in your ajaxSetup method:
dataType:'json',
^
Also I hope those \ in the JSON you have shown here are not part of the actual response from the server. The response should look like this:
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]

Related

Retrieve JSON encoded data in AJAX callback

This is the result when I do console.log(data) within my AJAX callback
{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}
but when I do data['image'] or data['url'], it can't retrieve the value correctly. I also tried data[0]['image'] to no avail
So I guess data is returned from a ajax request. Your can use the following code to convert string to object:
data = JSON.parse(data);
If you are using jQuery to do the ajax request, you can add dataType: "json" to the ajax option. In this way, there's no need to convert data.
Your data in callback is JSON Object,then
var image=data.image;
var url=data.url;
have you tried data.image and data.url?
also try var x = eval(data);
then x.image and x.url
Be careful of eval() on untrusted data though!!
You need to parse it to Json
var retrieved = ......;
var json = JSON.parse(retrieved);
and then just use:
var image = json.image;
var url = json.url;
Usualy this code from jQuery API's page works great:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.
However, you must remember about the same origin policy as well as the about the correct server response's content type. For json response it should be application/x-javascript or at least text/json.
javascript does not have associative arrays, You should use a javascript object like
var data = JSON.parse(data)
and then you can acces it by
data.image and data.url
If You are getting string as a response then use like below.
var response = '{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}';
var data = eval("("+response +")");
console.log(data["image"]);
console.log(data["url"]);

submitting a form using $.ajax

I'm calling this function when the dom is ready on $().submit
but it seems not working there is no response from server
$(function(){
$("#logingform").submit(function(){
var values =$(this).serialize();
call_server("../php/login.php",values);
});
});
function call_server(URL,DATA)
{
$.ajax(
{
type:'POST',
url : URL,
data : DATA,
dataType:'json',
success:function(response){
$("#d1").append(response);
}
}
);
}
nothing seems to get back from the server.
server code
<?php
$email = $_POST['loginemail'];
$password =$_POST['loginpassword'];
echo json_encode(array('returned_val' => 'yoho'));
There is an extra semi colon following your ajax option:
data : $(this).serialize();,
vs correct
data : $(this).serialize(),
You do not need to parse the json that is returned, since you already have dataType:'json' defined in the ajax options.
$("#d1").append($.parseJSON(response));
That is not necessary.
If you want to show the response object as a string, then you need to stringify it instead:
$("#d1").append(JSON.stringify(response));
Also, you have a syntax error on this line:
data : $(this).serialize();,
Remove the ;.
Your data for a POST should be in json format, so rather than $(this).serialize(), use $(this).serializeArray() for your data. This will pass those values for POST body rather than in the querystring.

Parsing JSON returned via an AJAX POST formating issue

I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.

Why can I not parse json string using jQuery.parseJSON(json)?

I am trying to parse a response of a string which is a json string. In another page of my web app following code is working fine. but its not working for my current page i am working with. Following is the code:
$.ajax({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
success: function(result) {
alert('result: '+result);
var obj = jQuery.parseJSON(result);
alert('obj: '+obj);
// doing rest of stuff
}
});
first alert comes and shows right result. result is:
[
"Richard",
"Eric",
"John"
]
but second alert does not come.
i checked it, its a valid json. why can not i parse this json with jQuery.parseJSON(). Thanks in advance.
Try to add return type: dataType : json
$.ajax({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
dataType:'json',
success: function(result) {
console.log('result: '+result);
// doing rest of stuff
}
});
"json":
Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
http://api.jquery.com/jQuery.ajax/
Replace $.ajax by $.getJSON. This is guaranteed to trigger $.parseJSON internally, so result will already be the desired JS object.
$.getJSON({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
success: function(obj) {
alert('obj: '+obj);
// doing rest of stuff
}
});
Try with adding dataType:'text', it will return string as result. and your code will run as you expect.
See the accepted answer here
You're parsing an object. You parse strings, not objects;
jQuery.parseJSON only takes strings.
Because $.ajax already parsed the data, result is Javascript object not a string. parseJSON expects a string parameter.
FROM DOCS (more on .ajax() data types here):
The json type parses the fetched data file as a JavaScript object and
returns the constructed object as the result data. To do so, it uses
jQuery.parseJSON() when the browser supports it; otherwise it uses a
Function constructor
.

Error on my jquery ajax json function, wont return data

Hi iv got this error on my ajax function using json on retrieving data. It wont return any data. Here's my code below
$.ajax({
url: "php/getCategory.php?action=getyear",
cache: false,
dataType: "json",
success: function(data){
$.each(data.items, function(i,item){
$("#catYear").append('<option value="'+item.id+'">'+item.name+'</option>');
});
}
});
When i try to remove dataType: "json" it will pass into success: function. I think the problem is on my json. I also echo the output of my getCategory.php and i think their is no problem on it. Below is the output of my php json_encode.
{items:[{"id":"1","name":"2010"},{"id":"2","name":"2011"}]}
Thanks!
from jquery documentation :
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
so jour json string has element items which is not double quoted try something like that :
{"items":[{"id":"1","name":"2010"},{"id":"2","name":"2011"}]}

Categories

Resources