0

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?

1
  • I do highly recommend implementing any number of solutions posted below, so I can reach different functions on back-end by simply tampering your javascript. Thank you Commented Feb 6, 2014 at 15:41

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You want to send GET/POST parameters along with your request, and catch those in the PHP script.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.