简体   繁体   中英

how to send values from PHP to jQuery: echo or return?

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.

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'){

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM