Difference between ajax and getJSON calls? - javascript

I have a page being served from a Web.API app located at http://server/application. On the client side, I am doing a GET to pull some data from the servers. The problem is what I thought should work does not.
This code works:
$.ajax( {
url: "api/slideid/getdirectories/",
dataType: 'json',
success: function ( data ) {
setPaths( data );
}
} );
But this does not:
$.getJSON( "api/slideid/getdirectories/",
function ( data ) {
setPaths( data );
} );
In the first example I see in fiddler that the url it is trying to retrieve the data from is http://server/application/api/slideid/getdirectories, which is correct.
In the second, it is http://server/api/slideid/getdirectories, which is not right. I was thinking that these two methods of json GET were the same.... but it seems they are not?
Interestingly, BOTH these methods work on my local dev box- it is only on my staging server that one works and the other does not. IIS settings are identical as far as I can tell- and I dug in pretty good to check.
So I'm wondering why getJSON does not work, when the jQuery docs state that getJSON is just shorthand for the .ajax call?
EDIT: I had put in an explicit version of getJSON hoping to show that they were very similar calls, but the 'real' getJSON call is now there.

You have a wrong implementation of $.getJSON() This should be:
$.getJSON(url, {data:data}, function(data){
alert(data);
});
where {data:data} is optional.
From the docs:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});

$.getJSON(url, {data:data}, ....
wrong syntax

Related

How to run getJSON synchronously? [duplicate]

GOAL: What I'm after is to get data from database and refresh main.php (more evident through draw_polygon) every time something is added in database (after $.ajax to submit_to_db.php).
So basically I have a main.php that will ajax call another php to receive an array that will be saved to database, and a json call another php to return an array will be used by main.php.
$(document).ready(function() {
get_from_db();
$('#button_cancel').click(function(){
$.ajax({
url: 'submit_to_db.php',
type: 'POST',
data: {list_item: selected_from_list},
success: function(result){
...
get_from_db();
}
});
});
function get_from_db(){
$.getJSON('get_from_db.php', function(data) {
...
draw_polygon(data);
});
}
});
In my case, what I did was a get_from_db function call for getJSON to actually get data from database, with the data to be used to draw_polygon. But is that how it should be done? I'm a complete newbie and this is my first time to try getJSON and ajax too to be honest. So my question: How does asynchronous work actually? Is there another workaround for this instead of having to call function get_from_db with getJSON (it isn't synchronous, is it? is that why it doesn't update the page when it isn't within a function?) All the time - like $.ajax with async: false (I couldn't get it to work by the way). My approach is working, but I thought maybe there are other better ways to do it. I'd love to learn how.
To make it more clearer, here's what I want to achieve:
#start of page, get data from database (currently through getJSON)
Paint or draw in canvas using the data
When I click the done button it will update the database
I want to AUTOMATICALLY get the data again to repaint the changes in canvas.
Since $.getJSON() uses ajax configurations, just set the global ajax configs:
// Set the global configs to synchronous
$.ajaxSetup({
async: false
});
// Your $.getJSON() request is now synchronous...
// Set the global configs back to asynchronous
$.ajaxSetup({
async: true
});
Asynchronusly does mean the Request is running in the background, and calls your function back when it got a response. This method is best if you want to have a result but allow to use your app within the request. If you want to have a direct response, take a look at a synchron request. this request will pause script execution until it got a response, and the user can not do anything until the response was recieved. You can toggle it via:
async: false,
So for example:
$.ajax({
url: "myurl",
async: false,
...
})
$.getJSON(), doesn't accept a configuration, as it says in the docs it's a shorthand version of:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So just rewrite your request in terms of that and async:false will work just as you expect.
$.getJSON() is a shorthand notation for $.ajax() which can be configured to be synchronous (see jQuery.getJSON and JQuery.ajax):
$.ajax({
dataType: "json",
url: url,
data: data,
async: false,
success: function(data) {
...
draw_polygon(data);
}
});
Try to avoid synchronous calls though. Quote from jQuery doc (see async prop):
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation. Note that synchronous requests may temporarily
lock the browser, disabling any actions while the request is active.
You might want to try jQuery Deferreds like this:
var jqxhr = $.getJSON(url);
jqxhr.done(function(data) {
...
draw_polygon(data);
});

What is the best way to check if Ajax call is 200 OK if I'm returning the table?

I have a question about ajax success. So in previous situations I have returned Data something like ID but now in this case I'm returning entire table. So I would like to check if Ajax was successful(200 OK) before I retrieve my data. What is the best way to do that? Also I use new way to retrieve data and check for errors with JQuery. Here is example of my code:
<div id="box"></div>
function getSlots(fld){
var userID = '134';
$j.ajax({
type: 'POST',
url: 'AjaxData.html',
cache: false,
data: {'userID':userID},
dataType: "html",
async: false
})
.done(function(html){
$j('#box').html(html);
})
.fail(function(jqXHR, textStatus, errorThrown){
gwLogIt(errorThrown);
});
}
You don't need to check. The various callbacks are called under the following conditions:
.done() or success: are called when the AJAX call is successful.
.fail() or error: are called when there's an error (either from the server or in the jQuery code that parses the response).
.always() or complete: are called in either case.
from official docs:
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
http://api.jquery.com/jQuery.ajax/
also if you use something like babel to transpile ES6, you can use fetch api for ajax calls. I personally stopped using jQuery ±2 years ago.. when moved to React world :)

