wtm
wtm

Reputation: 166

Javascript/jquery AJAX post WITH VARS function returns undefined

I created this synchronous Ajax function to simply post data:

function postme(id, tt) {
 tt['id'] = id;

 $.ajax({
   async:false, type: 'post', url: 'post.php', data: tt,
   success: function(response){ console.log(response);return response; }
 });
}

The response is: {"Info": "aoaaa"}

The console.log(response); provides the JSON in the console, but the return gives a 'undefined'. I tried calling it like this:

postme('generate', {'1':'ee','w':'yy'});

I tried JSON parse, giving the function a name I tried everything I could found online but it just does not work.

I've looked at How do I return the response from an asynchronous call? but that does not seem to work for me since the function does not send variables like mine, it will just do foo(); or postme(); in my case. How do I do this with vars?

Edit: I do not NEED to use async, if there is a better code to not use it, I would rather use it.

Upvotes: 1

Views: 198

Answers (3)

jfriend00
jfriend00

Reputation: 707158

First off, stop using synchronous Ajax. That's horrible for the user experience and should pretty much NEVER be used.

But, if you are using synchronous Ajax, your problem is that there is no return value from postme(). You are returning inside the success handler, but that just goes back into the ajax infrastructure, not back to the caller of postme(). Instead, you can simply do this:

function postme(id, tt) {
    tt['id'] = id;
    var retVal;

    $.ajax({
        async: false,
        type: 'post',
        url: 'post.php',
        data: tt,
        success: function (response) {
            console.log(response);
            retVal = response;
        }
    });
    return retVal;
}

What you really should do is use asynchronous ajax like this:

function postme(id, tt) {
    tt['id'] = id;

    return $.ajax({
        async: true,
        type: 'post',
        url: 'post.php',
        data: tt
    });
}

postme(...).then(function(response) {
    // process response here
}, function (err) {
    // handle error here
});

Upvotes: 3

Shashi Kant
Shashi Kant

Reputation: 1

Suppose the return value is used in some function, such as:

function foo(response) { /* some code */}

then provide foo as callback.

function postme(id, tt, callback) {
 tt['id'] = id;

 $.ajax({
   type: 'post', url: 'post.php', data: tt,
   success: callback
 });
}

and you call the function 'postme' as:

postme(param1, param2, foo)

Upvotes: 0

Dave
Dave

Reputation: 10924

I agree that synchronous AJAX should be avoided, but if you must this should work:

function postme(id, tt) {
 var r = null;
 tt['id'] = id;

 $.ajax({
   async:false, type: 'post', url: 'post.php', data: tt,
   success: function(response){ console.log(response);r =response; }
 });

 return r;
}

Upvotes: 1

Related Questions