Jquery suddenly unable to drill into json? - javascript

I have a weird scinario. I have been using $.ajax() to make ajax calls to my server for data and have been using the same sort of format for these server calls. All has been going fine but suddenly I wrote a function and returned a JSON object that jQuery is unable to drill into. I looked at it in Firebug and everything appears normal. Can someone help me here to understand why suddenly I am unable to drill into this particular data object?
Here is the ajax code:
$.ajax(
{
type: "GET",
url: "php/getoptions.php",
dataType: 'json',
data: 'id='+id,
success: function(j)
{
alert(j.isdefault);
}
});
when I try to do this, the alert gives me "undefined." I have tried "alert(JSON.stringify(j))" and I see the valid json being returned. I have even taken the json that I saw in Firebug and run it through JSONLint and it returned valid.
Here is a sample of the json coming back:
[{"isdefault":"1","option1":"1","option2":"0","option3":"0","option4":"1","option5":"1"}]
WHAT IS GOING ON? Why can jQuery suddenly not drill into this data set?
thanks!

You need...
alert(j[0].isdefault);
...because the object that has the isdefault property is at index 0 of an Array.

Related

Chrome not consoling JS object completely

I am making an AJAX post request with response in JSON.
My ajax code is
$.ajax({
type: "POST",
url: "admin/vendors_post.php",
data: "vendet_req=fetch&venid="+sel_ven,
dataType: 'json',
beforeSend: function(){
$('#trans_loader').css("display", "table");
},
success: function(response){
console.log(response);
}
});
Consoling the object shows
When consoled object is explored
The problem is that, the object that I have received in response is not showing some object properties when explored. But when I try to call them explicitly using the dot notation, I get the proper value. I wasted my time looking for those few variables that were not shown when I console the whole response object. For reference, the properties 'id', 'com_name', 'cat_name', etc are not displayed when the console object is explored (refer attached image number 2 above).
What can be the issue? Why the object was not consoled with all properties? I am using jQuery 2.2.0. And using php 5.4.31 on the server side.
NOTE: The object size as per JavaScript is 24, while the actual size, sent from the server, is 29. Though I am able to access those 5 properties explicitly. I am sending data from php post file after 'json_encode()'ing.
Adding my comment here, so it's easier to find from the references:
If there's a data transformation between the console.log() and when you expand the items in the console, this can happen.
When the data is logged to the console, it's the state you are after, however if anything changes your data throughout the code, the entry in the browser's console will refer to the updated values.
Yes. #Alex is correct. #Yogesh try to avoid that function call and check the console.
This has nothing todo with jQuery or PHP, it's how Chrome works.
2 things to notice:
In Chrome when you use console.log on an object, it shows only the first 5 properties without sorting them. When you expand the object, it shows all the properties sorted alphabetically.
As #Alex Szabó said, if the object properties changed after using console.log(), the expanded object will display the current properties by the time of expanding.
Please try using
console.log(JSON.stringify(response))

JSON GET returns HTML when called from code/console but returns JSON object when called from web address

I am trying to run this code:
$(document).ready(function () {
$.ajax({
url: 'http://foodfetch.us/OrderApi/locations',
type: 'GET',
success: function(data){
alert(data);
//do work here
}
});
});
For some reason, the AJAX call returns HTML source code, not the JSON object that it should be returning. If you copy the URL into any web browser, the JSON object shows up in plain text.
Can anyone explain what silly thing am I doing wrong here?
As Patrick Evans has pointed out in the comments, the URL in the code links to a page with an embedded frame, I was able to get the code working by using the URL that the frame links to.

Ajax request, fetch JS array and make it available

I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.

Bad formatting in JSON ajax response

