Passing parameters to a function in Ajax - javascript

I'm following a tutorial on using Ajax with JavaScript, and this was the code we're making:
$('document').ready(function(){
$.ajax({
url: "AwesomeText.html",
type: "GET",
datatype: "Html"
})
.done(Success)
});
function Success(result){
$("p").append(result);
}
I got how it worked but there is one thing that confused me. We made a Success function to append the requested HTML file to the paragraph in the page, and then we passed a parameter called result, so from what I understand I can name the parameter anything and pass it as an argument and it will work. I took out success and passed in x as an argument and it still worked..
so my question is how does JQuery know it should store the requested HTML document in this parameter we're creating in this function? what if I have other functions will Jquery store the requested file to every function in it's parameter? I don't get how JQuery knows.
Also, there is a .done function in there, is that the same function that's explained here:
https://api.jquery.com/deferred.done/
why is it called deferred?

Default .done() callbacks will have 3 arguments passed through so based on your need you can use any of them in your success function with your own name.
three arguments passed are data, textStatus ,jqXHR
so your success function's first argument would be the response of the ajax call,i.e data recieved from the server,
second argument would be the status and third argument would the the jqueryXmlHttpRequest object.
based on your need you can access these objects in the same order

When you pass url to ajax it basically fetches that url and returns whatever it got at that url, AwesomeText.html in your case
and then it sends the content of that url to success function as a first parameter
Documentation
success = Type: Function( Anything data, String textStatus, jqXHR jqXHR
)
deferred .done(fn) method makes calling some method after the method on which .done was called [You can say Promise ] which makes synchronous calls
You can check following question for understanding the promises and .done() method
jQuery deferreds and promises - .then() vs .done()

The .done method accepts a "success" function as input.
Success: Function( Anything data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn.
So, the first argument (call it whatever - data / result / x / etc) will contain the reply of the server.
Source: http://api.jquery.com/jquery.ajax/

Related

about $.get() callback function argument

When I use Ajax for asynchronous communication, I may use the $.get() method, which is often used in callback functions as follows:
$.get('http://example.com', function(result) {
console.log(result);
})
I just wonder about 'result' parameter.
Where did that parameter that says 'result' come from?
It doesn't matter if I put any name in it, so I can't put a second or third argument in that function? If it can be put in, how should it be handled?
When you define a function, you can give the parameters any name you like (so long as they are valid identifiers):
function foo(a, b, c) { }
When the function is called, the arguments are passed to those parameters in order:
foo(1, 2, 3);
It is exactly the same for:
function(result) {
console.log(result);
}
The only difference is that the function is called by code written by someone else (which is part of the jQuery library).
The documentation tells you what arguments are passed:
success Type: Function( PlainObject data, String textStatus, jqXHR jqXHR ) A callback function that is executed
if the request succeeds. Required if dataType is provided, but you can
use null or jQuery.noop as a placeholder.
The callback will be invoked when the query is succeeded, then jQuery will pass the data to the first argument, and the following arguments is textStatus and jqXHR. For more you can check the documentation here: https://api.jquery.com/jQuery.get/

Ajax json requests and responses

I'm hoping I can get some help understanding what's happening in this bit of code at a rather fundamental level.
I know that this is basically making a call to the specified URL. I also know that it should be returning a JSON object. If the call succeeds, then it calls my displayResults function, which I defined below.
The displayResults function takes a single parameter.
If I pass it a simple string for example ("response", in the code), everything works fine. However, I'd like to pass the response object from the API call as an argument to the function, but I cannot figure out how. Does the response object have a specific name I should be using?
$.ajax({
url: wikiAPI,
dataType: "json",
success: displayResults //dont call the function, pass it. it will be called when the response is ready.
});
function displayResults(data){
console.log(data);//here is your response
$(".results").html("<p><h3>Hello World!</h3></p>");
}
You have to understand that in Javascript, functions are "first-class", meaning that a function can be treated exactly as you would treat any other variable: you can pass it to another function as a variable, and return it from another function.
This is heavily used in javascript, especially as callbacks.
When you call the $.ajax function, you provide it an object as an argument. This object will contain the callback functions for different states of the ajax request -- one of which is success.
So, basically, the key success needs to have a value of type function.
Now, when you say displayResults("response"), you are calling the function displayResults with an argument "response" -- the return type of which is not a function.
If you just say displayResults without the (), you are treating the function exactly as you would do any other variable. The function is not executed.
You can do stuff like:
var functionAlias = displayResults;
Just like any other variable.
In the same way, you can do this:
$.ajax({
url: wikiAPI,
dataType: "json",
success: displayResults
});
Now, jquery will call the function you have provided when the ajax request has succeeded.
You can read the documentation for what arguments to expect in the function:
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR
)
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object.
So, your displayResults function will receive three arguments: data (can be of any type), textStatus (string), and jqXHR (XMLHttpRequest object). Although the argument names can be anything you want, it is common practice to keep it consistent with the docs.
about the success method parameter, it has no specific name it's dynamic take a look at this link JavaScript Object Methods
about your code,make your ajax call like below
$.ajax({
url: wikiAPI,
dataType: "json",
success: function(data){
displayResults(data)
},
error:function(erData):function{cosole.log(erData)}
});
It seemsdisplayResults method is not complete since it receive an object as input you should iterate through your object in your method like below
function displayResults(data){
console.log("Ajax success response data:", data);
$.each( data, function( key, value ) {
$(".results").append(data.YourProperty);
})
};
do note that I used error method to make sure ajax call succeeded if not the error method will be fired
Hope it hepls
Try with this
$.ajax({
url : wikiAPI,
dataType : "json",
success: function(response){
displayResults(response)
}
});
})
function displayResults(data){
console.log("Ajax success response data:", data);
$(".results").html("<p><h3>Hello World!</h3></p>");
}

