skip to Main Content

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);
  }
?>

2

Answers


  1. 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");
                }
            });
        } 
    
    Login or Signup to reply.
  2. 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);
      }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search