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))
Related
I am using the following code to make a request to a PHP script:
$.ajax({
method: "POST",
url: "myAPI.php",
data: {
orderById: 2,
action: 'returnStuff',
},
success: function(data){
$.each(data.data, function(key, value) {
var $targetToMove = $('.shape.'+value.attr_name);
//if element already exists on page, move it to the end of the container
if($('.'+value.xml_name).length){
$('.container').append($targetToMove);
}
});
}
});
Here is a simplified example of my return data
{"data":{"0":{"id":"1","name":"This","color":"blue"},
"1":{"id":"2","name":"That","color":"red"},
"2":{"id":"3","name":"whatever","color":"blue"}}}
If the orderById equals 1, the data is returned numerically from lowest to highest by the id. If it equals 2 it is returned numerically from highest to lowest like this:
{"data":{"0":{"id":"3","name":"whatever","color":"blue"},
"1":{"id":"2","name":"That","color":"red"},
"2":{"id":"1","name":"This","color":"blue"}}}
The idea is that the API returns the data in the order I want, then on success in the ajax call, the elements are re-arranged on the page in the order of the returned data object.
This works how I intend in Firefox, but in Chrome, whenever I console log the data on success, the order is always the same, despite the console indicating the response from my API is in the correct order.
What am I missing? I can't tell if this is a caching issue or if I am just overlooking something in my javascript.
Object properties order is not guaranteed in JavaScript. You would rather use Array for that
Format you json to look like this:
{"data":[{"id":"3","name":"whatever","color":"blue"},{"id":"2","name":"That","color":"red"},{"id":"1","name":"This","color":"blue"}]}
I'm trying to do a getJSON call to a page within my domain that is simply a json array, which is not returning anything given the script in my webpage:
<script>
$('#genButton').click(function() {
console.log("click");
$.getJSON("http://mygithub.github.io/repository/quotedb.json", function(data){
console.log("executing");
var entry = data[Math.floor(Math.random()*data.length)];
console.log(entry);
$("#quoteDisplay").text(entry);
}).fail(function() {
console.log( "error" );
});
})
</script>
When the button is clicked, the console logs the "click", but never logs "executing", but also doesn't log any errors related to the getJSON. The debugger also never pauses within the getJSON function.
My question is, 1. Is it valid for quotedb.json to be literally a webpage with just a single json array? Or does the page need to be annotated in some way so that the getJSON request knows where to pick up the json from? 2. If (1) is fine, then are there any other reasons you can see why nothing from the getJSON return function would appear?
The json is again one array of json objects, in the form:
{
"character": ""
"quote": ""
}
EDITS
With the edited code, it now outputs "click" followed by "error" from the .fail() method of the $.getJSON call now.
I tried removing the ?callback? section of the url as suggested below, which did not work.
The /repository/ section of my url seems to be necessary to access the file.
Try without ?callback=? at end of url, see jQuery.getJSON()
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
I'm trying use jQuery's AJAX handling .load while passing several variables along with the request.
Normally, as a xmlhttp request GET, I would pass variables like so:
xmlhttp.open("GET","myfile.php?
var1="+data1+"&var2="+data2+"&var3="+data3+"&var4="+data4,true);
Using load, I can't get this to work (the request doesn't succed):
$('#txtHint').load("myfile.php?var1="+data1+"&var2="+data2+"&var3="+data3+"&var4="+data4 , null, function (){ });
In the space where it says "null" in the .load example, is the parameter for:
"data: This optional parameter represents a map of data that is sent with the request".
If I'm unserstanding that correctly, I believe I can use it to send my variables along with the request. However, I can't find information on how to format it.
How can I pass my variables along with the request using .load?
It looks like your method should work as a GET to myfile.php.
If you want to use the data parameter instead, then look at the official jQuery API docs for the .load() method (not to be confused with the .load() event handling method), where it says:
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
So you can pass it as a string or as an object.
As a string (which you more or less already have):
$('#txtHint').load('myfile.php',
"var1="+data1+"&var2="+data2+"&var3="+data3+"&var4="+data4,
function() { }
);
As an object (note that this makes your request a POST):
$('#txtHint').load('myfile.php',
{
var1: data1,
var2: data2,
var3: data3,
var4: data4
},
function() { }
);
Most of the examples in the jQuery docs don't use the data parameter, but the last two examples at the very bottom of the page (as of typing this answer) shows some basic examples of using it in the object format.
This question already has answers here:
console.log() async or sync?
(3 answers)
Closed 8 years ago.
Can anyone elaborate on what might be going wrong? I have no real clue on what to look for at this point.
sample code:
$.ajax({
url: uploader.fileupload('option', 'url'),
context: uploader,
success: function(response){
//logging uploader
console.log(uploader);
//logging this --> logs the same as logging uploader
console.log(this);
//loggin response --> clearly shows a context attribute holding the correct data for this response
console.log(response);
//logging response.context --> shows undefined
console.log(response.context)
var done = uploader.fileupload('option','done');
done.call(this, null, response);
},
dataType:"json"
})
I'm not used to working with the context attribute in $.ajax() call and i'm suspecting this functionality to cause my issue.
The snippet causes issues in my code some time after the ajax call. I'm pretty sure this has nothing to do with ASYNC problems, since problem allready exists way back in the actual success-callback of the original ajax-request.
I've disabled php-headers which were sent, but it remains the same. I tried this based on another topic which implies something could be wrong with my headers.
I've also disabled the dataType attr in $.ajax() but then my response isn't recognised as being json.
Any help or tips on how to debug are much appreciated!
UPDATE:
removing the context attribute in the ajax-call does solve the issue.
But why does it get appended to my response object (or at least seems to be appended) when console.logging()
I'm not sure if this is your problem because the question itself should be better specified. But looking at the title, it seems the plain old problem with console.log()being asynchronous and passing by reference.
When you call console.log(object) the object is kept as a reference and not printed immediately. After some time, when the logging actually happens, the object may be in a different state (for example as in this case, it may have an attribute).
On the contrary when you log obj.property the call is synchronous and that property is not yet defined.
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.