-1

How i can use only 1 ajax function in my code, which will return data only when ajax finish.
Example:

var Jurl = json.php, Jdata='one:AAA';    
jsonRet = json(Jurl, Jdata);    
if(jsonRet) {    
  $('body').prepend(data);    
} else {  
  Jurl = anotherJson2.php;
  Jdata='one:BBB';   
  jsonRet2 = json(Jurl,Jdata);  
  if(jsonRet2) {  
...  
  }  
}  
json(Jurl, Jdata) {  
  $.getJSON(Jurl, {Jdata} , function(data) {  
    if(data ==='finish') {
      return false;  
    } else {  
      return data;
    }
}

But, i cant use this code, i must create some another (one more) function with jsonRet2. So the code will be not optimize... I want maximum less code.

fdrv
  • 852
  • 1
  • 11
  • 21
  • That's a lot of syntax errors. Please fix them before asking about the workings of your code. – Bergi Oct 02 '13 at 00:28
  • 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) – Bergi Mar 01 '14 at 15:32

1 Answers1

0

You have a syntax error, that's all.

if(data['end']===true) { ... }

EDIT

You also need to use a promise to return a value from an async call, please see the example below:

$.getJSON(Jurl, {Jdata} , function(data) {
    var dfd = $.Deferred();

    if(data['end']==='true') {
        dfd.reject(false);  
    } else {  
        dfd.resolve(data);
    }

    return dfd.promise();
});
francisco.preller
  • 6,559
  • 4
  • 28
  • 39
  • Sry, i forgot use "". It is just example, it is not my work code. – fdrv Oct 02 '13 at 00:15
  • You are missing the === operator. You are just assigning the value to data['end'] not comparing it. Also, the thing with async is that you can't return a value, you would need to use a promise, let me get you an example of that. – francisco.preller Oct 02 '13 at 00:17
  • Thank you for your help and time, i think it is what i need. New Deferred logic structure added in my brain =) – fdrv Oct 02 '13 at 00:30
  • One more question, how i can use Deferredand in while? So like while(json(url,data))...While(dfd.success) ... – fdrv Oct 02 '13 at 01:14
  • Not sure if I understand. I suppose you could break out of the while loop when you meet some condition and resolve your deferred promise. – francisco.preller Oct 02 '13 at 01:19