What does `success: function(msg)` mean in my jQuery Ajax call? - ajax

I have two jQuery Ajax calls that I'm combining on a page. I'm stuck on the success: function() in each, as one is success: function(msg) and the other is success: function(data). I'm unsure of what both of these mean, and what they should be in the combined code. I'll place the two calls below, separately, and combined as I have them thus far.
Ajax Request #1: there is a $msg .= "<div class='pagination'><ul>"; on this functions php page. Not sure if that is what this is referring to.
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: "page="+page,
success: function(msg)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
});
}
});
Ajax Request #2: As far as I can see, there is no data anywhere on this call's php file. Don't know what function(data) is referring to.
$.get("new_arrivals_data.php",{imgs: value}, function(data){
$("#gallery_container").html(data);
});
Combined Request: I have put a ? where msg was in the original call as I'm unsure what to put in it's spot.
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: {page:page, imgs: value},
success: function(?)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(?);
});
}
});

msg and data are simply the names of the formal parameters. You use those to refer to the response data that is passed to that function when it is invoked.
You can rename it to any valid JavaScript identifier.
Although there isn't really any reason to call ajaxComplete inside the success: callback:
success: function( whatever_you_want_to_call_it ) {
gallery_show();
loading_hide();
$("#gallery_container").html( whatever_you_want_to_call_it );
}
$.get("new_arrivals_data.php",{imgs: value}, function( i_like_ice_cream ){
$("#gallery_container").html( i_like_ice_cream );
});
Remember, in both cases, you're passing a function as an argument. That function is invoked when the response is received.
Whatever code is invoking that function, is also passing the response into that function as the first argument so that you have access to it. That's why you defined the parameter.
It's very similar to declaring a variable in a function.
$.get("new_arrivals_data.php",{imgs: value}, function(){
var i_like_ice_cream = arguments[0];
$("#gallery_container").html( i_like_ice_cream );
});
This does almost the same thing. You've associated a variable with the first argument passed into your callback function.

It can be any valid variable name. Either data or msg will work, just as long as you use the same one within the scope of that function.
To explain, you are setting success to an anonymous function, pretty much just a function with no name. So when jQuery dispatches the success event, it calls the function that you have given it when creating the ajax request. It also passes in some arguments into that function (in this case, the resulting data from the ajax request). What you are defining is what that incoming information should be called in the scope of this new function.
Take the following code for example:
function workOnBob(aWorker) {
aWorker("Bob")
}
var sayHi = function(name) { alert("Hello " + name); };
var getMarried = function(groom) { alert(groom + " is getting married!"); };
workOnBob(sayHi); // "Hello Bob"
workOnBob(getMarried); // "Bob is getting married!"
You can see that workOnBob is a function, and it should be passed an anonymous function. It invokes that function with the string "Bob". Also, notice the anonymous functions, sayHi and getMarried, have named the arguments they receive differently within their own scope (name and groom respectively). They both get the string "Bob", but they both choose to call it something different.
Anonymous functions and closures can be confusing, but once you get the hang of them, they are a lot of fun.

It just a name for the variable containing the response data returned from the ajax call. Name it whatever makes the most sense to the context, to make your code more readable, e.g. html, resp, logged.

Related

AJAX response undefined.

I am currently creating an AJAX call which queries a controller and returns the appropriate reponse. The only issue is is that the response is coming back as undefined doe to the async nature of the AJAX cal. I am unsure as to how I tell the function to wait for the response. Here is my code:
View:
jQuery(document).on("click", "#payment .membership", function(e) {
e.preventDefault();
var price = SignUpObject.membershipClick(jQuery(this).attr("data-membership-id"));
alert(price);
});
Javascript Library Function (which is within an object):
var SignUpObject = {
membershipClick : function(membershipDetailsId) {
jQuery.ajax({
type : 'POST',
dataType : 'json',
url : 'api/membership-choice',
data : 'membershipid=' + membershipDetailsId
}).done(function(response) {
return response
});
}
}
The PHP that the AJAX call is calling returns the correct response back so I don't need to include them here. Can anyone tell me how to make the AJAX call wait for a response?
Thanks
You've got two problems:
1) You're attempting to call the response synchronously, before the (asynchronous) request has completed.
2) membershipClick does not return the request object, so you've got no means of hooking a completion callback onto it.
To fix:
1) Change the line
jQuery.ajax({...
to
return jQuery.ajax({
2) Change the line
alert(price);
to
price.done(function(response) { alert(response); });
However, the variable price would be better named something like price_request, since it stores a reference to the request, not the actual price (which is the response.)
Change
}).done(function(response) {
return response
});
For:
}), success: function(response) {
return response
};

Chain multiple POST requests together using AJAX and jQuery

