How to bind variable to jquery ajax request? - javascript

This is self-explanatory:
while (...) {
var string='something that changes for each ajax request.';
$.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'}).done(processData);
}
function processData(data) {
// get string into here somehow.
}
As you can see, I need to get string into processData somehow. I can't make a global variable because string is different for every ajax request. So, the question is, how do I bind string to my ajax request so that I can access it from processData?
I really don't want to have to append string to the query and have the server return it, but if this is my only option, I have no choice.
Thanks in advance.

try in this way:
while (...) {
var str = 'something that changes for each ajax request.';
(function(_str) {
$.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php'})
.done(function(data) {
processData(data, _str);
});
}(str));
}
function processData(data, str) {
console.log(data, str);
}
and no global variables were used :)

var string='something that changes for each ajax request.';
// Use a closure to make sure the string value is the right one.
(function() {
// Store the "string" context
var that = this;
$.ajax({
'type': 'GET',
'dataType': 'json',
'url': 'get_data.php'
}).done(
$.proxy( processData, that )
);
}(string));
function processData( data ) {
this.string === 'something that changes for each ajax request.' // true
}
$.proxy is the jQuery version (cross-browser) of .bind().
You could add an argument as #Joel suggested (in his deleted answer), but the less arguments the better.

$(document).bind("ajaxSend",function(){
$("#ajax_preloader").show();
}).bind("ajaxComplete",function(){
$("#ajax_preloader").hide();
});

Related

How to create callback function using Ajax?

I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.
When I try this:
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.
Here is the full code:
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.
I have tried this and I still don't get a return value outside of the get_emailno function.
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
async: true,
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.
Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?
Thank you.
From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).
When you return data from the server in another function like this
function get_emailno(emailid, mailfolder) {
$.ajax({
// ajax settings
});
return email_number;
}
Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.
Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.
There are two ways you can define callbacks.
1. Define them within the jquery ajax request settings like this:
$.ajax({
// other ajax settings
success: function(data) {},
error: function() {},
complete: function() {},
});
2. Or chain the callbacks to the returned jqXHR object like this:
$.ajax({
// other ajax settings
}).done(function(data) {}).fail(function() {}).always(function() {});
The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().
On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).
With this knowledge, you can better write your code to catch the data returned from the server at the right time.
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
// sufficient to get returned data
email_number = data;
// use email_number here
alert(email_number); // alert it
console.log(email_number); // or log it
$('body').html(email_number); // or append to DOM
}
});
}

How to submit a form and pass some extra parameters to a $.getJSON callback method?

I know how to pass some parameters to a JQuery $.getJSON callback method, thanks to this question:
$.getJSON('/website/json',
{
action: "read",
record: "1"
},
function(data) {
// do something
});
And I can also submit a form to a $.getJSON callback method:
$.getJSON('/website/json', $(formName)
function(data) {
// do something
});
But I want to pass some parameters AND submit some form elements. How can I combine the two things togheter?
I could serialize the form elements and manually add some parameters to the url, and it looks like it works:
$.getJSON('/website/json',
'action=read&record=1&'
+ $(formName).serialize(),
function(data) {
// do something
});
But it doesn't look very elegant. Is this the proper way, or there's a better way to do it?
We could implement the functionality demonstrated in this answer as a custom jQuery instance method which produces an object of key/value pairs from a form and combines it with the properties that aren't derived from the form:
$.fn.formObject = function (obj) {
obj = obj || {};
$.each(this.serializeArray(), function (_, kv) {
obj[kv.name] = kv.value;
});
return obj;
};
$.getJSON('/website/json', $(formName).formObject({
action: "read",
record: "1"
}), function(data) {
// do something
});
Make an Ajax post to send the data to the server. Retrieve the parameter data in the backend code along with the form data.
var formData = {data from form};
formData.action = 'read';
formData.post = '1';
$.ajax({
url: '/website/json',
type: "post",
data: formData
}).done(function (data) {
// remove prior values set upon request response
formData.action = null;
formData.post = null;
});

Jquery returns [Object object] from POST function

