tags:

views:

47

answers:

3

I just wanted to check something here - do you have to echo values in PHP to retrieve them via (jQuery)XHR?

for example

PHP:

public function processRequest() {

    //intercept AJAX requests
    if (!empty($_GET)) {

        if (isset($_GET['xhr'])) {
            if ($_GET['xhr'] == true) {
                //process AJAX

                //call relevant method
                echo json_encode(array('key' => 'value'));
                return;
            }
        }
    }

    //else proceed with regular output
    $this->render();
}

jQuery:

function doAjax(){

    $.ajax({
        url: "index.php?xhr=true",
        cache: false,
         dataType: 'json',
         success: function(data){
             console.log(data);
         }
    });
}

This logs a json object in Firebug console with the appropriate values. If I try and return the value instead of echoing, I get nada.

+3  A: 

They have to be echoed to be in the response, so yes they have to be there for jQuery to see them...otherwise the response that the browser gets won't have the content.

As a side note, you can check for the X-Requested-With: XmlHttpRequest header if all you want is to check if it's an AJAX request from jQuery, it already adds this header with every request, for example:

if($_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest'){
Nick Craver
ah, I didn't realise that jQuery added that in, I read on D.Walsh' blog that it wasn't a reliable index
sunwukung
A: 

Return won't do anything because you're not in a function, you're in a separate file. Return will just stop execution gracefully.

You need to echo / print the data for javascript to read it when doing its http request. It does the same as if you'd take that url and open it in your browser.

Fanis
A: 

The response will consist of the rendered page, so when you return it, it returns it within the PHP file, the actual render of the page never sees the value, and therefore neither does jQuery.

Essentially, the jQuery AJAX command will see what your browser will see if you view source.

Robert