setting ajax response to a variable

Yesterday I was working on a small task of validation through jquery ajax, I was comparing two dates through ajax and then needs to set an variable on success, which I can use further in the same function but it was not working as per requirement. My code was like

$.ajax({
type: "POST",
url: 'test.php',
data: datastr,
success: function(res) {
result = res;
}
});

This code was not giving me “result” variable and I want to use it further in next ajax request, then I searched and found as the request is asynchronous it will not work and I made the request synchronous, like

var result = '';
$.ajax({
type: "POST",
async: false,
url: 'test.php',
data: datastr,
success: function(res) {
result = res;
}
});

alert(result); // use it here

Now I can use result any where in this function.

3 responses to “setting ajax response to a variable

  1. Good read.

    You could also store it directly into a variable – http://www.web-design-talk.co.uk/303/store-ajax-response-jquery/

    Thanks

  2. irham

    Thanks man it helped me

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Links

phpcamp pune 2011: A gathering of php enthusiast

Twitter

  • #WordPress Theme Files Execution Hierarchy
    http://t.co/o07UCyx4
    2012/02/02 16:00
  • Planning Your Website Effectively- WordPress Is A Tool Not A Strategy
    http://t.co/lKDRhDi5
    2012/02/01 20:50
  • Here is how you can embed a 9slides into a WordPress blog post...
    http://t.co/c4tloCfR
    2012/01/25 23:52
  • awesome RT @itsCharlKruger: Updated #Buddypress Twitter - Download v1.1 & check out the new features in the admin panel
    http://t.co/ubrueciV
    2012/01/19 13:41
  • When NASA decided to make it easy to share their code they choose to build the site in #WordPress
    http://t.co/pLbFnScM
    2012/01/18 23:24

Pages