简体   繁体   中英

Why do i always get NULL in php response when i try to send some variable using ajax

I want to pass some json data from javascript using ajax to php file

I've tried a lot of solutions from internet but none of them is working.

This is my javascript file (a.html):

    <html>
    <head></head>
    <body>
      <script 
      src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" 
      </script>
      <script>
        var dataPwm = {dataHeat : 1};
        console.log(dataPwm)

        $.ajax({
          type: "POST",
          url: "b.php",
          data: {dataHeat : 1},
          //cache: false,
          success: function(response){
            console.log(response);
          }
        });
    </script>
    </body>
    </html>

and this is my php file in same directory (b.php):

    <?php
        $json_string = $_POST["dataHeat"];
        var_dump(json_decode($json_string));
    ?>

i expect the output of 1, but the result is NULL

You did not include Jquery! use this in head and it will work:

<script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous">
</script>

you are using jquery for ajax, therefore you should first load it and then use it. it is that simple. other than that your code is completely correct. and you should expect int(1) in console.

there may be a few problems here

  1. If there is an error in the browser console, then the jquery is not include

  2. You do not need to use json_decode

  3. if you want the result to come here

    console.log (response);

need to do

$dataHeat= $_POST["dataHeat"];
echo $dataHeat;

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