Using Jquery $.Ajax to Call a PHP Function

How to call a php function from ajax?

For AJAX request

  1. Include jQuery Library in your web page.
    For e.g.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  2. Call a function on button click

    <button type="button" onclick="create()">Click Me</button>
  3. While click on button, call create function in JavaScript.

    <script>
    function create () {
    $.ajax({
    url:"test.php", //the page containing php script
    type: "post", //request type,
    dataType: 'json',
    data: {registration: "success", name: "xyz", email: "abc@gmail.com"},
    success:function(result){
    console.log(result.abc);
    }
    });
    }
    </script>

On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in PHP and return in JSON format e.g.

$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];

if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}

How can I execute a PHP function via ajax?

Use Get param "action"

$("#form").on('submit', (function(e) {
e.preventDefault();

$.ajax({
url: "process.php?action=one",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(response) {
alert(response);
}
});
}));
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<form action="" method="POST" id="form">
<input type="text" name="text" id="text" />
<button type="submit" id="submit">Upload</button>
</form>

How to call php function inside ajax method

Generally you will have files that contain functions/definitions and others that handle requests. (This is not necessary, just common practice)

Files that handle requests will include any relevant functions/definitions from those other files

For this case, let's use functions.php to contain your main functions and actions.php as a page to handle requests

See the below setup

// functions.php file
function get_team_members(string $team_name){
// return a list of members based on $team_name
}
// actions.php file
include "functions.php";

$action = $_POST["action"] ?? "";
$data = null;
switch($action){
case "get_team_members":
$data = get_team_members($_POST["team"] ?? "");
break;
}

echo json_encode($data);
// js file
$(document).ready(function() {
$("#your_teams234").change(function() {

var team = $("#your_teams234").val();
$.ajax({
url: 'actions.php', // update the url to request from actions.php
method: 'post',
data: { // update data to reflect expected data
action: "get_team_members",
team: team,
},
})
.done(function(requests) { ... })
})
})

using jquery $.ajax to call a PHP function

Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:

$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});

On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:

if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}

I believe that's a simple incarnation of the Command pattern.

Make jQuery AJAX Call to Specific PHP Functions

Okay I found the solution to the problem myself.

I sent a GET-type AJAX call with the data passed in the form of String parameters and added a success property to get a confirmation whether my code has worked or not. I also changed my Award.php code to catch the passed parameter successfully.

So the source code of my files is:

awards.js

function onAdd() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=add",
success: function(response) {
alert(response);
}
});
}

function onSave() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=save",
success: function(response) {
alert(response);
}
});
}

Award.php

$functionName = filter_input(INPUT_GET, 'functionName');

if ($functionName == "add") {
add();
} else if ($functionName == "save") {
save();
}

function add()
{
$award = new Award();
$method = $award->addFunction();
echo json_encode($method);
}

function save()
{
$award = new Award();
$method = $award->saveFunction();
echo json_encode($method);
}

Using Ajax to run php function

Your AJAX call will send data by POST or GET, then you can do anything with that and also return something to your script. It's simple like that.

http://api.jquery.com/jquery.ajax/

Let's work with examples. If you want to make A+B on your server you will need to have a form with inputs like this:

<form id="yourform">
<div><input name="A" type="text" /></div>
<div><input name="B" type="text" /></div>
</form>

Then you will program some script to say what your form will do on submit. As you're using jQuery, let's work with jQuery:

$("#yourform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST", //or "GET", if you want that
url: "yourfile.php",
data: $(this).serializeArray(), //here goes the data you want to send to your server. In this case, you're sending your A and B inputs.
dataType: "json", //here goes the return's expected format. You should read more about that on the jQuery documentation
success: function(response) { //function called if your request succeeds
//do whatever you want with your response json;
//as you're learning, try that to see on console:
console.log(response);
},
error: function(response) { //function called if your request failed
//do whatever you want with your error :/
}
});
});

But what're you doing on the server?
Well, I just want to return my input's, just to check. Here goes my PHP:

<?php
header("Content-type: application/json; charset=utf-8"); //that's required to return any JSON data
if(isset($_POST, $_POST['A'], $_POST['B']))
exit(json_encode($_POST));
else
exit("INVALID REQUEST.");
?>

That's the way you can send information with AJAX to execute something on PHP.

Call PHP function from jQuery?

AJAX does the magic:

$(document).ready(function(

$.ajax({ url: 'script.php?argument=value&foo=bar' });

));

use jquery / ajax to execute php function and display message

HTML (index.php)

In order to use jQuery, you have to first include the script file in your code.

<html>
<head>
<title>Update Time</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="function.js"></script>
</head>
<body>
<div id="msg"></div>
<a id="update_link" href="index.php?user_id=user_id">Update Time</a>
</body>
</html>

JS (function.js)

Next, you want to attach a 'click' event handler to your #update_link element. When you attach an event handler to your link, you want to prevent it from doing its default behavior of redirecting to another page by using e.preventDefault().

// shorter syntax for document.ready
$(function () {
// attach a click event handler
$('#update_link').click(function(e) {
// prevent the click from redirecting
e.preventDefault();
// make an AJAX request
$.post($(this).attr('href'), function (res) {
// handle the response (*) by storing the message into the DIV#message
$('#msg').html(res);
});
});
});

PHP

Now, you are making an AJAX request to the same URL (index.php). It's usually better have a separate script to handle AJAX request -- but we'll work with your current setup. This means your page needs to be able to handle two different kinds of requests: those that are AJAX requests and those that aren't.

When it's an AJAX request, we only want to output a HTML message. When it is not, we want to output the HTML page.

(index.php)

So, first let's modify your page again.

<?php
include 'functions.php';

// check if the request was made via AJAX
if (is_ajax() && isset($_GET['user_id'])) {
// update and print (not return) a message
update_time($_GET['user_id']);
// stop the script from outputting the rest
exit;
}
?>

(functions.php)

Next, let's create a new function (that we just used above) for convenience to detect whether we are receiving an AJAX request.

function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}

Lastly, ensure that you print (or echo) your message. That will be the AJAX response (*) that will be sent back to your JavaScript.

function update_time($user_id){
if (user_exist()) {
//update the database
//print a message that the time was updated
} else {
//print a message that the user does not exist
}
}

How to call a php function in javascript using Ajax?

You can't get the functions of php with JavaScript, you can only read back the return value the server gives you

On the server side you need to listen for get requests, and if it contains "functionname" then call the function and send the return value to the page

So in the PHP file

var isFunc = $_GET["functionname"]
var args = $_GET["arguments"]
if(isFunc== "getPatientbyId") echo getPatientbyId(args)

Calling a specific function from PHP with Jquery & Ajax

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
}


Related Topics



Leave a reply



Submit