Reputation: 13
I know that to send data to a php file using $.ajax is something like this:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
What I'd like to know is if it is possible to send the data on a specific function inside that file. If it is, can you show me how? Thank you.
Upvotes: 0
Views: 1405
Reputation: 572
you can do it by following code. add one more parameter to your ajax call, like file_name=your_function_name, for instance here i send the ajax request as your data with function_name=getResult, it will call the getResult function in php file.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston", function_name: "getResult"}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
<?php
$function_name = $_POST['function_name']
switch($function_name){
case $function_name:
getResult();
break;
case $function_name:
updateFunction();
break
}
?>
switch statement is optimized way when you are having more cases.
Upvotes: 1
Reputation: 30488
Yes, for that you have to check which function you have to call. Also there is no need to pass the POST
parameters inside function because $_POST
is superglobal array
you can access them inside function without passing via parameter.
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston", func : 'add' }
In some.php
if(isset($_POST['func']) && $_POST['func'] == 'add') {
// call function here and pass parameter
func_add();
}
Upvotes: 0
Reputation: 904
add an action paramater to your ajax :
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston", action: "action1" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
and in your php file :
<?php
if($_POST['action'] == action1) {
action1(); //Do the function named "action1"
}
?>
Upvotes: 0
Reputation: 1308
You don't, but you could add a query string to the url: someurl.php?function=MyFunction and use $_GET['function'] to find out which function should handle the request.
Upvotes: 0
Reputation: 5400
Create your some.php PHP file like this:
<?php
foo($_POST);
function foo($postData) {
// Process the data
var_dump($postData);
}
The above code will immediately pass the data that is posted to the given function 'foo'.
Upvotes: 1