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
Related
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);
});
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 :)
I have a super simple JQuery ajax request below:
$.ajax("../ajax/data/items.json",
{ success: setContent, type: "GET", dataType: "json" });
function setContent(data, status, jqxhr) {
alert("Hello!");
}
The json loads on the page with a 200 response. The success function is set to setContent(). But the success function never runs and I cannot figure out why.
Questions:
Is my understanding of how the success function works incorrect? Why doesn't the function setContent() run for a 200 response on the Json?
Are the arguments for setContent() filled out behind the scenes by JQuery? Obviously I am not setting it anywhere in the code, but the video does not show adding arguments any place.
I am following Lynda.com's tutorial:
http://www.lynda.com/jQuery-tutorials/AJAX-made-simple/183382/368483-4.html
specifically the video AJAX made Simple.
The issue is most likely that you aren't getting back valid JSON. If you specify the data type as JSON and it returns something else, the success handler will not get called.
There is nothing wrong with the syntax:
As you can see, the console.log fires if you don't specify the dataType, as it doesn't care if it is JSON or not. If you do specify, nothing gets logged.
$.ajax(window.location.href,
{ success: setContent, type: "GET", dataType: "json" });
function setContent(data, status, jqxhr) {
console.log("It worked!");
}
You can copy that into dev tools on this site and see what happens when you remove the dataType parameter.
A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.
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
}