Creating Jquery Ajax Requests to a PHP Function

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) { ... })
})
})

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

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

Creating jQuery AJAX requests to a PHP function

AJAX requests call a URL (make a HTTP request), not a file, in most cases the URL is translated by the server to point at a file (or a php script in your case), but everything that happens from the HTTP request to the response that is received is up to you (on your server).

There are many PHP frameworks that map URL's to specific php functions, AJAX is just an asynchronous way to access a URL and receive a response.

Said URL CAN trigger the server to call a specific function and send back a response. But it is up to you to structure your URL's and server side code as such.

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.

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.

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

JQuery AJAX call to php function

You should use isset() method:

<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>

and if you are using ajax then why do you need to include it on index page:

<?php include 'scripts/phpfunctions.php' ?>

and i can't find this element $('#ajaxdata') on your index page.


Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.

jQuery Ajax POST example with PHP

Basic usage of .ajax would look something like this:

HTML:

<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />

<input type="submit" value="Send" />
</form>

jQuery:

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

// Prevent default posting of form - put here to work in case of errors
event.preventDefault();

// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);

// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");

// Serialize the data in the form
var serializedData = $form.serialize();

// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);

// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});

// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});

// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});

});

Note: Since jQuery 1.8, .success(), .error() and .complete() are deprecated in favor of .done(), .fail() and .always().

Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready() handler (or use the $() shorthand).

Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();

PHP (that is, form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

Note: Always sanitize posted data, to prevent injections and other malicious code.

You could also use the shorthand .post in place of .ajax in the above JavaScript code:

$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});

Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.



Related Topics



Leave a reply



Submit