Make jQuery AJAX Call to Specific PHP Functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
rugved
Forum Newbie
Posts: 23
Joined: Tue Dec 03, 2013 12:33 am
Location: Cyber World

Make jQuery AJAX Call to Specific PHP Functions

Post by rugved »

Hello!

I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class located in /controller/ folder in the project named, Award.php. This PHP file which contains code to execute a function called, addFunction() in another Award.php file located in /model/ folder in the project, which returns a JSON array and is displayed in the awards.html page.

The source code of my files is given as follows:

awards.html

Code: Select all

<div class = "divbottom">
    <div id="divAddAward">
        <button class="btn" onclick="onAdd();">Add</button>
    </div>
</div>
awards.js

Code: Select all

function onAdd() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}
Award.php (located in /controller/ folder)

Code: Select all

<?php

foreach (glob("../model/*.php") as $filename) {
    include $filename;
}

$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
Award.php (located in /model/ folder)

Code: Select all

<?php

class Award
{
    public function addFunction() {
        $array = array(
            'status' => '1'
        );
        return $array;
    }
}
My code works perfectly and is error-free. Now I want to add another button in awards.html called, Save which when clicked will call a function onSave() in the JS file. Thus the source code of my files will change to the following:

awards.html

Code: Select all

<div class = "divbottom">
    <div id="divAddAward">
        <button class="btn" onclick="onAdd();">Add</button>
        <button class="btn" onclick="onSave();">Save</button>
    </div>
</div>
awards.js

Code: Select all

function onAdd() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}

function onSave() {
    $("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
    $.post(
            'classes/Award.php'
            ).success(function(resp) {
        json = $.parseJSON(resp);
    });
}
Now the problem here is that since I want to call the same Award.php file from JS, how do I modify my controller Award.php file? In my opinion there should be two different functions which would contain code to instantiate the view Award.php class and call a different function; something like the following:

Award.php

Code: Select all

<?php

foreach (glob("../model/*.php") as $filename) {
    include $filename;
}

function add(){
    $award = new Award(); //Instantiating Award in /model/ folder
    $method = $award->addFunction();
    echo json_encode($method);
}

function save(){
    $award = new Award(); //Instantiating Award in /model/ folder
    $method = $award->saveFunction();
    echo json_encode($method);
}
Award.php

Code: Select all

class Award
{
    public function addFunction() {
        $array = array(
            'status' => '1'
        );
        return $array;
    }

    public function saveFunction() {
        $array = array(
            'status' => '2'
        );
        return $array;
    }
}
But how do I call these specific PHP functions from my JS file? If the code I have assumed above is correct, then what should be my JS code? Can anyone please advise me on this? Replies at the earliest will be highly appreciated. Thank you in advance.

PS: I am not using an MVC pattern for my web project. I have kept dummy names for the folders to maintain confidentiality.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by Celauran »

Why not specify which function to call as part of the data sent in the AJAX request?
User avatar
rugved
Forum Newbie
Posts: 23
Joined: Tue Dec 03, 2013 12:33 am
Location: Cyber World

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by rugved »

Celauran wrote:Why not specify which function to call as part of the data sent in the AJAX request?
Thank you for replying. May I know how do I do this?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by Celauran »

jQuery.post

Code: Select all

$.post('classes/Award.php', {action: 'function_name_goes_here' }).success(function(foo) { // do stuff });
When a POST request comes in, check the value of $_POST['action'] to determine what method should be executed.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by pickle »

Just a quick note that the action should probably not be the actual function name, as the temptation there might be to directly call the posted string. I'd suggest if you are going to do what ~Celauran suggested, make Award.php have a switch statement that does different actions based on what $_POST['award'] is.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
rugved
Forum Newbie
Posts: 23
Joined: Tue Dec 03, 2013 12:33 am
Location: Cyber World

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by rugved »

Celauran wrote:jQuery.post

Code: Select all

$.post('classes/Award.php', {action: 'function_name_goes_here' }).success(function(foo) { // do stuff });
When a POST request comes in, check the value of $_POST['action'] to determine what method should be executed.
Okay I have tried this code but it doesn't give any output. When I checked for errors in the Chrome developer tools, it tells me that it doesn't identify the add() method; which means that the program gets executed successfully till finding the Award.php file but throws an error in the {action: add()} line.
User avatar
rugved
Forum Newbie
Posts: 23
Joined: Tue Dec 03, 2013 12:33 am
Location: Cyber World

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by rugved »

I have modified my code a bit to at least get something working.

awards.js

Code: Select all

function onAdd() {
    $("#display").load('controller/Award.php');
    var functionName = JSON.stringify({values:"add"});
    $.ajax({
        type: "POST",
        url: "controller/Award.php",
        data:
                functionName

    });
}

function onDrop() {
    $("#display").load('controller/Award.php');
    var functionName = JSON.stringify({values:"add"});
    $.ajax({
        type: "POST",
        url: "controller/Award.php",
        data:
                functionName
    });
}
Award.php

Code: Select all

$functionName = $_POST['functionName']; [color=#FF0000]//Error here![/color]
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);
}
And I am getting the following error on the line marked above:
Notice: Undefined index: functionName in C:\xampp\htdocs\phpproject\controller\Award.php on line 20
which means that the JS file is able to pass the value but it is not able to catch it. Any advice on hos do I progress further?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by Celauran »

data is meant to be an object.

Code: Select all

$.ajax({
    type: 'POST',
    url: 'controller/Action.php',
    data: { action: 'functionName' }
});
Then check for $_POST['action'] to determine which method should be called.
User avatar
rugved
Forum Newbie
Posts: 23
Joined: Tue Dec 03, 2013 12:33 am
Location: Cyber World

Re: Make jQuery AJAX Call to Specific PHP Functions

Post by rugved »

I found the resolution 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.

The source code of my files is:

awards.js

Code: Select all

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

Code: Select all

$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);
}
Post Reply