简体   繁体   中英

Trying to post a javascript variable to a php file using the ajax method : POST but getting an undefined index in $POST array within php file

I have a php file with the directory "JqueryPHP/HighestBid.php". All I want to do is be able to post javascript variables from one file "views/AuctionPage.php" to another file "JqueryPHP/HighestBid.php".

I then want to echo a value from "JqueryPHP/HighestBid.php" into the span tags with the id "price" into "views/AuctionPage.php".

The problem is that when I load the page "views/AuctionPage.php" it shows me the alert with the returned value "hi" but where the text is supposed to be outputted between the span tags, it is telling me that the index within my $POST array is undefined.

在此处输入图片说明

在此处输入图片说明

  //JS views/AuctionPage.php <script> $(document).ready(function() { var auc = "hi"; $.ajax({ url: "JqueryPHP/HighestBid.php", method: "POST", data: {'auctionid': auc }, success: function (result) { alert("result: " + result); } }); }); </script> <script type="text/javascript"> $(document).ready(function() { setInterval(function () { $('#price').load('JqueryPHP/HighestBid.php') }, 333); }); </script> 
 //HTML views/AuctionPage.php <h4 class="price">Highest bid : <span id="price"></span></h4> 

 //PHP FILE "JqueryPHP/HighestBid.php"

<?php
  $auctionid = $_POST['auctionid'];
  echo $auctionid;
?>

When I get rid of the $POST array in "JqueryPHP/HighestBid.php" and just assign auctionid with a normal string.

     <?php
  $auctionid = "hi";
  echo $auctionid;
?>

the text gets outputted between the span tags like it's supposed too so I am having a problem posting the variables to another page and I have no idea why. I have tried many ways to get this to work following examples on stack overflow but to no success.

在此处输入图片说明

This line:

$('#price').load('JqueryPHP/HighestBid.php')

loads the JqueryPHP/HighestBid.php script using GET, and that's another, completely independent request from your AJAX one, that's why the $_POST superglobal is empty. What you need to do is to change the span inside the success function of your AJAX call:

$.ajax({
    url: "JqueryPHP/HighestBid.php",
    method: "POST",
    data: {'auctionid': auc },
    success: function (result) {
        // alert("result: " + result);
        $('#price').html(result);
    }
});

That gives the result you need. Delete the whole setInterval code, you don't need it at all.

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