Home > Article > Web Front-end > How to Post Data to a PHP File Without Reloading the Page Using AJAX?
When attempting to execute code upon clicking a button, you encounter an issue where the post data is not successfully transferred to a specified PHP file named "MonsterRequest.php." Instead, the page reloads itself as if the data is being sent to the main parent page. The objective is to post data without causing the page to reload.
AJAX: Asynchronous JavaScript and XML
To understand this issue, it's important to be familiar with AJAX. AJAX is a technique used in web development to allow data exchange between a web browser and a web server without reloading the page. This is possible using the XMLHttpRequest object in JavaScript, which sends requests to the web server asynchronously.
In your code, you are using $.load to load the "MonsterRequest.php" file into the "CenterPiece" div. However, this method is not appropriate for posting data. It is primarily used to load external content into a specified element.
To post data without reloading the page, you should use the $.ajax method. This method allows you to send asynchronous data to a server-side script and receive a response without affecting the main page content.
Here's a modified version of your code using $.ajax:
Readthis = "MonsterRequest.php?id=<?php echo $_REQUEST['id']; ?>&Mon="; TestVar = TestVar.replace(/\s/g, ""); Readthis = Readthis + htmlencode(TestVar); $.ajax({ url: Readthis, type: "POST", data: { Mon: TestVar }, success: function(data) { // Handle the server response here (e.g., display data in the "CenterPiece" div) } });
In this code, the $.ajax method is used to post the data contained in the "TestVar" variable to "MonsterRequest.php" without reloading the page. The "success" function can be used to handle the server's response and update the DOM as needed.
The above is the detailed content of How to Post Data to a PHP File Without Reloading the Page Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!