Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get access to the data returned from a jquery ajax call? outside the $.ajax(...);

Tags:

jquery

ajax

How do i get access to the data return from jquery ajax call. Outside the $.ajax( ).

//Reloads the inital page
function jobexist( jobname )
{
   var dataString = 'jobname=' + jobname;
   var found = false;

   $.ajax(
   {
      type: 'POST',
      url: "/genode/jobs/jobexist.m",
      data: dataString,
      dataType: 'json',
      success: function(data)
      {
         alert("Passed");
         if( data.result == 0 )
         {
            found = true;
          }else{  
            found = false; 
          }
      },
      error: function( data )
      {
         alert("Login Failed");
         return -1; //alert(data);
      }
   });

   if( found == true )
   {
       alert("found!")'
       return true;
   }else{
       alert("not found!");
       return false;
    }
}



if( !jobexist(jobname) )
{
    $("#jobname_error").text("This jobname already exist.");
    $("#jobname_error").show();
    return false;
}
like image 307
Scott Dolan Avatar asked Dec 07 '10 16:12

Scott Dolan


1 Answers

Ajax works asynchronously so your if found statement will be hit before the ajax call finishes.

What you can do is call a function from inside your ajax success function and pass whatever data you want to it

function found(data){

   if( data.result == 0 )
   {
       alert("found!")
       return true;
   }else{  
       alert("not found!");
       return false;
   }
}

$.ajax(
   {
      type: 'POST',
      url: "/genode/jobs/jobexist.m",
      data: dataString,
      dataType: 'json',
      success: function(data)
      {
         alert("Passed");
         found(data);
      },
      error: function( data )
      {
         alert("Login Failed");
         return -1; //alert(data);
      }
   });
like image 175
wajiw Avatar answered Oct 05 '22 22:10

wajiw