tags:

views:

32

answers:

2

JS:

function ajax_post_var(url, event_id)
{
var info = $.post(url).responseText;
alert(info);
if (event_id == '1')
{
 do something with info...
}
...more if's here...
}

ajax_post_var('http://www.website.com/a.php', 1);

a.php displayed the text TEST;

Why does info show undefined... I'd like to be able to use the returned value for something else.

+3  A: 

Try this:

function ajax_post_var(url, event_id)
{
  $.post(url, function(info)
  {
    alert(info);
    if (event_id == '1')
    {
      //do something with info...
    }
    // ...more if's here...
  });
}

ajax_post_var('http://www.website.com/a.php', 1);

Not sure why you're using $.post and not $.get for this purpose.

jQuery AJAX requests, by default, are asynchronous. This means the call to $.post() would not return a value immediately. The way to go about such things is to use callback functions.

See below for more information:
http://docs.jquery.com/Ajax

Lior Cohen
Thanks... Will continue using it like this. I just thought maybe the other way should work... But I guess it didn't get the value yet and it's funking up...For using POST instead of GET it's because people can click on the same link over and over, POST does not cache the results but GET does... On some browsers anyways it seems. It goes from ON to OFF... But with GET it always stays the same for some reason.
Nuclear
A: 
function ajax_post_var(url, event_id) {
    $.post(url, function(data, textStatus) {
        alert(textStatus);
        if (event_id == '1') {
              //do something with this...
        }
        // ...more if's here...
    });
}
ajax_post_var('http://www.website.com/a.php', 1);
David