$.ajax() success won't run function

My question regards the $.ajax() jQuery method. I can't get the success parameter in $.ajax() to work.
This works:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: window.alert("inside aJax statement")
});
This does not:
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json',
success: function(){
window.alert("inside aJax statement");
}
});
In the first case, I get a JavaScript alert window that lets me know the $.ajax() I called is working. All that is changed in the second block of code is I put the window.alert() inside a function() { window.alert(); }.
The point of this is to verify that the $.ajax is running so I can put some actual useful code in the function(){} when the $.ajax runs successfully.
In your second example nothing will happen unless you get a successful call back from the server. Add an error callback as many here have suggested to see that indeed the ajax request is working but the server is not currently sending a valid response.
$.ajax({
type: "POST",
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType:"json",
success: function(response){
alert(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
helpful Link in tracking down errors.
Your first example does nothing whatsoever to prove that the ajax call has worked. All it does is prove that the ajax function was reached, because the values of the properties in the anonymous object you're passing into the ajax function are evaluated before the function is called.
Your first example is basically the same as this:
// THIS IS NOT A CORRECTION, IT'S AN ILLUSTRATION OF WHY THE FIRST EXAMPLE
// FROM THE OP IS WRONG
var alertResult = window.alert("inside aJax statement");
$.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent=" + $('#wClient').val(),
dataType: 'json',
success: alertResult
})
E.g., first the alert is called and displayed, then the ajax call occurs with success referencing the return value from alert (which is probably undefined).
Your second example is correct. If you're not seeing the alert in your second example, it means that the ajax call is not completing successfully. Add an error callback to see why.
In first case window.alert is executed immidiatly when you run $.ajax
In second it run only when you receive answer from server, so I suspect that something wrong in you ajax request
You may want to try and use a promise:
var promise = $.ajax({
type: 'POST',
url: "/getCodes.php?codes=billingCodes&parent="+$('#wClient').val(),
dataType: 'json'
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
What this does is saves the ajax call to a variable, and then assigns additional functionality for each of the return states. Make sure that the data type you are returning is actually json, though, or you may see strange behavior!
Note that js is single-threaded; the reason your first example works is because it actually executes the code next 'success' and stores the result. In this case there is nothing to store; it just pops an alert window. That means that the ajax call is leaving the client after the alert is fired: use the developer tools on Chrome or equivalent to see this.
By putting a function there, you assign it to do something when the ajax call returns much later in the thread (or, more precisely, in a new thread started when the response comes back).
I think that you do it right, but your request does not succeeds. Try add also error handler:
error: function(){alert("Error");};
I guess that dataType does not match or something like that.
It is 100% your second example is correct. Why it does nothing? Maybe because there is no success in the ajax call.
Add "error" handler and check waht does your ajax call return with the browsers' developer tool -> Network -> XHR . This really helps in handling of broken / incorrect ajax requests

jQuery.ajax returns jsonp instead of json

I have a simple ajax call like this:
$.ajax({
url: u, type: "POST", dataType: "json",
data: data,
success: function (d) { response($.map(d, function (o) { return { label: o.Text, value: o.Text, id: o.Id} })); }
});
It is part of an tb autocomplete that does not work on only one view.
The reason it does not work is that instead of json, it makes jsonp request (by sniffing I saw that it calls passed url with ?callback=jQueryxxxxxxxxx), and success function is never called because jquery packs it into anonymous function whose name is passed in callback argument, and server returns standard json (I don't want to use jsonp as it is POST request and NOT cross-domain request). I checked, both current view url and this u for ajax url argument are on http://localhost:8080/myapp/areax/..., so I don't see why jQuery makes JSONP request here.
EDIT:
View on which this does not work has url request is made is like this:
http://hostname:8080/AreaName/Report/ViewReport
and u parameter of ajax is like /AreaName/MyAutoComplete/Search, so complete url to which autocomplete is made is like
http://hostname:8080/AreaName/MyAutoComplete/Search?callback=jQuery151013129048690121925_1327065146844
Server's response looks like this:
[{"Id":2,"Text":"001"},{"Id":7,"Text":"002"}]
I know it is not jsonp, for that it should be
<script>
jQuery151013129048690121925_1327065146844([{"Id":2,"Text":"001"},{"Id":7,"Text":"002"}]);
</script>
But I want to make normal json request, not jsonp.
UPDATE
Weirdest thing of all (I'm starting to think it is a bug in jQUery v1.5.1 which is used on project) is that when I remove dataType: "json", it makes a normal json request :)
So, instead of how to make json request, now I will accept an explanation to why this works as expected (and the one with dataType:"json" does not):
$.ajax({
url: u, type: "POST",
data: data,
success: function (d) { response($.map(d, function (o) { return { label: o.Text, value: o.Text, id: o.Id} })); }
});
From the bug here : http://bugs.jquery.com/ticket/8118
You are probably using jquery-validation plugin. Jquery-validation plugin is not compatible with jQuery 1.5 and the conflict causes the kind of issue you are having here.
If the problem is not specifically due to jquery-validation plugin, check if you have any other jquery plugin that might not be compatible with jQuery 1.5

Having problems with jQuery, ajax and jsonp

I am using jsonp and ajax to query a web-service written in java on another server. I am using the following jquery command:
$.ajax({
type: "GET",
url: wsUrl,
data: {},
dataType: "jsonp",
complete: sites_return,
crossDomain: true,
jsonpCallback: "sites_return"
});
function jsonp_callback(data) {
console.log(data);
}
function sites_return(data) {
console.log(data);
}
So my problem is that after the query finishes a function called jsonp_callback is called. Where I can clearly see the json formatted string:
{"listEntries":["ELEM1", "ELEM2", "ELEM3", etc...]}
But after the function sites_return is called when the complete event fires, I get the the following:
Object { readyState=4, status=200, statusText="parsererror"}
Also for reference the jsonp_callback function is called before the sites_return function. Also if i take the jsonp_callback function out of the code, I get a complaint it firebug that the function is not implemented.
My question three fold:
1) What am i doing wrong on the jquery side?
2) Why does the json get parsed correctly in jsonp_callback but not sites_return?
3) What can i do to fix these issues?
EDIT
Some new development. Per the comments here is some additional information.
The following is what comes out of the http response
jsonp_callback({"listEntries":["ELEM1", "ELEM2", "ELEM3"]})
I assume this is the reason jsonp_callback is being called. I guess my question now becomes, is there any way to control this (assuming i don't have access to the back end web-service).
Hope this helps~
var url = "http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
var address = "1600+Amphitheatre+Parkway";
var apiKey = "+Mountain+View,+CA";
$.getJSON("http://maps.google.com/maps/geo?q="+ address+"&key="+apiKey+"&sensor=false&output=json&callback=?",
function(data, textStatus){
console.log(data);
});
I believe that the first argument to the sites_return function would be the jqXHR Object. Instead of complete try using success.
But still this may not work as it seems that there is a parsing error (mentioned in the return value of sites_return function called from oncomplete). Therefore, you would first need to check your json string.
To Validate JSON, you can use http://jsonlint.com/
I think that the problem is that your server is not behaving the way jQuery expects it to. The JSONP "protocol" is not very stable, but generally what's supposed to happen is that the site should look for the "callback" parameter and use that as the function name when it builds the JSONP response. It looks as if your server always uses the function name "jsonp_callback".
It might work to tell jQuery that your callback is "jsonp_callback" directly:
$.ajax({
type: "GET",
url: wsUrl,
data: {},
dataType: "jsonp",
complete: sites_return,
crossDomain: true,
jsonpCallback: "jsonp_callback"
});
Not 100% sure however.
If you don't have the ability to change the JSONP function wrapper that the remote server returns, jQuery's $.ajax() may be overkill here. Ultimately, all you're doing is injecting a script reference to wsUrl, which makes a call to jsonp_callback with a JavaScript object literal as its input parameter.
You could just as easily do something like this and avoid the confusion around the callback naming/syntax:
$.getScript(wsUrl);
function jsonp_callback(response) {
// Access the array here via response.listEntries
}

Categories