Reputation: 2281
I am using JQuery post method to send data to a PHP script from an external JS script.
const Url2 = 'MainPage2.php?action=updatePurchaseToDB';
const data = {
name: "test name"
}
//takes 3 arg, url, data to sedn, call back function, data in callback holds the page reqeusted in data
$.post(Url2,data, function(data, status){
console.log('${data} and status is ${status}');
alert("PHP Retrned form server: Status " + status);
});
This is the PHP code in MainPage2.php :
if ($_POST['action'] == 'updatePurchaseToDB'){
echo "<script>console.log('UPDATE PURCHASE CALLED!');</script>";
echo "PHP CALLED AS PURCHASE BUTTON PRESSED";
}
The call back function returns a Success message but I can't see any evidence the PHP code has executed, that is nothing has printed to the console.
Is there something missing in my call to the PHP script?
Upvotes: 0
Views: 47
Reputation: 781068
Since the action is in the URL, you need to access it with $_GET['action']
, not $_POST['action']
. If you want it in the POST
data, you need to add it to the data
object:
const data = {
action: "updatePurchaseToDB",
name: "test name"
}
Your console.log()
call is not substituting the variables correctly. You need to use backticks to create a template literal.
$.post(Url2,data, function(data, status){
console.log(`${data} and status is ${status}`);
alert("PHP Returned form server: Status " + status);
});
Upvotes: 2