greener
greener

Reputation: 5069

Returning value from jquery function and ajax call

I'm looking to return the value from an ajax call which is inside a jquery function. I have this code but it returns undefined. Any help as to what I'm doing wrong is much appreciated.

$.inlDo = function(action,rec,val) {
    $.ajax({
        type: 'POST', url: 'editFile.php?do='+action+'&record='+rec+'&val='+val,
        success: function(d) {
            return 'ok';
        }
    });
}

alert($.inlDo('del',id,''));

The ajax call is successful so that's not likely to be the problem.

Upvotes: 0

Views: 136

Answers (3)

user1386320
user1386320

Reputation:

Try like this:

$.inlDo = function(action,rec,val) {
    return $.ajax({
        async: false,
        type: 'POST', url: 'editFile.php?do='+action+'&record='+rec+'&val='+val,
        success: function(d) {
            return 'ok';
        }
    }).responseText;
}

If you are reciving an XML or a JSON response, you should use some XML parser, or JSONIFY for a JSON response so you could access the response as an object

Upvotes: 1

frozenkoi
frozenkoi

Reputation: 3248

The issue is that this is an asynchronous call. alert is trying to show the result of $.inlDo, but it doesn't return the function you specified as a callback.

The $.inlDo function returns without blocking, i.e. it doesn't wait for the ajax call to complete and then continue executing. The ajax call can complete after (even a while after) $.inlDo returns.

Then what happens is that the callback success gets executed once the data is returned from the server (i.e. the ajax call completes). In this callback you have to deal with the result. This function is the one that should do the alert (like @Zlatan suggests) or update the webpage, etc.

If you want the call to block, i.e. to wait until the response returns, then use the async: false configuration. There are some limitations on when you can use synchronous (blocking) calls.

More info: http://api.jquery.com/jQuery.ajax/

Upvotes: 0

StaticVariable
StaticVariable

Reputation: 5283

You cannot return a value using a ajax call

$.inlDo = function(action,rec,val) {
    $.ajax({
        type: 'POST', url: 'editFile.php?do='+action+'&record='+rec+'&val='+val,
        success: function(d) {
          alert(d);
       //i will suggest you to add a function call back
         compltedRequest(d);
        }
    });
}

function completdRequest(data)
 {
  alert("request has been completed");
 }

Upvotes: 2

Related Questions