I received a suggestion from a prior question that I need to amend my code chain a series of POST requests together, but I don't have any idea how to accomplish this. Specifically, the advice I was given was to:
fire off a post, have its success handler fire off the next post,
etc... and then when all the posts are done, the final post's success
handler fires off the get
This strategy makes sense to me but I do not know how to implement. I am trying to prevent the call to GET before all of the calls to POST have completed. Currently, I have implemented $.when.apply to delay the sending of GET. Here is the code for that:
function(){
$.when.apply(undefined, InsertTheAPPs()).done(function () {
$.ajax({
url: sURL + "fileappeal/send_apps_email",
success: function() {
var m = $.msg("my message",
{header:'my header', live:10000});
setTimeout(function(){
if(m)m.setBody('...my other message.');
},3000);
setTimeout(function(){
if(m)m.close(function(){
window.location.replace(sURL+'client/view');
});
},6000);
$('#ajaxShield').fadeOut(1000);},
error: function(){
$.msg("error message",
{header:'error header', live:10000});
}
});
});
}
Here is the code for the jQuery $.each loop. This is the code that needs to not only begin, but must end before the ajax call to fileappeal/send_apps_email above:
function InsertTheAPPs(){
$('input[name=c_maybe].c_box').each(function(){
var jqxhrs = [];
if($(this).prop('checked')){
var rn = $(this).prop('value');
jqxhrs.push(
$.ajax({
url: sURL + 'fileappeal/insert_app',
type:"POST",
dataType: 'text',
data: {'rn': rn},
error: function(data) {console.log('Error:'+rn+'_'+data);}
})
)
return jqxhrs;
}
});
}
Could someone demonstrate how I can modify the code above to implement the strategy of chaining together the multiple POST calls?
Don't return from .each. It doesn't work that way. Instead do this:
var jqxhrs = [];
$(...).each(...
});
return jqxhrs;
Nothing is assigned to the return value of .each, which you can't get anyway. Returning from each allows it to be used like break/continue, which doesn't make sense in your context.
Moreover, the var jqxhrs inside of the each loop causes a new variable to be declared in that context on each iteration of the loop.

Retain the context of JQuery ajax function