i want to get a string from a php file, using a jquery post.
function getString(string) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
});
};
in the firebug console i can see that the desired string is found, but if i want to get it with
var blub = getString("test");
alert(blub);
only "object Object" is shown.
just cant get where my mistake is..
That Ajax request that is made to the server is performed asynchronously, so the ajax method actually returns an object representing the request itself, rather than the actual response from the server.
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object.
You could use the success callback instead:
function getString(string) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
success: function(result) {
alert(result);
},
});
};
Or if you want to be a bit more flexible, you could take the callback function as a parameter:
function getString(string, callback) {
return $.ajax({
type : 'POST',
url : 'scripts/getstring.php',
data : { 'string': string }
success: callback,
});
};
getString('test', function(result) {
alert(result);
})
You are returning an jQuery jqXHR object.
If you want to deal with the data from the HTTP response, then you need to add a done (or success handler.
blub.done(function (data) {
alert(data);
});
object Object is the expected response, because the data being returned is and object.
If you want to see the resultant object, try:
console.log(blub) instead and view it in the console.
This can then help you determine the correct path to the data you want to retrieve in the object.

Checking a Url in Jquery/Javascript

All I need is a method that returns true if the Url is responding. Unfortunately, I'm new to jQuery and it's making my attempts at writing that method rather frustrating.
I've seen several examples of jQuery using .ajax, but the code is consistently failing on me. What's wrong?
var urlExists = function(url){
//When I call the function, code is still executing here.
$.ajax({
type: 'HEAD',
url: url,
success: function() {
return true;
},
error: function() {
return false;
}
});
//But not here...
}
That isn't how AJAX works. AJAX is fundamentally asynchronous (that's actually what the first 'A' stands for), which means rather than you call a function and it returns a value, instead you call a function and pass in a callback, and that callback will be called with the value.
(See http://en.wikipedia.org/wiki/Continuation_passing_style.)
What do you want to do after you know whether the URL is responding or not? If you intended to use this method like this:
//do stuff
var exists = urlExists(url);
//do more stuff based on the boolean value of exists
Then what you instead have to do is:
//do stuff
urlExists(url, function(exists){
//do more stuff based on the boolean value of exists
});
where urlExists() is:
function urlExists(url, callback){
$.ajax({
type: 'HEAD',
url: url,
success: function(){
callback(true);
},
error: function() {
callback(false);
}
});
}
urlExists() can not return because it needs wait for the request.
Either pass it a callback, or make it synchronous (not recommended, because it locks the browser).
var urlExists = function(url, callback) {
if ( ! $.isFunction(callback)) {
throw Error('Not a valid callback');
}
$.ajax({
type: 'HEAD',
url: url,
success: $.proxy(callback, this, true),
error: $.proxy(callback, this, false)
});
};
Then you can do
urlExists('/something', function(success) {
if (success) {
alert('Yay!');
} else {
alert('Oh no!');
}
});
It also worth mentioning the same origin policy.
Also, returning from an anonymous function's scope will not return in the parent function (like in your original example). It just returns that inner function. To return from an inner to a parent, set a flag and return it.
Basically, there is nothing wrong with your code. See it work here:
http://jsfiddle.net/PK76X/
My guess is that you're using it to check the availability of content on a different domain, which fails because browsers don't allow cross domain ajax-requests.
If the url is from the same domain as your page you can do it. But if it is from a different domain, for example google.com, then it will fail due to cross domain security.
In general, you should probably run your script in Firefox using the firebug plugin. It will give you the details needed to solve the issue.
The ajax and post methods are asynchronous, so you should handle the result in a callback method.
AJAX is basically asynchronous, and that's why the behavior you are describing.
I've used the following, which is free of cross origin, to get a simple true/false indication whether a URL is valid, in a synchronous manner:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
The usage is then trivial:
var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Hope this helps

jquery trouble with getJSON call

Got some basic problem again.
I need to modify a function that previously returned a in code written object.
Im now trying to get the object from json through $.getJSON
function getEventData() {
var result = '';
$.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data) {
result = data;
});
return result;
}
Problem is that result isn't set in the callback function for obvious reasons.
Do you guys have a solution for this?
Edit:
Ok i got an answer that was removed.
I just had to change it abit..
This is the answer that works:
function getEventData() {
var result = '';
url = "ajax.php?cmd=getbydate&fromdate=&todate=";
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
You should program your application in an asynchronous way, which means, that you should use callback functions for you application flow, too, or continue in the getJson callback function. You can also make the request synchronously which should then be able to return the value (or at least assign it and block the function till the callback is completed), but this is not recommended at all:
function getEventData() {
var result = '';
result = $.ajax({
url: "ajax.php?cmd=getbydate&fromdate=&todate=",
async: false,
dataType: "json",
data: data,
success: function(data) {
return data;
}
});
return result;
}
Are you sure that the server returns valid json? It will be better to validate it using a tool like jsonlint. Also make sure that application/json is used as content type for the response.

Categories

Resources