0

by using AJAX with method GET to sent data to a php file, how do I retrieve the data in PHP file?

the AJAX and PHP is in the same file

 <script>
   var xhr = new XMLHttpRequest();
   xhr.open("get","kal.php?id=5",true);
   xhr.send();
 </script>
 <?php
   echo "result is : ".$_REQUEST['id'];
  ?>

it says undefined index : id and the value of $_REQUEST['id'] is also empty.

Citra45Abadi
  • 207
  • 1
  • 6
  • 21
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – John V. Apr 28 '17 at 05:35
  • @JohnV. yes, I was just trying to send data from PHP to JS via AJAX and it works. now I'm doing the reverse : sending data from JS via AJAX to PHP and echo it. the problem is that I cannot seem to retrieve it (the data sent) on the same file – Citra45Abadi Apr 28 '17 at 05:44
  • For the cleanest, easiest code to understand, you should split up your php and html/javascript. – John V. Apr 28 '17 at 05:53

4 Answers4

2

When sending an XHR request to the same page you might need to take special care with the PHP code that processes the request. For instance, if you have any output generated on the page before the code that handles the request then you would probably wish to discard that output from the response that is sent back to the javascript callback function. Typically to do this I would use ob_clean() at the beginning of the request handling code and then ensure the response is terminated using exit

<?php
    if( $_SERVER['REQUEST_METHOD']=='GET' ){

        /* 
            listen for XMLHttpRequest requests
            ----------------------------------
            By testing for the existence of a particular header in the request
            you can ensure that a simple pageload with querystring does not
            trigger the id to be displayed.
            The ajax function sets the 'X-Requested-With' header and PHP reads this
            as 'HTTP_X_REQUESTED_WITH'
        */
        if( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] == 'XMLHttpRequest' && !empty( $_GET['id'] ) ) {

            /* discard any previous output */
            ob_clean();

            /* send the response to the javascript client */
            header('Content-Type: text/html');
            exit( 'Response='.$_GET['id'] );
        }
    }
?>
<html>
    <head>
        <title>XHR to same page</title>
    </head>
    <body>
        <div id='msg'></div>
        <script>

            var id=23;

            var xhr = new XMLHttpRequest();

            /* Only display the response if the request succeeds */
            xhr.onreadystatechange=function(r){
                if( xhr.readyState==4 && xhr.status==200 ){
                    document.getElementById('msg').innerHTML=xhr.response;
                }
            };
            /*
                As the request is to the same page you only require the
                query part of the url
            */
            xhr.open( "GET", "?id="+id, true );
            /*
                set some typical headers, including the important 'X-Requested-With' header
            */
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
            xhr.send();
        </script>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • `xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');` is to ensure that the PHP codes only run when there is a request with said header right? – Citra45Abadi Apr 28 '17 at 08:30
  • but which command sends the response? is it `header()` or `exit()` ? I know `exit()` terminates script and output message, but how does it send data to Js client? – Citra45Abadi Apr 28 '17 at 08:37
  • it is the `exit` command that actually sends the data. You could do `echo $data; exit()` but it amounts to the same thing. as for previous comment, yes - to ensure the php interprets the XHR request and responds rather than processing when the main page loads and has a querystring value of id present. – Professor Abronsius Apr 28 '17 at 09:36
  • I see but shouldn't we use `echo json_encode($data)` to send data from php to javascript? because it will change php var into javascript object – Citra45Abadi Apr 29 '17 at 02:09
  • You could - but from your original code there was no use of json so I kept it simple. I've never had any issues using `exit` like this so if you need to use json then you could do `exit( json_encode( $data ) );` – Professor Abronsius Apr 29 '17 at 06:54
0

When the page loads the first time $_REQUEST['id'] is undefined, hence the error, use isset() to prevent it.

Note, when the AJAX request is made, the response is going to be the Javascript code again. Try:

if(isset($_REQUEST['id'])) {
    echo "result is : ".$_REQUEST['id'];
} else {
    ?>
  <script>
     var xhr = new XMLHttpRequest();
     xhr.open("get","kal.php?id=5",true);
     xhr.send();
  </script>
    <?php
}
Enstage
  • 2,106
  • 13
  • 20
  • although there is no Notice message due to `isset()` function, there is nothing echoed either. it is possible to send data into php variable on the same file via AJAX right? I know I can send it to separate file.... – Citra45Abadi Apr 28 '17 at 05:41
0

Since your page is not refreshing / reloading , the contents can only be updated with js. The response data from ajax will contain everything the php page echos / displays. So you can use additional variable to just handle ajax requests.

if(isset($_REQUEST['id']) && isset($_REQUEST['ajax']) && $_REQUEST['ajax'] === true) {
    echo "result is : ".$_REQUEST['id'];
    exit(); // the remaining part will not be returned to the ajax response
} else {
?>
<script>
     var xhr = new XMLHttpRequest();
     xhr.open("get","kal.php?id=5",true);
     xhr.send();

    //write the code to update html on receiving ajax response text
</script>
<?php

}

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • I see the data is actually sent and recieved by server, but because the page does not load for the second time the PHP doesn't trigger echo? – Citra45Abadi Apr 28 '17 at 06:01
0

The first time page is loaded ,ajax not send request yet so you will get undefined index ! Need to check by isset and you are trying to show in the same page ,therefore replace current html content by XML response !!

<script>
   var xhr = new XMLHttpRequest();
   xhr.open("get","kal.php?id=5",true);
   xhr.send();
   xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.body.innerHTML = xhr.responseText;
                }
            }
 </script>
 <?php    
    if(isset($_REQUEST['id'])) {
      echo "result is : ".$_REQUEST['id'];
    }
  ?>
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52