Why parameter gets assigned to callback?

I have a javascript function as:
function triggerUpload(success, error, callback) {
var options = {
type: 'post',
success: success,
error: error
};
$("input[name=file]").change(function() {
$(this).parent().ajaxSubmit(options);
});
if (callback) {
callback();
}
}
And i use it as:
triggerUpload(function() {
applyPostAjax(postUrl);
});
It works well as: When someone clicks on a Upload the triggerUpload event occurs with applyPostAjax as its parameter assigned to callback which can be kept null as its optional.
Note: These methods were coded by someone else and i can't get them clearly. I'm a newbie to javascript.
My issues is: i pass only one argument to this function. one would think that argument would get assigned to success. How/why does it get assigned to callback? What are these success, error parameters are here for?
Please explain
The parameters success and error are callback functions (same like the parameter you decided to call "callback") that gets executed when the ajaxSubmit method either successfully transmits the form data or encounters errors.
So, in your function call, you've supplied the success callback but not the error callback or callback callback. Since your function gets executed one can assume that the ajaxSubmit operation has successfully submitted the form.
One would be 100% correct to think that the argument gets assigned to success and not to callback.
Full documentation of the jQuery Forms Plugin available here: http://malsup.com/jquery/form/
and here: https://github.com/malsup/form
Specifically, the documentation of the success callback states:
success
Callback function to be invoked after the form has been
submitted. If a 'success' callback function is provided it is invoked
after the response has been returned from the server. It is passed the
following arguments:
1.) responseText or responseXML value (depending on the value of the dataType option).
2.) statusText
3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
What this means is that the correct prototype of the success function should be:
triggerUpload(function(response,status,xhr,form) {
applyPostAjax(postUrl);
});
Though it's perfectly fine to supply a function with more or fewer parameters because javascript allows functions to be called by fewer or more arguments than exist in their formal declaration. So if you're interested in only the result of the upload function you can just do:
triggerUpload(function(response) {
applyPostAjax(postUrl);
});
Or if you don't care about the response from the server you can just call it like how you did.
As others said, all the three success, error and callback should be functions. However, they have different purpose:
success - called once the ajax submitting is finished successfully
error - called once there is some error in the ajax submitting
callback - called no matter what is happening with the submitting. I guess this is added just to confirm that the change handler is assigned to the input field.
In other words calling triggerUpload doesn't submit the form. You just attach a handler to the file input button. Once you change it, i.e. you choose a file the form is submitted and you get a response after that.

