Home > database >  Why ajax doesn't send my JS variable to PHP?
Why ajax doesn't send my JS variable to PHP?

Time:12-23

I'm trying to send JS variables to a PHP script (which is included in the page I try to make ajax work)

index.php

include 'PHP/display.php';
<button id="click" onclick="show();">Click !</button>

<script>
  function show(){
    var str = "Yes";
    $.ajax({
      method : 'post',
      url : 'PHP/display.php',
      data: {
        str : str
      },
      success: function(data) {
        console.log(data);
      }
    });
  }
</script>

display.php

<?php
  echo isset($_POST['str']) ? $_POST['str'] : "No";
?>

This keeps displaying "No", but the console shows me the "Yes" I want

This code is my first try with ajax, that's why I try to keep it simple, but it doesn't work.

I've been looking for hours on StackOverflow and not one solution works for me.

Maybe i'm missing something, please help me :(

CodePudding user response:

You can see the url property of the ajax call like the php include, but the difference is that it will be executed until you click on the button. PHP will be able to receive the content of data

You can use jQuery's text method to assign the response to the call to the paragraph as text.

function show() {
  var str = "Yes";
  $.ajax({
    method: 'post',
    url: 'display.php',
    data: {
      str: str
    },
    success: function(data) {
      $('#response').text(data);
    }
  });
}
<p id="response"></p>

display.php

<?php
echo isset($_POST['str']) ? $_POST['str'] : "No";
  • Related