0

I am trying to pass a js variable via ajax to the php side. My js code is:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  var sAgentId = 'hi'
  $.ajax({
    url: "api-test.php",
    method: "POST",
    data : { id:sAgentId}
  }).done(function(){
    console.log('done')  
  })

and in the php file, I am trying to get the variable via post:

$sAgentId = $_POST['id'];

But finally in api i get the notification that says

Notice: Undefined index: id in C:\xampp\htdocs\webdev-php-exam-prep\exercise\api-test.php on line 2

Can anyone tell me what I am doing wrong?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sofie
  • 1

3 Answers3

0

Try adding this to your AJAX method:

dataType: "json"

Try also console logging the response back to check $_POST['id'] is being set.

.done(function(data) {
    console.log("Data: ", data);
});

and in your PHP just return $_POST['id']

0
  var sAgentId = 'hi' 
    $.ajax({
        url:'api-test.php',
        type: "POST",
        data: {id: sAgentId },
        cache: !0,
        dataType: 'json',
        success: function(data) {
           console.log(data);
        }
    });
Balamurugan M
  • 580
  • 5
  • 9
-1

try replace method by type:

  type: "POST",
Phi Cuong
  • 1
  • 1