Chempooro
Chempooro

Reputation: 435

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

Upvotes: 0

Views: 60

Answers (2)

Muhammad Aamir
Muhammad Aamir

Reputation: 103

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

Upvotes: 2

Asif Chaudhary
Asif Chaudhary

Reputation: 61

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

Upvotes: 1

Related Questions