0

I'm trying to return AJAX response data like below..

        function reqNodelistByField( i ) {
            $.ajax({
                type: 'post',
                url: './req.nodelist.by.field.php',
                dataType: 'text',
                data: { field_id:i },
                success: function(data) {
                    r = $.parseJSON(data);

                    if(r.valid === false) r = false;
                }
            });
            alert(r);

            return r;
        };

Response data is perfect. However I don't know how to return this data outside the function.

Only I can see from alert(r) is undefined.

How can I return data?

GatesPlan
  • 465
  • 1
  • 4
  • 17

3 Answers3

0

try this :-

function reqNodelistByField( i,callback) {
        $.ajax({
            type: 'post',
            url: './req.nodelist.by.field.php',
            dataType: 'text',
            data: { field_id:i },
            success: function(data) {
                r = $.parseJSON(data);
                callback(r);
                //if(r.valid === false) r = false;
            }
        });

    };

use it like :-

reqNodelistByField("value of i",function(r){
// here you use the r i.e data from ajax request
// check  here 
  if(r.valid === false){
   }
});
Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68
0

alert(r) is undefined because you are perfoming an asynchronous call, in other words, your script makes the call and continue executing the code without wait for call's response. For that, you need return the r in the ajax success function.

 function reqNodelistByField( i ) {
            $.ajax({
                type: 'post',
                url: './req.nodelist.by.field.php',
                dataType: 'text',
                data: { field_id:i },
                success: function(data) {
                    r = $.parseJSON(data);

                    if(r.valid == false) {
                         return false
                    }
                    else{
                         return true
                     }
                }
            });
        };
levi
  • 22,001
  • 7
  • 73
  • 74
  • I forgot "asynchronous".. so I just add `async: false` in my code and work perfectly as I expected. Thank you!! – GatesPlan Aug 07 '14 at 09:41
  • my advice, dont use `async: false` because if your ajax call takes a lot time, your page will not render properly. Find a best way to execute your code inside the success function. – levi Aug 07 '14 at 15:27
0

Try Done Docs here.

function reqNodelistByField( i ) {
            $.ajax({
                type: 'post',
                url: './req.nodelist.by.field.php',
                dataType: 'text',
                data: { field_id:i },
            }).done(function(r){
                alert (r)
                console.log(r)
                });
        };
user3109875
  • 828
  • 12
  • 35