0

i want to get a string from a php file, using a jquery post.

function getString(string) {
    return $.ajax({
        type : 'POST',
        url : 'scripts/getstring.php',
        data : { 'string': string }
    });
};

in the firebug console i can see that the desired string is found, but if i want to get it with

var blub = getString("test");
    alert(blub);

only "object Object" is shown. just cant get where my mistake is..

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Chris
  • 19
  • 4
  • 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) – Felix Kling Dec 08 '13 at 21:33

3 Answers3

3

That Ajax request that is made to the server is performed asynchronously, so the ajax method actually returns an object representing the request itself, rather than the actual response from the server.

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object.

You could use the success callback instead:

function getString(string) {
    return $.ajax({
        type : 'POST',
        url : 'scripts/getstring.php',
        data : { 'string': string }
        success: function(result) {
            alert(result);
        },
    });
};

Or if you want to be a bit more flexible, you could take the callback function as a parameter:

function getString(string, callback) {
    return $.ajax({
        type : 'POST',
        url : 'scripts/getstring.php',
        data : { 'string': string }
        success: callback,
    });
};

getString('test', function(result) {
    alert(result);
})
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

You are returning an jQuery jqXHR object.

If you want to deal with the data from the HTTP response, then you need to add a done (or success handler.

blub.done(function (data) { 
    alert(data);
});
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

object Object is the expected response, because the data being returned is and object.

If you want to see the resultant object, try:

console.log(blub) instead and view it in the console.

This can then help you determine the correct path to the data you want to retrieve in the object.

brandonscript
  • 68,675
  • 32
  • 163
  • 220