I have an old code which is dependant on JQuery 1.3.2 that uses the following ajax call
function ChangeContent(url, somepageobject) {
var xhrobj = $.ajax({
url: url,
context: somepageobject,
callback: doFurtherStuff,
success: function(data) {
somepageobject.html($(data));
this.callback.call(this.context[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}
Problem with the code above is that this.callback is null when I upgraded to JQuery 1.8.1, most importantly the ChangeContent function is being used in different places and is outside my control (its used as as an API for external users...etc). An example of the usage of the above is like this:
xhr_object = ChangeContent("/someurl, $("#resultContainer"));
function doFurtherStuff(responseText, statusText, XMLHttpRequest)
{
var identifier = '#' + this.id;
...
}
Notice that the doFurtherStuff must have the correct "this" object value which is the context specified in ChangeContent function. When I tried to use different deferred then() ...etc. functions in JQuery 1.8.1 to solve the above this.callback.call(this.context[0], data); problem after the upgrade the "this" object in the callback function had different value since I guess the new JQuery library handles that differently.
Is there anyway to fix the error above while limiting the change to ChangeContent function only as I try to avoid asking all users to change the way they call and handle call backs from that function?
When you add the context option, you are telling jQuery what this should be inside of the success callbacks. That means you can't access the options passed into the ajax request. Either don't supply a context, or pass in the callback manually.
function ChangeContent(url, somepageobject) {
var callback = doFurtherStuff;
var xhrobj = $.ajax({
url: url,
context: somepageobject,
success: function(data) {
somepageobject.html($(data));
callback.call(this[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}
Update:
If you want to instead continue using your code as-is, simply rename the context property.
function ChangeContent(url, somepageobject) {
var xhrobj = $.ajax({
url: url,
thecontext: somepageobject,
callback: doFurtherStuff,
success: function(data) {
somepageobject.html($(data));
this.callback.call(this.thecontext[0], data, "ok"); // >> Code breaks here
}
});
return xhrobj;
}

jQuery - AJAX request using both native XHR and flXHR (Flash) fallback - how to minimize code duplication?

I need to retrieve data via cross-domain XMLHttpRequest. To make this work in (almost) all browsers, I use native XHR first and, if that fails, flXHR.
The (working) code I currently have for this is as follows:
jQuery.support.cors = true; // must set this for IE to work
$.ajax({
url: 'http://site.com/dataToGet',
transport : 'xhr',
success: function(data) {
console.log('Got data via XHR');
doStuff(data);
},
error: function(xhr, textStatus, error) {
console.log('Error in xhr:', error.message);
console.log('Trying flXHR...');
$.ajax({
url: 'http://site.com/dataToGet',
transport : 'flXHRproxy',
success: function (data) {
console.log('Got data via flXHR');
doStuff(data);
},
error: function (xhr, textStatus, error) {
console.log('Error in flXHR:', error.message);
console.log('Both methods failed, data not retrieved.');
}
});
}
});
This feels like a lot of code duplication to me, especially in the success handlers. Is there a more efficient way to do this? I'd really prefer to make one $.ajax call that would try both transports in turn, instead of having to use the error handler to make the call a second time. It's not too bad in this example, but rapidly gets more complicated if the success handler is longer or if the success handler has to itself issue another $.ajax call.
I've created a jquery-specific and slimmed-down fork of flxhr that simplifies your code sample above. You can see an example of usage in the "Usage" section in the README.
https://github.com/b9chris/flxhr-jquery-packed
In particular, you don't want to waste time waiting for a standard CORS request to fail. It's easy to determine whether flxhr is necessary by testing $.support.cors upfront (no need to override it). Then just use flxhr explicitly where necessary.
Why don't you just wrap this in a function by itself? That's after all, how you end up reusing code. You can even pass functions as arguments to make sure that you don't have to repeat this code more than once.
To me this is pretty straight forward but maybe I've misunderstood.
function xhr(success) {
$.ajax({
success: success,
error: function() {
$.ajax({ success: success })
}
});
}
Then just pass the success handler once
xhr(function(data){/*magic*/});
Or if you wanna basically avoid redundant configuration of the ajax call use the first object as a template, like this:
function xhr(success) {
var ajaxParams = { success: success };
ajaxParams.error = function() {
$.ajax($.extend(ajaxParams, { transport: 'xhr' }));
}
$.ajax(ajaxParams);
}
I simplified the whole thing a bit, but I hope you get the point.
Edit
Reading that last bit, maybe this will give you some ideas... it's a variation of that last snippet.
function xhr(success) {
var ajaxParams = { success: success };
ajaxParams.error = function() {
var newParams = $.extend(ajaxParams, { transport: 'xhr' });
newParams.success = function() {
// do something
// arguments is a special array, even if no parameters were
// defined in any arguments where passed they will be found
// in the order they were passed in the arguments array
// this makes it possible to forward the call to another
// function
success.apply(this, arguments);
}
$.ajax(newParams);
}
$.ajax(ajaxParams);
}

How can I manipulate an Ajax response before it's injected into the DOM?

Here is what I have so far:
$(function () {
dataValModify('body');
$('body').bind('ajaxSuccess', function (e, xhr, settings) {
dataValModify(xhr.responseText);
});
});
function dataValModify(elem) {
// Code to modify elements within the response.
}
How can I take the Ajax response and modify it before it is injected into the DOM? Previously, I was binding ajaxComplete and modifying the DOM directly after injection, but I would like to modify the response instead. I don't think it makes a lot of sense to find elements in the Ajax response and use them to modify the DOM. I send the xhr.responseText into my function so that I don't reapply the modifications to the rest of the body, which will have already been modified by the time of an Ajax call. Also, is there something better than xhr.responseText to use for this? I couldn't get xhr.responseHTML to work.
EDIT: Right now I'm just using a simple test Ajax call to return an MVC partial view:
$('#ajaxTest').load('<MVC Route>')
If I'm understanding your requirements correctly, they are as follows:
Make an asynchronous HTTP request to get some HTML
Modify the returned HTML using the dataValModify() function
Insert the modified HTML into your element with the ID: 'ajaxTest'
If so then it sounds to me like you need to make a lower level ajax call than what you're using at present i.e. $(elem).load()
Essentially the call to .load() is a wrapper for $.get() followed by a call to $(elem).html(someContent) where "someContent" is the responseText from the HTTP request.
Therefore if you want to modify the response before it's injected into the DOM, then you can do something similar to the following:
$.ajax({
type: "GET",
url: "<MVC Route>",
dataType: "html",
success: function(jqXHR, textStatus, errorThrown){
// Your HTTP call was successful but nothing else has happened with the response yet
// Therefore you can now do whatever you want with the it...
// First modify the HTML using the dataValModify function
// Assumption being that your function returns the modified HTML string
var myModifiedHTML = dataValModify(jqXHR.responseText);
// Inject the modified HTML
$('#ajaxTest').html(myModifiedHTML);
}
});
You can use ajaxComplete to modify the responseHTML itself.
$('body').ajaxComplete(function(e, xhr, settings) {
dataValModify(xhr.responseHTML);
});
Update: I haven't tried it, but it might help:
$.ajaxSetup({
converters: {
"text html": function( textValue ) {
if ( valid( textValue ) ) {
// Some parsing logic here
return dataValModify(textValue );
} else {
// This will notify a parsererror for current request
throw exceptionObject;
}
}
}
});
More info here: http://api.jquery.com/extending-ajax/

Resources