I'm using jquery's .ajax() method on a button click.
I wanted to know if there a way in whcih I can use the data that I passed in the data-part of the AJAX call in my success() function.
This is my code,
$.ajax({
url: //my URL here..
type: 'POST',
data:{
projDets : projDetailsArray,
},
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
//I wanted to re-use 'projDets' that I'm passing in the
//'data' part of my code..
}
});
Any help will be appreciated.
Thanks
You could wrap the $.ajax parameter in a closure, set up the "data" value as a local variable, and then reference it both for the "data" value and inside the "success" function:
$.ajax(function() {
var data = {
projDets: projDetailArray
// ...
};
return {
url: // your URL here..
type: 'POST',
data: data,
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
// just reference "data" here!
}
};
}());
Pritish - a quick and dirty way would be to store the json array in a jquery .data() object and then retrieve it as required.
1st, set the data: element to a named array:
// set 'outside' of the $ajax call
var projDetailsData = {projDets : projDetailsArray};
// now store it in a div data object
$("#targetDiv").data("myparams", projDetailsData);
// the data part of the $ajax call
data: projDetailsData,
to retrieve it again:
// get the value stored and call the $ajax method again with it
var projDetailsDataCopy = $("#targetDiv").data("myparams");
worth a try maybe!!
jim
[edit] - also, you could of course store the array in a module level vaiable -yuk!! :)
Related
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
}
});
}
I am working in php codeigniter and I tried like this in my code.
var dataSource = $.ajax({
url: <?php echo $url=$this->BASE_URL."home/destination_place" ?>,
method: "POST",
data: { id : id,firstName:firstName },
dataType: "html"
});
This is my returning array but it is not getting in the data source field
[{"id":"1","firstName":"dubai"},{"id":"2","firstName":"munnar"},{"id":"3","firstName":"wayanad"},{"id":"4","firstName":"kovalam"}]
I hope somebody will help me to solve this.
hopefully
I tend not to use .ajax because it's bulky and messy. The .get() and .post() methods work well and are nice and clean.
var dataSource = '';
$.post('<?= $this->BASE_URL.'home/destination_place' ?>',
{ id: id, firstName: firstName },
function(resp){ dataSource = resp; });
The third argument is the callback function, which takes the response as a function parameter. You can then assign it to a variable outside the callback.
Something to bear in mind is that AJAX is asynchronous. The response value will not be available until the call to the remote machine completes. For this reason, all data processing should be triggered inside the callback function, where in this case we are assigning resp to dataSource.
dataType parameter is the type of data you're expecting to get from server.
If I undearstand correctly, you want to get JSON from server, but u specified dataType as html. Try:
var dataSource = $.ajax({
url: <?php echo $url=$this->BASE_URL."home/destination_place" ?>,
method: "POST",
dataType: "json",
data: { id : id,firstName:firstName },
});
I'm facing a strange behaviour when trying to pass a variable as parameter to a nested ajax request callback:
$('form').on('submit',function(e){
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
e.preventDefault(e);
$.ajax({
type:"POST",
url:dest_url,
data:$(this).serialize(),
dataType: 'json',
success: function(data){
if($.isEmptyObject(data.error)){
// performing some actions
// at this point, data.id contains my id
// We call an other function,
// which performs an other ajax request,
// with data.id as parameter
listRefresh(data.id);
}else{
// error message
}
},
error: function(data){
// error message
}
})
});
function listRefresh(id){
console.log(id); // At this point, id contains my id
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
var src_url = location.href + '?id='+id;
$.ajax({
url: location.href,
type: 'GET',
cache: false
})
.done(function(id) {
console.log(id);
// At this point the console outputs
// all my html code in place of id
// I tried to pass data, response, id, but still the same issue
})
.fail(function() {
//error message
});
}
As said in code comments above, in the listRefresh ajax done callback, my variable seems to disapear and the console.log outputs my entire html code in the console...
I've never seen something like this. Do you have an explanation of why, and how could I pass my id as parameter to the ajax callback ?
The first argument passed to the function in done is the response from the AJAX request. It doesn't matter what you call the variable, that's what will be passed to that function.
You can capture the value in the closure however, simply give it another name and assign it to a local variable. Something like this:
done(function(response) {
var theId = id;
// "response" contains the response from the server.
// "theId" contains the value of `id` from outside this function.
})
The parameter of the .done() method is the response of the AJAX call. If your call returned a HTML page, the id variable got all of the html string assigned to it.
To keep the id in its variable simply use another one like:
.done(function(data) {
console.log(data)
console.log(id);
});
I'm trying to figure out how to access to all the data from a json provided by movie database api, but I don't understand how to retrieve it.
The console log give me an "data is not defined" error.
So here is my code:
$(document).ready (function(){
var key = 'api key provided';
$.ajax({
type: 'GET',
url : 'http://api.themoviedb.org/3/search/movie'+key+'&query=Minions',
dataType: 'jsonp',
data: {
format:'json'
},
error: $('#result').append("errore"),
success: function(data){$('#result').append("ok")}
});
var jsonData=data.results.original_title;
//this give me a data is not provided
});
Here a portion of json:
Let's assume that I only want to access to the release_date propriety, how can I achieve this?
data not is defined out of $.ajax() closure, you need to move the code to success handler like, then loop through the JSON data.results.
success: function(data){
$('#result').append("ok");
console.log(data);
$.each(data.results, function(i, result) {
console.log('Release date is' + result.release_date);
});
}
alternatively, you can define a variable, then update that variable in success handler of $.ajax()
var ajaxResponse;
$.ajax({
/* skipped lines*/
success: function(data){
ajaxResponse = data
}
});
I have the following method:
function priceRange(FESTIVALID){
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
}//success
});//ajax;
//
return formatedPriceRange;
};
The second console.info correctly displays the formatedPriceRange,
but outside the function is undefined.
how can I access this variable out side the priceRange function?
Thanks
It's normal, that's how AJAX works. It's asynchronous, meaning that the jQuery.ajax function returns immediately and in this case formatedPriceRange hasn't yet been assigned a value and once the server responds (which can be for example 10 seconds later), the success callback is invoked and the variable is assigned a value.
So always consume the results of your AJAX requests inside the success callback function.
You also have the possibility to pass the async: false option to your jQuery.ajax call which will perform a synchronous request to the server and block until the result is retrieved. Obviously this will lead to your browser freezing during the execution of the request. So it would no longer be AJAX (Asynchronous Javascript And Xml) but SJAX (Synchronous Javascript and Xml).
You have to make sure that the AJAX request finishes before you access the price range data.
You need to expose the price range data outside the scope of the success function.
Here's how you can do it:
function priceRange(FESTIVALID, callback) {
jQuery.ajax({
url: '/actions/festheads.cfc?method=getPriceRangeByGUID',
type: 'POST',
data: 'FESTIVALID=' + FESTIVALID,
dataType: 'json',
success: function(data) {
console.info("AJAX:qPrices", data.MINPRICE);
formatedPriceRange = '$ ' + data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
callback.call(this, formatedPriceRange);
} //success
}); //ajax;
}
var myFestivalID = 1;
priceRange(myFestivalID, function(priceRange) {
// this code runs when the ajax call is complete
alert('The formatted price range is:' + priceRange);
});
how can I access this variable out
side the priceRange function?
Like Darin said, you have to use your results in the success callback function.
Assuming you're using your current function like this:
var range = priceRange(festivalId);
// ... doing stuff with range variable
You'll want reorganize your code so that anything you do with the range variable stems from the success callback. For example, you can create a function to handle updating the UI with the new range:
function handleRangeVariabe(range) {
/// ... do stuff with range variable
}
Call it from success:
success: function(data) {
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
handleRangeVariable(formatedPriceRange);
}
Flower the steps of sample Code:
//declare function
function priceRange(FESTIVALID, functionCallBack){
//1º step
jQuery.ajax({
url : '/actions/festheads.cfc?method=getPriceRangeByGUID',
type : 'POST',
data : 'FESTIVALID='+FESTIVALID,
dataType: 'json',
success : function(data) {
//3º step, because this function will only trigger when server responds to request
//handle data in other function
functionCallBack(data);
}//success
});//ajax;
//more code
//2º step
//no return value, because this method no know when the data will return of server
//return formatedPriceRange;
};
var formatedPriceRange;
//using function
princeRange(1 , function(data){
console.info("AJAX:qPrices",data.MINPRICE);
formatedPriceRange = '$ '+data.MINPRICE;
console.info("AJAX:formatedPriceRange", formatedPriceRange);
});