简体   繁体   中英

Ajax send javascript variable to php

I am trying to send a JS variable to a PHP file but it does not seem to be working. In the console its showing an error as an show.php file. I am not able to understand What I am doing wrong.

function details(id) {
  var id = id;
  //   alert(id);
  $.ajax({
    type: 'POST',
    url: 'show.php',
    data: id,
    success: function(data) {
      alert("hi");
    }
  });
}
<button onclick="details(<?php echo $id ; ?>)" class="btn btn-rounded btn-primary">Details</button> 

show.php:

<?php 
  if (isset($_POST['id']))
  {
    $uid = $_POST['id'];
    echo json_encode($uid);
  }
?>

Write data in json object see code below

function details(id)
    {
        var id = id;
     //   alert(id);
        $.ajax({
            type: 'POST',
            url: 'show.php',
            data:  {id:id},
            success: function(data)
            {
             alert("hi");
            }
        });
    } 

Check your network tab and check the sending parameters list . You have to mention datatype json

Try this

function details(id)
    {
        var id = id;
     //   alert(id);
        $.ajax({
            type: 'POST',
            url: 'show.php',
            dataType: 'json',
            data:  {'id':id},
            success: function(data)
            {
             alert("hi");
            }
        });
    } 

In your show.php

<?php 
  if (isset($_POST['id']))
  {
    $uid = $_POST['id'];
    echo json_encode($uid);
  }
?>

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