AF1
AF1

Reputation: 17

Execute a PHP function from within a Javascript script

I've looked at all the questions on here and simply cannot get my head around this or get it to work. I simply want to use a button which runs a script that executes a php function.

HTML:

<button id="update_submit" type="button" onClick="myFunction()">Update</button>

Script:

                    <script>
                        function myFunction(){
                            if (document.getElementById("drug_text_name").value=="") {
                                alert( "I am an alert box!" );
                            } else {
                            $.ajax({url: "../script.php", success: function(result){
                                window.location.href = '../drug_manager.php';
                                }      
                                   });
                            }
                        }
                    </script>

PHP file:

<?php
// including the database connection file

    include_once("../../includes/dbh.inc.php");
    $result = mysqli_query($conn, "UPDATE drugs SET Drug_Name='$Drug_Name' ,Allergies='$Allergies' ,Side_effects='$Side_effects' ,Type_of_Medication='$Type_of_Medication',Dosage='$Dosage' WHERE Drug_ID=$Drug_ID");

?>

Here, I would like it to run the SQL query, then redirect the user to the page /drug_manager.php.

Upvotes: 1

Views: 53

Answers (1)

mikaelwallgren
mikaelwallgren

Reputation: 330

First of all, you cannot execute a PHP-function within JavaScript because PHP runs on the server-side and JavaScript runs on the client-side. In your example, your PHP-file is not doing anything because the test function is never executed. If you execute the test function the ajax call will be redirected to that location, read more about it here.

If you want the user to be redirected when they click the button you could simply redirect them with help of window.location.href, something like this:

<script>
$("#update_submit").on('click', function(){
    window.location.href = '../script.php';
)};
</script>

If you want PHP to decide where the user should be redirected your PHP-file could return an URL and then you use window.location.href to that URL. Something like this:

PHP:

<?php
function test() {
    echo "drug_manager.php";
}
test();
?>

Script:

<script>
$("#update_submit").on('click', function(){

    $.ajax({
       url: '../script.php',
       dataType: 'json',
       success: function(data){
           window.location.href = data;
       }
    });
)};
</script>

Upvotes: 3

Related Questions