The trouble is that the $.post is run asynchronously so anything after
the $.post will be executed before the callback function.

If you want the returned data to be available outside the callback
then it will have to be inside a function which is called from within
your callback method.

e.g.

 var data1;

    $.post('save_search.php', formData, function(data) {

         data1 = data;
         handle();

       } );
function handle() {
    jsonData = eval('(' + data1 + ')');

    if (jsonData.return_status.search("successful") > -1)
      $('#msg_div').html("<font color=red>Search was saved</font>");
    else
      $('#msg_div').html("<font color=red>Search was not saved. Try
saving again.</font>");
}

On Aug 19, 11:33 pm, dkomo872 <dkomo...@comcast.net> wrote:
> I have Javascript code that looks like this:
>
>     var data1;
>
>     $.post('save_search.php', formData, function(data) {
>
>          data1 = data;
>
>        } );
>
>     jsonData = eval('(' + data1 + ')');
>
>     if (jsonData.return_status.search("successful") > -1)
>       $('#msg_div').html("<font color=red>Search was saved</font>");
>     else
>       $('#msg_div').html("<font color=red>Search was not saved. Try
> saving again.</font>");
>
> +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
> ++++++++
>
> "data1" comes up as undefined in the statement
>
>   jsonData = eval('(' + data1 + ')');
>
> even though "data" is a perfectly correct JSON string *inside* the
> callback function!  I can put the eval statement inside the callback
> function and it will form a good JSON object, like this:
>
>    jsonData = eval('(' + data + ')');
>
> I'm simply trying to get my Ajax response data to the outside of my
> callback function so I can use it in other Javascript code.
>
> Does anyone know what is wrong?  I've never seen an ordinary function
> behave this way.

Reply via email to