Crayl
Crayl

Reputation: 1911

Can't get the result from a PHP script with jQuery

I'am trying to call a PHP script on my local server with jQuery inside an CasperJS function, but somehow I don't get the result. Here is my code:

casper.then(function() {
    var result = casper.evaluate(function() {
        var result = $.get('http://localhost/test.php', function() {});
        return result;
    });
    result = JSON.stringify(result);
    this.echo(result);
    this.exit();
});

It does not matter which URL is called, it delivers always the same result:

{"abort":{},"always":{},"complete":{},"done":{},"error":null,"fail":{},"getAllRe
sponseHeaders":{},"getResponseHeader":{},"overrideMimeType":{},"pipe":null,"prog
ress":{},"promise":{},"readyState":1,"setRequestHeader":{},"state":{},"statusCod
e":{},"success":null,"then":{}}

Things I have checked:

Don't know what to do. Thanks for any suggestions!

Upvotes: 0

Views: 151

Answers (3)

Shawn G.
Shawn G.

Reputation: 622

I would recommend changing your async to false in $.ajaxSetup();

and also, you should get your return data from within the callback success function

casper.then(function() {
    var result = casper.evaluate(function() {

        var $return = ''; // initiate $return

        var async = $.ajaxSetup()['async'];
        $.ajaxSetup({'async':false}); // Set async to false

        $.get('http://localhost/test.php', function( data ) {

            $return = data; // test.php return data is saved to $return

        });

        $.ajaxSetup({'async': async }); // Set async to back to original value

    });
    result = JSON.stringify($return);
    this.echo(result);
    this.exit();
});

The only downside to this, thanks to Esailija for pointing it out, is that your page will 'hang' until the request is completed

Upvotes: 1

MueR
MueR

Reputation: 977

Nowhere on the jQuery docs for $.get() does $.get() return the contents of the page. You're using the http transport instance.

Upvotes: 0

Esailija
Esailija

Reputation: 140220

$.get is asynchronous, its result won't be available until the callback is called.

casper.then(function() {
    var _this = this;
    casper.evaluate(function() {
        $.get('http://localhost/test.php', function(result) {
            _this.echo(result);
            _this.exit();
        });
    });
});

Upvotes: 1

Related Questions