Explaining jQuery AJAX Success Method

Im trying to use this jQuery script and this is confusing me:
function CallService()
{
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
The bit im confused about is the sucess object. The jQuery documentation says:
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
But this method signature looks nothing like the:
success : function(msg) {//On Successfull service call
ServiceSucceeded(msg);
}
Object that we seem to be passing in.
Questions:
1) What does function(msg){ServiceSucceeded(msg)} mean?
2) What is 'msg' in this context?
3) How on earth am I meant to know how to structure the method sugnature for sucess?
Perfectly reasonable question. :-) In JavaScript, you don't necessarily have to call a function with as many args as it defines, and you don't have to define as many args as you may get called with. Which can be confusing if you're used to more constrained environments. :-)
Answering specifics:
1) What does function(msg){ServiceSucceeded(msg)} mean?
It defines a function (an anonymous one) that accepts one named argument (msg) and calls ServiceSucceded passing in that arg. jQuery will call the function with the three arguments defined by the jQuery documentation for the success function, but this particular success function is only using the first of those (data). More about named functions vs. anonymous functions here.
2) What is 'msg' in this context?
The first argument to the function. jQuery's docs call this first argument data, but you can call it whatever you like.
3) How on earth am I meant to know how to structure the method sugnature for sucess?
You did the right thing, it's in the jQuery documentation.
This thing about function arguments can be confusing, so let's do some examples:
function foo(arg) {
alert(arg);
}
That's perfectly clear, I'm defining a function called foo that takes a single named argument, arg. And thus:
foo("Hi there"); // alerts "Hi there"
But I can also do this:
foo(); // alerts "undefined"
There, I didn't give any arguments for foo, and so within foo, arg is undefined.
I can also do this:
foo("Hi there", "again"); // alerts "Hi there"
I'm calling foo with two arguments, but foo only makes use of one of them.
I could define foo to use as many arguments as you pass in:
function foo() {
var index;
for (index = 0; index < arguments.length; ++index) {
alert(arguments[index]);
}
}
arguments is an automatic thing all functions have, which is a pseudo-array (it's not really an Array) of the actual arguments the function was called with. And so:
foo("Hi there", "again"); // alerts "Hi there", and then alerts "again"
You can even mix named and unnamed arguments:
function foo(arg) {
var index;
alert(arg);
for (index = 1; index < arguments.length; ++index) {
alert("[" + arguments[index] + "]");
}
}
So now
foo("Hi there", "again"); // alerts "Hi there" and then alerts "[again]"
Note the [] around the second alert, because I started looping with index 1 rather than zero.
arguments and named args are connected:
function foo(arg) {
alert("arg = " + arg);
alert("arguments[0] = " + arguments[0]);
arg = "Updated";
alert("arg = " + arg);
alert("arguments[0] = " + arguments[0]);
}
If I do foo("Hi");, that shows these alerts:
arg = Hi
arguments[0] = Hi
arg = Updated
arguments[0] = Updated
(It goes the other way, too, if you update arguments[0].)
The function is passed 3 parameters: data, status, and the jqXHR object. data is what is returned from the AJAX call, status is the HTTP status code (I think), and jqXHR is a jQuery wrapped XHR object.
In this script, they only care about the data parameter, and not the other two.
So using success: function(msg), they only get the data parameter. The other two are sent, but ignored.
ServiceSucceeded is just a function that is being called with the data parameter sent to it.
success: ServiceSucceeded could have also worked here.
It means the success handler invokes ServiceSucceeded with the response of the request.
msg contains the response from the request. msg maps to data in the jQuery documentation.
You need to look into the jQuery documentation for finding the signature.
This is an anonymous function.
It's like a regular function, but without a name.
msg is the function's first parameter.
By reading the documentation.
jquery Ajax is a way for you to communicate with the server (PHP, ASP, whatever). Let's assume you use PHP. the function "callService()" send a request to "varUrl" (validation.php, i.e) and get (or POST -> varType) the content (varContentType -> valdation.php?id=1231&whatever=soemthing). The purpose of this is to get some server side data without reloading the page. If you want the validation.php to echo some html, then the dataType in the Ajax function must be "html". See jquery.com for more info on dataType.
The success parameter is a function handler for the server response. Success is called if you get a response from the server corresponding to the dataType you asked (html, json, text, whatever). In that perticular case, if the server respond correctly, the function "ServiceSucceeded" is called with the attribute "msg" which is the server response you asked for.
1) That function is called if the AJAX request is successful i.e. a success status code is returned by the server being contacted.
2) I would assume that 'msg' is the data returned from the server. The other two arguments are not supplied and therefore not used.
3) Use the Jquery documentation, and fiddle around until you get what you want.
Even though the success function is defined as taking three parameters (as per the documentation you quoted), those three parameters are not mandatory - Javascript is very forgiving about this sort of thing; if you miss a parameter from a function call, it simply gets set to underfined, so as long as you don't try to use it, JS won't throw any errors.
The code you've provided only gives one parameter - msg - but in JS, this is perfectly valid; it just means that msg will be the data parameter defined in the docs, and textStatus and jqXHR will be undefined.
This is fine, as long as in your success function you don't actually want to use either of those parameters. If you want to use them, then pass them, but if not, it's fine to drop them. You're writing the success function, so you get to decide which of the three parameters to use.

