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
}
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:
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.
I have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>
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
I am developing one website using cakephp and jquery technologies.
Server-side there are some functions which handles SQL queries.
As per requirement I want to modify server side functions on client side using jQuery AJAX call.
E.g. : Below is the function on server side to modify users information.
function modifyUser(username,userid) {
//update query statements
}
Then jquery AJAX call will be like this:
$.ajax({
url: 'users/modiyUser',
success: function() {
alert("Updation done") or any statements.
}
});
and I want to modify above i.e. server side function depending upon client input criteria.
$.ajax({
function users/modiyUser(username,userid) {
// I will write here any other statements which gives me some other output.
}
});
Above AJAX call syntax may not present, but i think you all understood what I am trying to do I simply wants to modify/override server side functions on client side.
Please let me know is there any way to resolve above mentioned requirement.
Thanks in advance
You cannot call a PHP functions from the client directly. You can only make an HTTP request to a URI.
The URI determines the PHP script run. Input can be taken via $_GET, $_POST, and $_COOKIE (among others, but those are the main ones).
You can either write separate scripts for each function or determine what to do based on the user input.
You could have a server-side function in a separate PHP file to do this, and make an AJAX call call into that function first to perform the modification. But client-side changes to server-side code are just not possible.
I can't actually imagine why you would want to do this, though.
why override a function???
can i suggest this?
in PHP
try {
// functions here....
function modifyUser($username,$userid) {
//update query statements
if(!is_string($username)) throw new Exception("argument to " . __METHOD__ . " must be a string");
if(!is_string($userid)) throw new Exception("argument to " . __METHOD__ . " must be a string");
// do some modification codes....
}
function delete($userid){
// do stuff blah blahh...
}
// $_POST or $_GET etc. here
if(isset($_GET["modify"])){ // I make use of get for simplicity sake...
$username = $_GET['username'];
$userid = $_GET['userid'];
modifyUser($username,$userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been modified";
echo json_encode($ret);
} else if(isset($_GET["delete"])) {
$userid = $_GET['userid'];
delete($userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been deleted";
echo json_encode($ret);
}else {
// the client asked for something we don't support
throw new Exception("not supported operation");
}
}
catch(Exception $e){
// something bad happened
$ret = array();
$ret["error"] = true;
$ret["msg"] = $e->getMessage();
echo json_encode($ret);
}
in jQuery ajax
$.ajax({
url: 'ajax.php',
data : { modify : true, // sample for modify... can also be delete : true,
username : $('#username').val(),
userid : $('#userid').val() },
type: 'GET',
dataType: 'json',
timeout: 1000,
error: function(){
alert('error in connection');
},
success: function(data){
if(data.error)
alert('Something went wrong: ' + data.msg);
else {
alert('Success: ' + data.msg);
}
}
});