0
   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"?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
            });
          }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.