.done() jquery not working - javascript

Im using the below code for a ajax call
var getRequest = $.ajax({
type: 'GET',
url: Url,
async: false,
dataType: "text",
complete: function () {
$('#loading').hide();
}
});
the request is getting complete and data is also withdrawn after the data is recieved the following:
getRequest.done(function (dataDb) {
if (dataDb) {
alert('dataDb: ' + dataDb);
}
});
getRequest.fail(function (jqXHR, textStatus, error) {
alert('data error within getUsersRequest ' + textStatus + ' : ' + error);
});
I'm recieving a error that getRequest.done(function(dataDb) or getRequest.fail(function(jqXHR, textStatus, error) is not a function.

It is because your JQuery version is too old.
You can use success if you are not willing to upgrade the latest version of JQuery.
success: function(dataDb) {
}

success only fires if the AJAX call is successful from back end, i.e. it returns a HTTP 200 status as response. if any error fires if it fails and complete when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR object (returned by $.ajax) success is being replaced with the done, error with fail and complete with always.
However you should still be able to initialise the AJAX request with the current syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
Last: you need to use .success rather then using .done

You can try using .success.
var getRequest = $.ajax({
type : 'GET',
url : Url,
async: false,
dataType: "text",
complete: function(){
$('#loading').hide();
}
}).success(function(dataDb){
if(dataDb) {
alert('dataDb: '+ dataDb);
}
});

Related

How to return data from PHP to a ajax function

Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});

Jquery Ajax beforeSend and success,error & complete

I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the first ajax.
The loading class I am adding to the placeholder before sending is working for the first ajax call. However soon after the first ajax request completes the class is removed and never appends again on the second and further calls (remember recursive calls).
While debugging it shows that the beforeSend function of the second ajax call is called first and the complete function of the first ajax call is called later. Which is obvious, because the return data inserted in the page from the first ajax call starts the second call.
In short it's mixed up. Is there any way this can be sorted out?
The function code is as follows
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
$(placeholder).removeClass('loading');
},
dataType: 'html'
});
}
And the data contains the following snippet of javascript/jquery which checks and starts another ajax request.
<script type="text/javascript">//<!--
$(document).ready(function() {
$('#restart').val(-1)
$('#ajaxSubmit').click();
});
//--></script>
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: #get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Check is a Self-Hosted-Service is running or not

