0

Im trying to sort this around, im making an ajax requests of get type, and the page will be returning many responses, OK is one of those, is the page returns OK then I need to proceed for form submitting, else I need to halt the form submission, but Im unable to access the data out side of the function, it is available inside the fall back function alone, is it due to asynchronous mannerism?, can some one assist me to get out of this?

 $.get('ajax.html',function(data){
//some code here
});

if(data == 'ok'){return true; } else {return false;}
Peterson Andrew
  • 243
  • 6
  • 16
  • 1
    http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re#answer-2592780 – Dmitry Teplyakov Apr 23 '14 at 05:51
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Quentin Apr 23 '14 at 08:32

2 Answers2

0

$.get fires an asynchronous request, and the execution of you program continues. So in your case data is available only after the ajax call finishes and only inside your callback function. You need to do whatever you want to do with data inside your callback function.

You need to re-arrange you code to do something like:

$.get('ajax.html', function (data) {
   if(data === 'OK') {
      // do what you need to do in this case
   }
});

// at this point there's no data
Jaime
  • 6,736
  • 1
  • 26
  • 42
  • returning from inside the fallback if not helping to hold form submission. – Peterson Andrew Apr 23 '14 at 06:10
  • You can't do it in the way you are thinking about it. The return from the function that calls has the $.get inside, is not usable, that's the nature of async calls. What you want to do is prevent the form from submitting automatically and submit it manually from inside the callback – Jaime Apr 23 '14 at 17:06
-1

No, you are accessing data which is not a variable available. How about assigning it to another variable?

var resp = "";
 get('ajax.html', function (data) {
   resp = data;
});

if(resp == "OK") {alert(1);}

alternatively you can go use asyn false

$.ajax({
    url: url,
    type: "GET",
    async: false,
    data: data,
    success: function(ret) {
        //alert(ret);
        resp = data;
    }
});
alert(resp);

Cheers!

Gian Carlo
  • 215
  • 2
  • 6
  • you cant really access the data outside the ajax. if you want to access the data you must assign it into a variable outside ajax call. Thanks for the vote down! – Gian Carlo Apr 23 '14 at 08:52