How to Call a PHP Function from Ajax

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 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.

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)

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.

Call any Wordpress PHP function via AJAX

Okay, let's write simplified example for this.

Here is a sample for functions.php:

add_action('wp_ajax_nopriv_sayhello', 'say_hello_function');
add_action('wp_ajax_sayhello', 'say_hello_function');
function say_hello_function(){
echo 'hello';
exit();
}

And this is front-end part:

<button class="my_button" type="button" role="button">Click Me</button>

<script>
jQuery(".my_button").click(function(){

jQuery.get(ajaxurl,{'action': 'sayhello'},
function (msg) { alert(msg);});

});

</script>

UPD:

To display returned data in your website content:

   <script>
jQuery(".my_button").click(function(){
jQuery.get(ajaxurl,{'action': 'sayhello'},
function (msg) { jQuery(".result_area").html(msg);});
});
</script>

To get above code working you need to have a div with "result_area" class.

<div class="result_area"></div> 

How to call a PHP function from XMLHttpRequest (AJAX)?

What you need to do is make the PHP function run when the PHP file is triggered. To do this, add hello(); at the bottom of functions.php. To have multiple functions, you could have a folder of php files that all do one single function.

If you wanted to have a PHP file with multiple functions that the JS chooses, you could do something like this:

Functions.php

<?php

$function = $_POST["function"];

if ($function == "hello") {
hello();
}
else if ($function == "goodbye") {
goodbye();
}

function hello() {
echo "Hello from function php";
}

function goodbye() {
echo "Goodbye from function php";
}

?>

index.php


<script>

var xhr = new XMLHttpRequest();
xhr.open('POST','functions.php',true);
xhr.onload = function() {
console.log(this.responseText);
// If you wanted to call the function in here, then just make another whole xhr var and send it in this function
}

xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('function=hello');
</script>

Eval could work, but it is an extremely bad idea to use it on data sent by the client (as in a malicious request could delete and read all sorts of data on the server)



Related Topics



Leave a reply



Submit