jQuery invoke function only when ajax of the previous function was executed - javascript

I have the following problem:
$('#id').on('click', '.class', function(){
// it is doing something and
// executing AJAX request
// with the data from request it is doing something
} // this is onclick handler
Later in the code I need to execute it as well and after executing I need to run another function which depends on the ajax execution of this onclick handler, so I am doing something like this
$('#id .class').click();
anotherFunction();
It is not working. The problem is understandable, because the ajax request has not finished.
I tried to achieve the right execution using the idea of Deferred object.
$.when( $('#id .class').click() ).then( anotherFunction() );
And using the idea of autoexecuted functions with callback:
(function(o, callback){
$('#id .class').click()
})(null, anotherFunction() );
Both ideas failed.
Is there any way to achieve the intended functionality without modifying anotherFunction() and onclick function?

Not sure if I entirely understand your question, but what keeps you from executing your onsuccess / onerror code in the corresponding $.ajax response methods?
$.ajax({
type: 'POST',
url: "your url",
data: "your data",
error: function(jqXHR, textStatus, errorThrown) { ... },
success: function (data, textStatus, jqXHR) { ... }
});
Also, why don't you put the ajax executing part to an own function and call it from the event handler and on every other place, like this?
function ajaxMe(onerror, onsuccess)
{
$.ajax({
type: 'POST',
url: "your url",
data: "your data",
error: function(jqXHR, textStatus, errorThrown) { onerror(...) },
success: function (data, textStatus, jqXHR) { onsuccess(...) }
});
}

Related

Success is always fired even when the response is an error

I have an Ajax function that takes in 4 parameters. The url, the data, the success callback and error callback functions. I'm trying to make this Ajax function as reusable as possible. Here's how it looks:
function send_data(url, data, successCallback, errorCallback) {
$.ajax({
url: url,
type: 'post',
data: data,
success: successCallback,
error: errorCallback
});
}
Where the success callback looks like this:
function createMessage(message) {
console.log(message);
}
and error callback looks like this:
function createErrorMessage(message) {
console.log(message);
}
However, when I call the Ajax function with parameters that should return a 400 error bad request, the success function is always fired regardless if it is a 200 or 400 response. I don't understand why the success callback function is firing when only the error function should be firing. However, both are firing. Why is this?
The problem is in these lines
success: successCallback,
error: errorCallback
They both are running immediately one after the other so both are returning their values.
Make an anonymous callback function on both success and error and it will work fine.
success: function() {
successCallback();
},
error: function() {
errorCallback();
}

Ajax call to asp.net web method doesn't trigger

I am new to ajax and javascript.
I have the following web method in a page called people.aspx in the root of my web porject:
[System.Web.Services.WebMethod]
public static string RenderDetails()
{
return "Is it working?";
}
I'm attempting to access the web method via an Ajax call from the people.aspx page. I have the following ajax call on the click event of a div:
$("div.readonly").click(function (e) {
e.stopPropagation();
$.ajax({
type: "POST",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
failure: function (msg) { alert("Sorry!!! "); }
});
alert("Implement data-loading logic");
});
I'm not receiving any errors in the javascript console, however, the ajax call also does not hit the web method. Any help will be appreciated.
Thanks!
Try change the type to GET not POST (this is probably why your webpage isn't getting hit). Also your failure parameter is incorrect, it should be error. Expand it to include all parameters (it will provide more information). In short, change your entire AJAX query to this:
$.ajax({
type: "GET",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
error: function (jqXhr, textStatus, errorThrown)
alert("Sorry!!! "); // Insert breakpoint here
}
});
In your browser, debug the error function. The parameters (particularly jqXHR) contain a LOT of information about what has failed. If you are still having more problems, give us the information from jqXHR (error string, error codes, etc).

Can ajaxSetup.success callback prevent ajax.complete callback from being called?

In $.ajaxSetup.success I want a general piece of code to check something and then the $.ajax.complete callback should not be called. Is this possible? Preferably by doing something in the $.ajaxSetup.success callback and not in every $.ajax.complete callback.
event.stopImmediatePropagation might work, but I don't know how to access event from success.
$.ajaxSetup({
success : function(jqXHR, textStatus, errorThrown) {
alert('this will happen');
}
});
$.ajax({
url: '/echo/json/',
type: 'POST',
complete: function () {
alert('this shouldn\'t happen');
}
});
jsFiddle: http://jsfiddle.net/z4L4z3oo/1/

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.

Expanding on the jQuery post function

I have the following function in my code:
$.post($form.attr('action'), $form.serializeArray())
.done(function (json) {
}
From what I understand from the jQuery docs this is a shortcut. What I would like to do is to change so that it allows me to have some function that executes on success and some function that executes on error. Is this possible to do? All I see is a .done?
$.ajax({
url: target,
dataType: 'json',
type: 'POST',
data: data,
success: function(data, textStatus, XMLHttpRequest) { },
error: function(XMLHttpRequest, textStatus, errorThrown) { }
Since all the jQuery ajax methods, including $.post(), return a jqXHR object, you can use the Deferred object API if you don't want to use a full-out $.ajax() call.
$.post(/* snip */).fail(function () {/* snip */});
Actually you can use .success() .error() and .complete() as chained methods to .post() - http://api.jquery.com/jQuery.post/

Categories

Resources