How to run php file from ajax?

Member

by deron , in category: PHP General , 25 days ago

How to run php file from ajax?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 23 days ago

@deron 

To run a PHP file from AJAX, you can make use of AJAX's XMLHttpRequest object to send a request to the server and receive the response. Follow these steps:

  1. Create an HTML file containing JavaScript code and an AJAX request. For example, in your index.html file, you can have:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <button onclick="runPHP()">Run PHP</button>
    <div id="result"></div>

    <script>
        function runPHP() {
            $.ajax({
                url: 'your-php-file.php',
                type: 'GET',
                success: function(response) {
                    $('#result').html(response);
                },
                error: function() {
                    $('#result').text('Error running PHP file.');
                }
            });
        }
    </script>
</body>
</html>


  1. Create a PHP file that performs the desired actions. For example, create a file named your-php-file.php with the following code:
1
2
3
4
<?php
    // Your PHP code here
    echo "Hello from PHP!";
?>


Make sure to replace 'your-php-file.php' in the AJAX request with the correct file path.

  1. Now, when you open index.html in a web browser and click the "Run PHP" button, an AJAX request will be sent to the server, executing the PHP file and receiving the response. The response will be inserted into the result div.


Note: You will need a web server to run the PHP file. You can use tools like XAMPP or WAMP to set up a local development server.