I am having some odd problems with data coming back from a jquery Ajax call that I cannot figure out.
I have a c# asp.net web page that binds a valid JSON data blob to the UI with client side JavaScript on page load. This part works just fine. I set up a jquery Ajax post back that returns the same data and calls the same JavaScript data binding method, and this throws an error when I attempt to bind the data. It looks like the JSON written to the page on load is properly treated as a JSON object, but the data returned by the ajax call isn't.
Here is the ajax call:
jQuery.ajax({
type: 'POST',
data: "{'move_list': '1-2,3-2'}",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
url: 'Puzzle.aspx/ProcessMove',
complete: OnComplete,
success: function(data){BindData(data);},
error: OnError
});
Here is a sample of the JSON data that is being processed:
{"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]}
Here is the code that loads the data when the page is first loaded:
<script type="text/javascript">
// method returns JSON object above.
// client side code appears like this:
// BindData({"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]});
BindData(<%=Game.SerializeToJson()%>);
</script>
and finally, the JavaScript binding function:
function BindData(data)
{
try
{
document.getElementById("square1").className = data.game[0].color;
// much more of the same....
}
catch(exception)
{
alert(exception.message);
// error thrown here is 'data.game is undefined'.
// the data object is being treated like a string and not a JSON object.
// so the indexing into the object fails.
}
}
I have double checked the JSON data with several online JSON parsers, and the data is formatted correctly. The server side code generates the same output in either case.
I tried to change the jquery Ajax call to...
success: function(data){BindData(JSON.parse(data));},
...to see if it was just treating the returned data as a string as opposed to a JSON object, but that just generates this message:
SyntaxError: JSON.parse: unexpected character
BindData(JSON.parse(data));
Completely stumped by this one. I have been reading everything I can find and trying all sorts of things, but nothing seems to work.

jQuery ajax method with dataType 'json' incorrectly parsing json data

I'm having some inexplicable behaviour using jQuery 1.4.2, and I'm beginning to think that it might be a safari problem, not a jQuery one. Let me explain.
I began simply enough by using .getJSON like this:
$.getJSON("/challenge/results", form_data, function(data){
//I know console.log is bad news, just a simplification.
console.log('data', data);
}
And the log gave me something along the lines of
>locations: Array (1)
While I was expecting an array of size 2. So I had a look at the json in the response:
{"locations":
[{"customer_id":2,"editable":true,"id":971,"latitude":43.659208,"longitude":-79.407501,"max_zoom":25,"min_zoom":9,"name":"test"},
{"customer_id":3,"editable":true,"id":974,"latitude":36.746944,"longitude":-107.970899,"max_zoom":25,"min_zoom":9,"name":"test2"}]}
I've simplified this considerably for the sake of clarity, but as far as I can tell, the json received is perfectly valid (generated programmatically through rails). [Update: JSONLint confirms this hypothesis.]
I was surprised by this, so I converted my request to a $.ajax request to see if there was some subtle difference between them (since then, looking in the source of jQuery I see that $.getJSON simply calls $.ajax).
$.ajax({
url:"/challenge/results",
dataType: 'json',
data: form_data,
cache:false,
success: function(data, textStatus){
console.log("data!", data, textStatus);
});
But alas! The same response:
locations: Array (1) success
At this point, I must admit - I was getting a bit silly, so I thought I would try something completely bound to fail:
$.ajax({
url:"/challenge/results",
dataType: 'text',
data: form_data,
cache:false,
success: function(data, textStatus){
console.log("Parsed:!", $.parseJSON(data), textStatus);
});
Much to my surprise my console read:
locations: Array (2) success
I was stumped. At this point I dug in my heels and took a long hard look at the jQuery source (1.4.2). I suppose unsurprisingly, the ajax function seems not to handle the json parsing itself (although, I must admit, I can't be sure).
I'm totally at a loss for why this could be happening - any help is appreciated.
Perhaps I missed something, but I notice that your JSON is an object that has a single property ("locations") with an array as it's value. Have you tried:
$.getJSON("/challenge/results", form_data, function(data){
//I know console.log is bad news, just a simplification.
console.log('data', data.locations);
}
try this:
// Enables for all serialization
jQuery.ajaxSettings.traditional = true;
// Enables for a single serialization
jQuery.param( stuff, true );
// Enables for a single Ajax requeset
$.ajax({ data: stuff, traditional: true });
hey,your problem seems like to be have something to do with the nested param serialization.just as what the jQuery 1.4 release note say:
Query 1.4 adds support for nested param serialization in jQuery.param, using the approach popularized by PHP, and supported by Ruby on Rails. For instance, {foo: ["bar", "baz"]} will be serialized as “foo[]=bar&foo[]=baz”.
In jQuery 1.3, {foo: ["bar", "baz"]} was serialized as “foo=bar&foo=baz”. However, there was no way to encode a single-element Array using this approach. If you need the old behavior, you can turn it back on by setting the traditional Ajax setting (globally via jQuery.ajaxSettings.traditional or on a case-by-case basis via the traditional flag).
The Webkit inspector's debugger should be used instead of console logging, which can show the object in a future state. This was the cause of this problem as the list was being trimmed in code after the console.log line, which resulted in the unexpected behaviour.

Categories

Resources