简体   繁体   中英

Pass variable via ajax to api.php

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?

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']

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

尝试按类型替换方法:

  type: "POST",

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