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/
Related
I am making the following ajax call to a Wordpress file which handles WP user creation.
jQuery.ajax({
method: 'POST',
dataType: 'json',
url: ajax_object.ajax_url, // Post URL
data: userData, // Data
context: self,
success: self.handleUserResponse(),
error: self.error
})
Where self is the enclosing class object, and handleUserResponse() function which belongs to the enclosing class.
handleUserResponse: function(data, textStatus, jqXHR) {
console.log(data);
console.log(textStatus);
console.log(jqXHR);
}
The callback executes, and all three console.logs return undefined
Am I missing something?
change
success: self.handleUserResponse()
to
success: self.handleUserResponse
handleUserResponse() will result in the success callback parameters being set to undefined.
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).
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).
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(...) }
});
}
I have the following working Ajax call -
$.ajax({
url: ajaxUrl,
type: sendHttpVerb,
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
complete: function () {
setTimeout($.unblockUI, 2000);
},
success: function (response, status, xml) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
callbackFunction(response);
},
error: function (jqXHR, textStatus, errorThrown) {
clearTimeout(delayLoadingMsg);
$.unblockUI();
dcfForm.ajaxErrorDisplay(jqXHR, textStatus, errorThrown)
}
});
My problem is the I conditionally want to add an option when I invoke the Ajax call. For example, adding data: sendRequest before I issue the Ajax request.
My problem I cannot find an example for the syntax on how to do this without completely duplicating the entire function.
what about a ternary operation:
$.ajax({
data: condition ? sendRequest : undefined,
... the rest
});
If that's not your taste, some people seem to forget $.ajax doesn't take a long group of paramters, but an object:
var ajax = {};
ajax.success = function (data) { ... };
ajax.type = 'GET';
if (myCondition) {
ajax.data = sendRequest;
}
$.ajax(ajax);