This question already has answers here:
Calling PHP file using AJAX
(3 answers)
Closed 8 years ago.
I have php website showing/hiding the pages through the nav links.
Im wondering how to call my php functions when clicking on the corresponding page link.
Is it possible to use ajax (jquery?) to call one of all the functions on my function.php file?As i understand it ajax will run the whole code in the php file its calling?
$(document).on("click", ".dbLink", function() {
var sText = $(this).attr("data-variable");
$.ajax({
url: '../ini/functions.php?q='+sText,
type: 'get',
success: function(data){
alert(data);
}
});
});
function.php
function a(){
echo "result";
}
if (isset($_POST['action'])) {
switch($_POST['action']) {
case "a":
a();
break;
case "b":
b();
break;
default:
break;
}
}
Put a string in the AJAX parameters, and have your PHP code run different functions depending on the string, e.g.
switch($_GET['op']) {
case "delete":
do_delete();
break;
case "update":
do_update();
break;
...
default:
// Report unrecognized operation
}
In your jQuery code, the handler function should call event.preventDefault or return false to prevent the normal action of the element you click on (I'm guessing it's a link). Also, you need to match the way you send the AJAX request with the way you retrieve the parameter in PHP -- if you use $_POST, you have to use type: 'post' -- and the parameter names must match (you used q in the Javascript, but action in the PHP).
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var sText = $(this).attr("data-variable");
$.ajax({
url: '../ini/functions.php',
data: { action: sText }
type: 'post',
success: function(data){
alert(data);
}
});
});
You can do ajax request to server with your data in request parameters.
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
json_encode($aResult);
?>
You don't call functions from AJAX. With AJAX you retrieve resources.
PHP is a resource preprocessor (as every server-side language is), so it executes code to bring you the so-called resource (html pages, css, images, ... are resources).
So, AJAX does not issue functions, since AJAX is not related to PHP but to HTTP requests.
In that sense, the AJAX-side could understand that it must issue a resource (and it DOESN'T KNOW that resource will trigger a chunk of server-side logic).
So, what you could expect to do is to send arguments (e.g. via GET or POST) and expect a result. In the other (i.e. the PHP) side you should consider those arguments and process them.
Perhaps sending parameters like functionName=func1¶ms=[1,2,%22a%22] and processing them like:
$func = $_GET['functionName'];
$params = json_decode($_GET['params']);
if (function_exists($func))
{
$result = call_user_func_array($func, $params);
echo json_encode($result);
}
else
{
echo "unexistent function";
}
would do the job but, again, AJAX does not know about this, and never will, since AJAX is not related to PHP.
Related
Using the following Ajax POST function on form submit (simplified here):
$form.on("submit", function (i) {
i.preventDefault();
var sendEmail = 1;
ValidateForm(sendEmail, "goSignup");
});
function ValidateForm(sendEmail, action) {
$.ajax({
type: "POST",
url: window.location.pathname,
dataType: "json",
data: {
ajaxRequest: 1,
sendEmail: sendEmail,
}
}
After I post this I want to use a conditional GET parameter that equals 1 (i.e https://www.example.com?test-parameter=1) and then if it's present in the URL use one or another function from there if the ajaxRequest is received from $_POST in my PHP:
public function __construct() {
$testingParameter = $_GET["test-parameter"] ?? '';
if (trim($testingParameter) == '1') { // if has get parameter equal
if (!empty($_POST['ajaxRequest'])) { // if JS postRequest has been posted
$this->handlePostRequests();
}
echo 'has get parameter';
} else { // else use old logic
if (!empty($_POST['ajaxRequest'])) {
$this->handleOtherRequests();
}
echo 'no get parameter';
}
}
Issue:
I get the correct echo from PHP but when I submit the form with Ajax its still using the handleOtherRequests(); instead of the handlePostRequests(); function if I'm using the url www.example.com?test-parameter=1.
Likely getting some basic PHP logic wrong here, would appreciate if anyone could guide me in the right direction with this.
url: window.location.pathname,
Your Ajax is never going to POST the data to a URL with a query string because you explicitly took only the path name.
Maybe you want location.href instead.
This question already has answers here:
Ajax return value with return not work
(2 answers)
Closed 3 years ago.
I have two php files one is index.php and other is phpscriptname.php. i need to call differet functions by using ajax and case method. i found a solution in a website which i give below, but this is not working.
index.php as below
<script>
$.ajax({ url: 'phpscriptname.php',
data: {function2call: 'getEmployeesList'},
type: 'post',
success: function(output) {
alert(output);
}
});
</script>
phpscriptname.php as below
<?php?
if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
$function2call = $_POST['function2call'];
switch($function2call) {
case 'getEmployeesList' : getEmployeesList();break;
}
}
function getEmployeesList(){
return "hai";
}
?>
i was expected "hai" in a popup. but it is not working.
alert(output); will not return anything becuase you are using return for getting plain text response from PHP, you need to use echo instead return in your method.
Second solution is that, if you want to use return in your method then you can modify your switch case as:
if(isset($_POST['function2call']) && !empty($_POST['function2call'])) {
$data = ''; // initialize in default
$function2call = $_POST['function2call'];
switch($function2call) {
case 'getEmployeesList':
$data = getEmployeesList();
break;
}
echo $data;
}
For me this is something new, so I am just researching this and trying to understand it.
As you can see in the php script there are 2 functions and I am trying to call a specific one with jquery.
Now if I have one function then I can do it, but when I have 2 or more I am starting to get stuck.
I suppose I could do this when I have 2 functions, but as soon as more variables are in play or more functions do I just make massive if statements in my php?
The problem is that when I attach a database to it, I would need to consider all inputs that can happen.
How do I specify a specific php function when using jquery & ajax?
//function.php
<?php
function firstFunction($name)
{
echo "Hello - this is the first function";
}
function secondFunction($name)
{
echo "Now I am calling the second function";
}
?>
<?php
$var = $_POST['name'];
if(isset($var))
{
$getData = firstFunction($var);
}
else if(isset($var))
{
$getData = secondFunction($var);
}
else
{
echo "No Result";
}
?>
//index.html
<div id="calling">This text is going to change></div>
<script>
$(document).ready(function() {
$('#calling').load(function() {
$.ajax({
cache: false,
type: "POST",
url: "function.php",
data: 'name=myname'
success: function(msg)
{
$('#calling').html((msg));
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
You need to pass a parameter in, either via the data object or via a GET variable on the URL. Either:
url: "function.php?action=functionname"
or:
data: {
name: 'myname',
action: 'functionname'
}
Then in PHP, you can access that attribute and handle it:
if(isset($_POST['action']) && function_exists($_POST['action'])) {
$action = $_POST['action'];
$var = isset($_POST['name']) ? $_POST['name'] : null;
$getData = $action($var);
// do whatever with the result
}
Note: a better idea for security reasons would be to whitelist the available functions that can be called, e.g.:
switch($action) {
case 'functionOne':
case 'functionTwo':
case 'thirdOKFunction':
break;
default:
die('Access denied for this function!');
}
Implementation example:
// PHP:
function foo($arg1) {
return $arg1 . '123';
}
// ...
echo $action($var);
// jQuery:
data: {
name: 'bar',
action: 'foo'
},
success: function(res) {
console.log(res); // bar123
}
You are actually quite close to what you want to achieve.
If you want to specify which function will be called in PHP, you can pass a variable to tell PHP. For example, you passed request=save in AJAX, you can write the PHP as follow:
$request = '';
switch(trim($_POST['request'])) {
case 'save':
$player_name = (isset($_POST['playername']) ? trim($_POST['player_name']) : 'No Name'));
saveFunction($player_name);
break;
case 'load':
loadFunction();
break;
default:
// unknown / missing request
}
EDIT: You can even pass along with other parameters
This may not be exactly what you are looking for but it can help some others looking for a very simple solution.
In your jquery declare a variable and send it
var count_id = "count";
data:
{
count_id: count_id
},
Then in your php check if this variable is set
if(isset($_POST['count_id'])) {
Your function here
}
I have a php file func.php where I defined many functions let's say :
<? php
function func1($data){
return $data+1;
}
?>
I want to call the function func1 using ajax. thank you for your help
You can't call a PHP function directly from an AJAX call, but you can do this:
PHP:
<? php
function func1($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
?>
JS:
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { alert(response); }
});
You should call your php script through an ajax request, using jQuery like:
Javascript:
$.ajax({
url: "script.php",
data: { param1: "value1", param2: "value2" },
type: "GET",
context: document.body
}).done(function() {
// your code goes here
});
You could give your parameters through data property of ajax object.
Php
// you can do isset check before
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
// validate // sanitize // save to db // blah blah // do something with params
More information you could get from jQuery.ajax() function description from http://api.jquery.com/jQuery.ajax/
It's a bit more complicated, but I will try to shrink it down to the basics.
You will need some kind of interface (a convention, basically) between the caller and your script. Two are the main concerns here:
The way your script understands what needs to be called and with what arguments. Let's say you decide to use a GET request for calling a function. The function name could be in a func field and the arguments in an args one, as a string separated by ;. In other words, calling funcFoo(5,'bar') would be done by requesting func.php?func=func1&args=5;bar.
The way in which the caller receives (and understands) the return value. Since your requirements are js-oriented, a JSON approach would be highly appropriate.
Add the following code along with your functions:
if(isset($_GET['func']))
{
$func=$_GET['func'];
if(function_exists($func))
{
$args=(isset($_GET['args'])?explode(';',$_GET['args']):array());
$result=call_user_func_array($func,$args);
}
else
$result=array('error'=>"Unknown Function $func!");
}
else
$result=array('error'=>"No function name provided!");
echo json_encode($result);
However, your functions should also be changed to meet the new requirements. Since there's no way of telling how many arguments the caller will supply, a function should be designed to accept no mandatory arguments and check for the supplied ones itself. Also, it should always return an array in order to be json_encoded before it is returned to the caller.
Your example function, for instance, should look something like this:
function func1(){
$data=func_get_args();
if(count($data)) // at least one -- rest will be ignored
return $data[0]+1;
else
return array('error'=>__FUNCTION__."() expects an argument!");
}
Be aware though: This is just a skeleton to get you started with the whole concept. A lot more care should be taken for both fault tolerance and security. But that's another topic's subject.
Yes you can !
here my code :
$.ajax({
type: "POST",
url: "ajax.php",
data: { kode: $(this).val(), func: 'my_func' },
success: function(response) {
//any success method here
}
});
and here the code in php to receive what function to call.
$post = (object) $_POST;
if(!$post)
return false;
$func = $post->func;
return $func($post);
function my_func($post) {
$json['any_data'] = false;
if($post->kode == 'ND'){
$json['any_data'] = 'ND-'.date('Y');
}
echo json_encode($json);
}
Hope it help you out bro... :D
I'm using Select2 3.3.1, and on an event I get access to the changed elements in my multiple text input that serves as a place to create and delete tags for use on my website. I'm having trouble iterating over the objects returned in the event handler. Specifically, I want to do this because I want access to the individual tags, and the event handler return parameter contains these objects organized by whether the tags were added or removed. So, this is excellent. But everything I've tried fails.
.on("change", function(e) {
alert(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
var added = JSON.stringify({added:e.added});
$.each(added, function(){
$.ajax({
url: '/db-interaction/tags.php',
data: {
'action': 'addtag',
'q': this
},
type: 'get',
success: function(output) {
}
});
});
The command on the second line above
alert(JSON.stringify({val:e.val, added:e.added, removed:e.removed}));
displays this string
{"val":["newtag"],"added":{"id":"newtag","count":"0"}} in an alert.
In this case, I had just added the word 'newtag' as a tag. I'd like to be able to iterate over these items in this inner list.
I've also tried a double nested loop, like shown below, but I get the same error. I'm not certain what structure the JSON string requires.
$.each(added, function(){
$.each(this, function(){
The ajax request doesn't seem to execute but I can't locate the bug. The success function doesn't execute and there is an error in the firebug console. It says TypeError: invalid 'in' operand e, pointing to the jquery script. It's my bug, I'm sure. Probably to do with the way I'm handling the event handler parameter 'e', but I don't know what I'm doing wrong.
Here's the tag script. FWIW, the addNewTag() method works in other use cases.
<?php
session_start();
include_once "../inc/constants.inc.php";
include_once "../inc/class.tags.inc.php";
$tags = new Tags();
if (isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn']==1)
{
if(!empty($_POST['action']) )
{
switch($_POST['action'])
{
case 'addtag':
echo $tags->addNewTag();
break;
case 'removetag':
echo $tags->removeTag();
break;
case 'getalltags':
echo $tags->getAllTags();
default:
break;
}
}
else if(!empty($_GET['action']))
{
switch($_GET['action'])
{
case 'addtag':
echo $tags->addNewTag();
break;
case 'removetag':
echo $tags->removeTag();
break;
case 'getalltags':
echo $tags->getAllTags();
default:
break;
}
}
}
else
{
header("Location: /");
exit;
}
?>
And the addNewTag() method, which works well in other cases:
/**
* Adds a new tag, increment uses_count if it already exists
*
*
*/
public function addNewTag($name=NULL)
{
if ($name === NULL){
if (isset($_POST['q']) )
$u = $_POST['q'];
else if (isset($_GET['q']))
$u = $_GET['q'];
}
else{
$u = $name;
}
$sql = "INSERT INTO tags(name,uses_count) VALUES (:term,1)
ON DUPLICATE KEY UPDATE uses_count=uses_count+1;";
if($stmt = $this->_db->prepare($sql))
{
$stmt->bindParam(":term", $u, PDO::PARAM_STR);
$stmt->execute();
$stmt->closeCursor();
}
Can anyone help me out? If it would be of use, I could describe the other things I've tried and why they haven't worked.
Try something like
$.each(e.added, function(key, value){
alert(key + ' - ' + value )
$.ajax({
url: '/db-interaction/tags.php',
data: {
'action': 'addtag',
'q': this
},
type: 'get',
success: function(output) {
}
});
});
Demo: Fiddle