John Davidson

php action code not working with javascript confirmAction()

0 comments
Message:


I have this php file which suppose to have a button to do some checkout functionally action by calling a JavaScript built-in function to do it


<a href="index.php" class="btn btn-danger btn-xs" > onclick="confirmAction()" <i class="icon-edit">Check out</a>

I used confirmAction() like this


<script>
// The function below will start the confirmation dialog
function confirmAction() {
let confirmAction = confirm("Dose the maintenance finished yet?");

if (confirmAction) {

alert("Action Done")

}
else {
alert("Action canceled");
}
}
</script>

if the user pressed ok I want to do php code
which should do post action


controller.php?action=checkout&code=<?php echo $result->CONFIRMATIONCODE; ?>

but I wasn't successful in making it work inside the TRUE case in the javascript function


basically I tried to run the php code without the tag but I failed


any suggestion ?
Thanks



My Answer:
You cannot directly run PHP code within a JavaScript function as PHP is a server-side language and JavaScript is a client-side language.

One way to achieve what you want is to make an AJAX call to the server-side script (controller.php) from your JavaScript function. Here's an example of how you can modify your JavaScript function to make an AJAX call:

javascript
function confirmAction() {
let confirmAction = confirm("Dose the maintenance finished yet?");

if (confirmAction) {
alert("Action Done");

// Make an AJAX call to the server-side script
let xhr = new XMLHttpRequest();
xhr.open("POST", "controller.php?action=checkout&code=CONFIRMATIONCODE; ?>", true);
xhr.send();
}
else {
alert("Action canceled");
}
}


In the above code, an AJAX POST request is made to the server-side script (controller.php) when the user confirms the action. Make sure to handle the POST request in your controller.php file to perform the checkout action.

Remember to sanitize and validate user input on the server-side to prevent any security vulnerabilities.

Rate this post

4 of 5 based on 6173 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us