I have a Self-Hosted-Service(using WCF) that will run on clients machines. That service is supposed to make request to another server, get the data as XML then it returns to me that data as JSONP. Now i want to check if the service is running or not .. How can i check that ?
In my JS code i use $.getJSON with callback, so i tried to use .fail like this:
$.getJSON("http://localhost:8080/url?callback=?", function () {
alert("success");
}).fail(function () {
alert('fail');
})
but fail function didn't called when the server is not running(on chrome the Type is pending and Status is Failed)
Then i tried to use $.AJAX like this:
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://localhost:8080/url?callback=?',
success: function (data, textStatus) {
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
I got the same result.
When you make the AJAX request to your localhost and /url? returns weather the other server is up or not, your script won't fail. Because http://localhost/url is online.
I'd make the /url script return JSON array with remoteHostOnline: true or false,
then use:
$.ajax({
type: 'GET',
dataType: 'jsonp',
url: 'http://localhost:8080/url?callback=?',
success: function (data, textStatus) {
if (data.remoteHostOnline == false) {
alert('remote host not online');
}
}
});
You might have to tweak this script I didn't test it but you will understand what's wrong.

JQuery ajax() done / fail callbacks not returning upon status 200

I'm trying to post a form data using JQuery to a remote servlet.
I can see that the server receives the data and also returns status code 200 and a response string of "{result: 'success'}"
But the ajax call doesn't return with the done or fail functions (if I add an always function than I can see that it is being called)
Here's a code snippet of the client side:
`
var dataParams = 'email='+email+'&password='+password;
var url = 'http://127.0.0.1:8888/signup';
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json",
done: function() {
console.log("done!");
hideSignUp();
showThankYou(); },
fail: function() {
console.log("fail!");
}
});
`
Seems like I'm missing out on something, but can't seem to find what.
Note that I'm using JQuery 1.8.3 so success is deprecated.
Any thoughts?
Try:
var url = "http://127.0.0.1:8888/signup";
var jxhr = $.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function() {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
Try chaining your callbacks, rather than setting them as object fields:
$.ajax({
type : "POST",
url : url,
data : dataParams,// serializes the form's elements.
dataType: "json"
}).done(function (xhrResponse) {
console.log("done!");
hideSignUp();
showThankYou();
}).fail(function (xhrResponse, textStatus) {
console.log(textStatus);
}).always( function () {
console.log("I'm done with this.");
});
By chaining your callbacks, you guarantee execution of at least one (complete).

How to callback a function on 404 in JSON ajax request with jQuery?

I want to make an Ajax request with response in JSON. So I made this Ajax request:
$.ajax({
url: 'http://my_url',
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},
complete: function(data) {
alert('complete')
}})
This code works good but when my url send me a HTTP code 404, no callbacks are used, even the complete callback.
After research, it's because my dataType is 'json' so 404 return is HTML and the JSON parsing failed. So no callback.
Have you a solution to call a callback function when a 404 is raised ?
EDIT: complete callback don't call is return is 404. If you want an URL wit 404 you can call : http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697 it's with this URL I have my problem.
$.ajax({
url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',
dataType: "json",
success: function(data) {
alert('success');
},
error: function(data) {
alert('error');
},
complete: function(xhr, data) {
if (xhr.status != 0)
alert('success');
else
alert('fail');
}
})
With your configuration jQuery uses jsonp to transport the data. This works by dynamically inserting a script element and setting the URL to the specified value. The data returned by the server is then evaluated as JavaScript - usually calling the provided callback. If the server returns a 404, the contents is obviously no JavaScript and the callback is never called. Some browsers support error handlers on the script tag, which are called in these situations. Unfortunately IE doens't support this. The best way to detect an error is to rely on a timeout.
In your case you should specify an additional timeout option, which causes the error handler to be called if the callback wasn't called in time (which would be the case for a 404 response).
$.ajax({
url: 'http://my_url',
timeout: 2000, // 2 seconds timeout
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},
complete: function(data) {
alert('complete')
}
});
Use the statusCode-Option
$.ajax({
url: 'http://my_url',
dataType: "json",
statusCode: {
404: function() {
alert("I could not find the information you requested.");
}
},
success: function(data) {
alert('success');
},
error: function(data) {
alert('error');
},
complete: function(data) {
alert('complete');
}
})
If you want to handle errors when accessing the Twitter API with Javascript and jsonp you need to include the parameter suppress_response_codes in your request. This makes all responses from the Twitter API respond with a 200 OK response and include a error. Then you need to check if the response includes the error parameter or not.
$.ajax({
url: "https://api.twitter.com/1/users/show.json",
dataType: 'jsonp',
jsonp: "callback",
data: {
screen_name: "simongate1337",
suppress_response_codes: true // <- Important part
},
success: function(data) {
if(data.error) {
console.log("ERROR: "+data.error);
} else {
console.log("Success, got user " + data.screen_name);
}
}
});
Do not you think that the problem is not with the dataType but with cross-domain requests that you are not allowed to make?
The code below works as expected when you request data from the same domain and does not when you are making cross-domain requests:
function handle404(xhr){
alert('404 not found');
}
function handleError(xhr, status, exc) {
// 0 for cross-domain requests in FF and security exception in IE
alert(xhr.status);
switch (xhr.status) {
case 404:
handle404(xhr);
break;
}
}
function dumbRequest() {
var url = 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697';
url = 'http://twitter.com/';
url = '/mydata.json';
// url = 'mydata.json';
$.ajax(
{url: url,
dataType: 'json',
error: handleError}
);
}
Is it simply because the dataType is set to "json"? If so, try changing it to text and evaluate the JSON yourself:
$.ajax({
url: 'http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697',
dataType: 'text',
success: function(data, status, xmlHttp) {
try {
data = eval('(' + data + ')');
alert('success');
} catch (e) {
alert('json parse error');
}
},
error: function(xmlHttp, status, error) {
alert('error');
},
complete: function(xmlHttp, status) {
alert('complete');
}
});
Are you aware that even though the HTTP status is 404, the actual body is valid JSON? For instance, this link has the following JSON:
jsonp1269278524295({"request":"/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697","error":"Not found"})
As such, you should check if your data has the error property within your normal callback function.
UPDATE: apparently, even though the actual content of the page is valid JSON, the browser (I checked in Firefox) is not executing it, most likely because it is a 404. Because jQuery has to add a script element (because of the cross-domain issue), its JSONP wrapper is never called, and as a consequence, neither are your callbacks.
So, in short, I don't think there is a way to deal with this without manually adding that script element and checking if your pre-defined callback function has been called afterwards.
Just faced the same issue, and saw another question mentioned that jQuery-JSONP (jQuery Plugin) supports catching 404 errors or as they describe: "error recovery in case of network failure or ill-formed JSON responses"
And it works perfect :)
Here is my (simplified) code for fetching details about a YouTube video via JSONP:
$.jsonp(
{
url: "https://gdata.youtube.com/feeds/api/videos/ee925OTFBCA",
callbackParameter: "callback",
data:
{
alt: "jsonc-in-script",
v: "2"
},
success: function(json, textStatus)
{
console.log("WEEEEEEEE!");
},
error: function(xOptions, textStatus)
{
console.error(arguments);
}
});
Here's how I deal with this. I check the returned data for errors before trying to use it. What is shown below is just a sample that you could extend to more closely match your requirements. This also considers session time outs and other scenarios...
My initial call:
$.ajax({ type: 'POST',
url: '../doSomething',
data: 'my data',
success: function(data) {
if (HasErrors(data)) return;
var info = eval('(' + data + ')');
// do what you want with the info object
},
error: function(xmlHttpRequest) {
ReportFailure(xmlHttpRequest);
}
});
And the two helper functions:
function HasErrors(data) {
if (data.search(/login\.aspx/i) != -1) {
// timed out and being redirected to login page!
top.location.href = '../login.aspx';
return true;
}
if (data.search(/Internal Server Error/) != -1) {
ShowStatusFailed('Server Error.');
return true;
}
if (data.search(/Error.aspx/) != -1) {
// being redirected to site error reporting page...
ShowStatusFailed('Server Error. Please try again.');
return true;
}
return false;
}
and
function ReportFailure(msg) {
var text;
if (typeof msg == 'string') {
text = msg;
}
else if (typeof msg.statusText == 'string') {
if (msg.status == 200) {
text = msg.responseText;
}
else {
text = '(' + msg.status + ') ' + msg.statusText + ': ';
// use the Title from the error response if possible
var matches = msg.responseText.match(/\<title\>(.*?)\<\/title\>/i);
if (matches != null)
{ text = text + matches[1]; }
else
{ text = text + msg.responseText; }
}
}
// do something in your page to show the "text" error message
$('#statusDisplay')
.html('<span class="ui-icon ui-icon-alert"></span>' + text)
.addClass('StatusError');
}
Following solution is working fine for me :)
$.ajax({
url: 'http://my_url',
dataType: "json",
success: function(data){
alert('success');
},
error: function(data){
alert('error');
},complete: function(xhr, data) {
if(data==="parsererror"){
alert('404');
}
}
});

Categories

Resources