Can I use a static (i.e., predetermined) callback function name when requesting JSONP with jQuery?

The jQuery documentation lists the following example of using $.getJSON to request JSONP:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data) {
$.each(data.items, function(i,item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if (i == 3) return false;
});
});
Rather than use this method, which generates a dynamic callback function name because of this parameter:
jsoncallback=?
I want to be able to set that in advance to a hardcoded function name, like this:
jsoncallback=test
This works, in the sense that I run the script and the JSONP that I get back has the JSON object wrapped in a call to test().
However, I can't figure out how to set up the callback function. Shouldn't it be as simple as this?
function test(data) {
console.log(data);
}
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=test");
When I try that, I get back the JSONP which is wrapped in test(), but the function test() that I've defined is never called. Am I missing something?
Thanks for any help!
As defined in the documentation for you to use the following method
jQuery.getJSON(...)
you need to specify callback=? when making a JSONP call. I usually only uses this for response types of "json". For response types of "jsonp", you want to use:
jQuery.get(...)
and specify the type as "jsonp". See this documentation on the subject. But that is also bound by the fact of having to have a callback=?.
What I think you are looking for is this:
jQuery.getScript(...)
Which should execute whatever method you have defined in your callback.
Ah, the "Related" sidebar section saved me here. After I submitted this question, I found a similar one already asked:
using a named function as the callback for $.getJSON in jQuery to satisfy Facebook request signing demands
Duncan's answer from Oct. 15 solved this for me:
window.fixed_callback = function(data){
alert(data.title);
};
$(function() {
$.getScript("http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&tagmode=any&format=json&jsoncallback=fixed_callback", function(data) {
alert('done'); } );
});
I guess the key is using $.getScript instead of $.getJSON. One can still specify an anonymous callback function in the parameters of the $.getScript method, which will be executed after the callback function named in the request URL parameters ("fixed_callback" in this case). Hope this helps someone down the road.

Categories