-1

I'm using Javascript to make XMLHttpRequests to various PHP files across my app, such as add.php, update.php, and delete.php. It feels redundant to have (3) different files being called. Is there a way I can put all these 3 files, add/update/delete, inside a single PHP file, like "main_operations.php", and then just make XMLHttpRequests to that single file each time, and have some sort of logic that only executes the part of the file I need? Example, maybe I can set a session variable in the xmlhttpprequest, like $_SESSION['ad_operation'] and then in the "main_operations.php" file use that variable to only run the ad operation?

JDH
  • 35
  • 1
  • 7
  • you can post an extra parameter (POST, GET) to choose which operation will be executed. Then in the php file you will have an if statement for any kind of operation you like. – Chris P Oct 12 '21 at 00:46
  • Ah, thank you! I think I just came up with that idea as you were writing this, see how I edited the last sentence: "Example, maybe I can set a session variable in the xmlhttpprequest, like $_SESSION['ad_operation'] and then in the "main_operations.php" file use that variable to only run the ad operation?" – JDH Oct 12 '21 at 00:48
  • 2
    I think there is no need of $_SESSION variable set. Only $_POST["operation"] or $_GET["operation"] is needed. – Chris P Oct 12 '21 at 00:50
  • Yes, this is possible. Do you have any specific question about that? – Nico Haase Oct 12 '21 at 06:27

1 Answers1

1

You can do it as Chris P said, it is as simple as that.

Example:-

$.post("url",{ action: "update/delete/add", id : "some_ID"},
  function(data,success){//Do something});

PHP file

<?php 
 if(isset($_POST['action'])){
   if($_POST['action'] == "add"){
   //Do add operation
   }
   else if($_POST['action'] == "update"){
   //Do update operation
   }
   else if($_POST['action'] == "delete"){
   //Do delete operation
   }
 }
?>

This helps you to handle the request and control the response.

Mohammed Khurram
  • 616
  • 1
  • 7
  • 14
  • Conceptually, I know what needs to be done. What I'm having trouble with is figuring out how to use xmlhttp.send to send over the $_POST variable to the php file that handles all the operations. Everything else makes perfect sense, just can't figure out how to get the php file to receive that post variable, via ajax, and plain JS. – JDH Oct 13 '21 at 00:22
  • maybe [this](https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest) will answer your question @JDH – Mohammed Khurram Oct 13 '21 at 05:41