Reputation: 135
I am trying to do a image uploading with ajax. I have run into a bit of problem. I have two functions in func-ajax.php : function doSth(){} and function doSthElse(){}. I want to target the doSth() function This is my javascript side:
var xhr = new XMLHttpRequest();
xhr.open("POST", 'func-ajax.php', true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
How can I specify whick function to send the request?
Upvotes: 0
Views: 2171
Reputation: 1151
You cannot run a specific function from the func-ajax.php
file.
What you should do is create something like ajax-controller.php
, containing
$functionName = $_POST["func"]; // func parameter should be sent in AJAX, determines which function to run
if (function_exists($functionName)) { // check if function exists
$functionName(); // run function
}
And send all requests from JS to this file xhr.open("POST", 'ajax-controller.php', true);
Hope you get the idea.
Upvotes: 2
Reputation: 89
You can add a parameter in the data being sent and that you check for in some sort of if block that you call the function manually from. You could also introduce a framework like Slim, to create an REST-api point that you can hit.
Upvotes: 0
Reputation: 943571
You can't send an HTTP request to a function.
You make a request for a resource. That request can include POST data and it can include HTTP headers.
The server then decides how to respond the request. It might choose to run a PHP program.
It is up to the PHP program to look at the requested resource / POST data / headers and determine which function(s) to run.
Upvotes: 0
Reputation: 671
You want to send GET/POST parameters along with your request, and catch those in the PHP script.
Upvotes: 0