How to call a php functions using ajax and case [duplicate] - php

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;
}

Related

JQuery Ajax Execute error function intentionally [duplicate]

This question already has answers here:
PHP trigger AJAX error code without using array
(4 answers)
Closed 6 years ago.
I am using jquery ajax to retrieve data from a php function.
My php function is as follows
<?php
if(isset($_GET['action'])) {
$data = array();
$data[0]["field"] = "data";
echo json_encode($data);
} else {
// error
return;
}
?>
and I am calling using the jquery ajax in my javascript
$.ajax({
url : '../functions/php/function.php',
type : 'GET',
dataType : 'json',
data : {'wrong','wrong'},
success : function(data) { console.log('all ok') },
error : function(log) { console.log('not ok') }
});
Instead of just returning from the php function with nothing is it possible to retrieve an error so that the jquery executes the error function?
You can set header with any http status code lets say 400 http_response_code(400). When jQuery Ajax function sees the status code other than 200 it will execute your error callback function.

Calling a specific function from PHP with Jquery & Ajax

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
}

How can i call one of many php functions with ajax? [duplicate]

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&params=[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.

Using Jquery and AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am using AJAX to call a PHP file that does email validation and outputs simple text that gets returned to the AJAX Success. I am using the text returned to create variables to represent which error to display. I am having trouble using these variables, the form still submits. What could I be doing wrong?
My Code:
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
success: function(data) {
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
}
});
}
if (invalid == 1) {
alert('invalid email');
error= true;
}
if (taken == 1) {
alert('email taken');
error= true;
}
if (error == true) {
return false;
}
Is this AJAX call inside a click event? If so, you may want to use event.preventDefault() function to avoid triggering the form submission:
event.preventDefault();
Have a look to the example in the documentation
You should have two things in consideration:
1) if you're ajax call is triggered by a link or submit button , you MUST use preventDefault function
2) in your "checkmail.php" don't forget to call exit function in the end of call

How to use the response coming from the php to $.post() in jquery [duplicate]

This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
this is my first question at stackoverflow, speaking specifically ... i am using the result of my PHP file ("myphp.php") ...
<?php
echo "Hello"
?>
now the javascript code that was called :
function functionX()
{
var result;
$.post("myphp.php",function(data)
{
result=data; /// result should be Hello
});
alert(result); /// the msgbox shows "Undefined"
// i am enable to access the result i got from PHP file
}
So my problem is how to access the result , so that i can use it at other parts of my code ...
OR can you suggest some other ways .. THANXX
as i am a newbie to ajax .. i want to use this concept for checking username availability as shown
var result;
function functionX(username)
{
$.post("check_username.php",{usn:username},function(data)
{
if(data=="OK"){result="yes";}
if(data=="FAIL"){result="no";}
});
alert(result); // Now i want the result here .. its important
}
<?php
$usn=$_POST['usn'];
$flag=0;
$q=mysql_query("SELECT * FROM accounts");
while($row=mysql_fetch_assoc($q))
{
if($row['usn']==$usn)
{
$flag=1;break;
}
}
if($flag==1)
{
echo "OK";}
else
echo "FAIL";
?>
i know these methods for detecting username existence can be silly .. so that's what i did
try this
var result;
$.ajax({
type: "POST",
url: 'myphp.php',
success: function (data) {
result=data;
}
});​
alert(result);
It's because if you just put the code below it doesn't mean after as raina77ow mentioned.
If you don't need the data later just use this:
function functionX(){
$.post("myphp.php",function(data) {
alert(data);
});
}

Categories