1

After sending data using ajax how to store those on PHP variable? I created a dump file where I can see that variable is sent but can't see them when I echo them? how can I see them? I send get data through URL and post data through XMLHttpRequest(); The data return nicely but why it's not storing on PHP variable?

<?php
//dumping code to see received data
$output = "Post Variables\n";
$output .= print_r($_POST, true);

$output .= "\nGet Variables\n";
$output .= print_r($_GET, true);

$output .= "\nBody Content\n";
$output .= print_r(file_get_contents('php://input') ?: "empty", true);

file_put_contents("dump.txt", $output);
// End


if(isset($_GET['a'])) {
    die('This is post data: ' . htmlspecialchars($_GET['a']));
 
} 
if(isset($_POST['b'])) {
    die('This is post data: ' . htmlspecialchars($_POST['b']));
 
} 
    echo "This is get variable: " .$a;
    echo "This is post variable: " .$b;

?>


<html>
<head>
<script>
//sending ajax request to change table name on onclick event
function clickMe(j){
    // Create our XMLHttpRequest object
    var req = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var dayName = document.getElementById("btn"+j).value;
    var SVAR = "b="+dayName;
    var url = "tempo.php?a="+dayName;
    req.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    req.onreadystatechange = function() {
     if(req.readyState == 4 && req.status == 200) {
      let data_return = req.responseText;
            document.getElementById("status1").innerHTML = data_return;
 
     }
    }
    // Send the data to PHP now... and wait for response to update the status div
    req.send(SVAR);
    
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>


<button id="btn1" value="saturday"  onclick="clickMe(1)">btn1</button>
<button id="btn2" value="sunday"  onclick="clickMe(2)">btn2</button>

<br><br>
<div id="status1"></div>
</body>
</html>
Ravikant Singh
  • 338
  • 5
  • 18
devtz007
  • 43
  • 9
  • It looks like you'd need to define the `$a` and `$b` variables, for example: `$a = $_GET['a'];` and `$b = $_POST['b'];`. Also see [PHP Automatically “GET” Variables](https://stackoverflow.com/questions/258397/php-automatically-get-variables). Is that what you mean? – showdev Jun 29 '19 at 08:38
  • Let's learn the correct use of ajax here : https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest – sylvain Jun 29 '19 at 08:59
  • It sounds to me like you are getting the desired values in `$_POST`, is that right? – showdev Jun 29 '19 at 09:30

2 Answers2

0

The way you use XMLHttpRequest is not right. You should use 2 differents pages : the caller (index.php) and the asynchrone script (tempo.php) To correct your current caller page : index.php : • Use an url without any parameter :

 url="tempo.php"

• Send your two parameters together :

 req.send("a="+dayName+"&b="+dayName);

To debug the asynchrone page : tempo.php, just add a fake get_parameter at the top of tempo.php:

 a = a_possible_value_for_a

and then call tempo.php in your browser directly (without your ajax-page)

sylvain
  • 853
  • 1
  • 7
  • 20
0

Request sent from HTML File.

Sending process one :

  $(document).on("click","#btn1",function(){
   var data = $(this).val();

   /* ajax request sent start */
   $.ajax({
       method:"post",
       url:"phpFileName.php",
       data:{backendPostName:data},
       dataType:"json",
       success:function(response){
           /* Logic implemented here */
       }
   });
  /* ajax request sent end*/
});

Sending process two according to your html structure :

function clickMe(data){
   var data = $(this).val();

  /* ajax request sent start */
   $.ajax({
       method:"post",
       url:"phpFileName.php",
       data:{backendPostName:data},
       dataType:"json",
       success:function(response) {
           /* Logic Implementation here */
       }
   });
  /* ajax request sent end*/

}

When you want to receive this sending data inside php file.

First check this name found or not through php "isset()" function

Example below :

php file :

<?php 
   if(isset($_POST['backendPostName'])){
     $customName = $_POST['backendPostName'];

     /* 
        store or other logic implement here .
        if you wants to echo html then echo "success"; or your choice
        if you wants to return json data then return json_encode(["result"=>1]);
      */

     /* For HTML Return */

    echo "<h1>Success</h1";

    /*For Json return */   

    echo json_encode(["result"=>1]);
 }

?>

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ripon Uddin
  • 709
  • 3
  • 14
  • 29