You only need to have one processing file in PHP when you are working with AJAX. If you have more than one processing file for every from you create you are wasting your time. This will make your programming less confusing. Lets dive into how using one processing form in PHP is more efficient.
Previous Lessons on Ajax
If you have not already done so it may be helpful for you to watch previous lessons on AJAX. This will give you a better understanding of what we are doing in this lesson.Ajax and PHP scripts For This Lesson
Create a file and call it index.php. Here is the code to put into that file.
<html> <head> <title>Ajax With Multiple Forms And One PHP Processing File</title> </head> <body> <input type="text" id="name" size="50" placeholder="Name"> <button type="button" id="sub" onclick="ajax_post();">GO</button><br/> <input type="text" id="buddy" size="50" placeholder="Your Buddy"> <button type="button" id="sub" onclick="ajax_post_buddy();">GO</button> <br/> <div id="status">You are: </div> <div id="statustwo">Your buddy is: </div> <script> function ajax_post(){ var hr = new XMLHttpRequest(); var url = "processor.php"; var name1 = document.getElementById("name").value; var vars = "namee="+name1; hr.open("POST", url, true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var return_data = hr.responseText; document.getElementById("status").innerHTML = return_data; } } hr.send(vars); // After Check Steps are done execute the request document.getElementById("status").innerHTML = "processing..."; } function ajax_post_buddy(){ var hr = new XMLHttpRequest(); var url = "processor.php"; var buddy1 = document.getElementById("buddy").value; var vars = "buddy="+buddy1; hr.open("POST", url, true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var return_data = hr.responseText; document.getElementById("statustwo").innerHTML = return_data; } } hr.send(vars); // After Check Steps are done execute the request document.getElementById("statustwo").innerHTML = "processing..."; } </script> </body> </html>
Now create a file and call it processor.php and put this code in that file.
if(isset($_POST['namee'])){ echo 'My Name is'; echo $_POST['namee']; } echo $_POST['buddy'];
Thats It!