Reputation: 18103
var last = 0;
function grabProducts(searchstring) {
var last = 0;
$.post('ajax/products', {
method: 'search',
string: searchstring,
category: $('#search_category').val(),
sort: $('.sort').val()
}, function (data) {
data = $.parseJSON(data);
$.each(data, function (index, b) {
last = "dada";
});
});
}
alert(last);
Gives me alert with "0"
. How can i make it set the variable to "dada"
?
Upvotes: 0
Views: 61
Reputation: 5911
When you POST
something, It needs time for server to respond. Do this:
var last=0;
function grabProducts(searchstring) {
var last=0;
$.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
data = $.parseJSON(data);
$.each(data, function(index, b) {
last = "dada";
});
alert(last);
});
}
Upvotes: 0
Reputation: 413702
You can't make a setup like that work because $.post()
is asynchronous. You'll have to put the "alert" in the callback function you pass to $.post()
.
var last=0;
function grabProducts(searchstring) {
var last=0;
$.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
data = $.parseJSON(data);
$.each(data, function(index, b) {
last = "dada";
});
alert(last);
});
}
The whole point of the callback, in fact, is to provide you with a way to have code run when the HTTP request is complete.
Upvotes: 6