Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from ajax.done()?

I have the following function:

$.ajax({
    url: "../../getposts.php"
}).done(function(posts) { 
    var postsjson = $.parseJSON(posts);
});

How do I use the variable postsjson outside the .done() function, or how do I declare it global?

I can't pass it to another function, because I want to use the array later on, and not when the ajax is completed.

like image 615
wederer Avatar asked Oct 24 '12 20:10

wederer


People also ask

How do I return data after AJAX call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

What is the use of AJAX () method?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.


3 Answers

If you just define the variable outside of the ajax call:

var postsjson;

$.ajax({
    url: "../../getposts.php"
}).done(function(posts) { 
    postsjson = $.parseJSON(posts);
});

Then you can use it outside. Likewise, if you just leave of the var, it will declare it globally, but that is not recommended.

As pointed out by SLaks, you won't be able to immediately use the data you get from the AJAX call, you have you wait for the done function to be run before it will be initialized to anything useful.

like image 195
Xymostech Avatar answered Oct 04 '22 20:10

Xymostech


The cool thing is that the promise returned from the Ajax function can be used in many different ways, here are some:

var XHR = $.ajax({
    url: "../../getposts.php"
});


function somethingElse() {
    XHR.done(function(posts) { 
       var postsjson = $.parseJSON(posts);
    });
}

--

function myAjax(url) {
    return $.ajax({
        url: url
    });
}

function doSomething(url) {
    var postsjson = myAjax(url).done(parsePosts);
}

function parsePosts() {
     return $.parseJSON(posts);
}

doSomething("../../getposts.php");

etc...

like image 36
adeneo Avatar answered Oct 04 '22 22:10

adeneo


You need to declare a variable before calling ajax.

Simple Sample:

var postsjson;

$.ajax({
    url: "../../getposts.php"
}).done(function(posts) { 
    postsjson = $.parseJSON(posts);
});

console.info(postsjson); // Use here for example
like image 26
FabianoLothor Avatar answered Oct 04 '22 20:10

FabianoLothor