简体   繁体   中英

Calling a PHP class method and getting the return value using jQuery and AJAX

I'm creating a little project for myself. I'm not a very experienced programmer, so I began creating the project in PHP. Soon it became evident that running PHP functions and class methods via HTML button clicks wasn't the most straightforward of tasks.

I have some test code set up. First I created an HTML form, from which I want to read user-input values:

<form name="form" action="" method="POST">
    Title: <br> <input type="text" id="title"> <br>
    Description: <br> <input type="text" id="description"> <br>
    Priority: <br> <input type="number" id="priority"> <br> <br>
    <input type="button" id="ajaxTest" value="Send>
</form>

Now, when the button with id #ajaxTest is clicked, I want to call one of the class methods in a PHP-file that I've created. To this end, I googled around and ended up with the following jQuery:

<script type="text/javascript">
    $("#ajaxTest").click( function() {

        $t = $("#title").val();

        $.ajax({
            type: "POST",
            url: "http://www.example.com/task.php",
            data: "t="+t
        }).done(function(results) {
            $("#results").html(results).hide().fadeIn();
        })
    });

</script>

There is also a div-element with id #results in the HTML, to show the resultant data.

Now, the task.php being called looks like as follows (simplified for readibility):

<?php
class Task {
    private $title;
    private $description;

    function SetTitle($t) {
        $this->title = $t;
    }

    function GetTitle() {
        return $this->title;
    }

    function SetDescription($d) {
        $this->description = $d;
    }

    function GetDescription() {
        return $this->description;
    }
}

How would I go about calling the different member functions of this class via jQuery/AJAX and getting their return values for input to DOM? I take I'll have to create an intermediary class like TaskHandler that initiates the object and so on, but I'm at a complete loss. Been at it almost the whole day, but I've failed to find an answer that would've lead me to a working solution. Ever so thankful for your help!

edit: I have now edited the jQuery and it looks as follows:

<script type="text/javascript">

    $("#ajaxTest").click( function() {

        var t = $("#title").val();

        $.ajax({
            type: "POST",
            url: "http://www.example.com/taskHandler.php",
            data: {"t": t},
            success: function(response) {
                 $("#results").html(response);
            }
        });
    });

</script>

and taskHandler.php is below

<?php
    require_once("task.php");

    $t = new Task();
    $t->SetTitle($_POST['t']);

    $output = $t->GetTitle();
    echo $output;

Still don't get anything to show up, though. What's it I'm doing wrong here?

As of the long comment list on this question just one thing which is probably messing up the AJAX call:

<form name="form" action="" method="POST">
    Title: <br> <input type="text" id="title"> <br>
    Description: <br> <input type="text" id="description"> <br>
    Priority: <br> <input type="number" id="priority"> <br> <br>
    <input type="submit" id="ajaxTest" value="Submit">
</form>

The submit button usually submits the entire form. As an empty action parameter is provided, the post action goes to the current page. This will immediately reload, and interrupt a probably issued but not completely sent AJAX request.

Change:

<form name="form" action="" method="POST">
    Title: <br> <input type="text" id="title"> <br>
    Description: <br> <input type="text" id="description"> <br>
    Priority: <br> <input type="number" id="priority"> <br> <br>
    <input type="button" id="ajaxTest" value="Send">
</form>

The final problem lied in the AJAX request, which the web browser regarded as cross-domain because of the format. Actually it was working in the same domain.

url: "http://www.example.com/taskHandler.php",

As soon as I changed to just

url: "taskHandler.php"

it started working.

Thanks everyone for your input! I learned a lot here trying to troubleshoot this.

Go through the following steps:
if you expecting to call only one backend method per request, then consider allowing only one of those fields for input: 'title' or 'description' .
*** js part:

<script type="text/javascript">
    $("#ajaxTest").click(function(e) {
        e.preventDefaut();
        var title, desc, type;
        if (title = $("#title").val().trim()){
            type = 'title';
        } else if (desc = $("#description").val().trim()){
            type = 'description';
        }

        $.ajax({
            type: "POST",
            url: "http://www.example.com/task.php",
            data: {'action': type, 'value': title || desc} // 'value' is for setting certain property, to return an existing property send only 'action' param
        }).done(function(results) {
            $("#results").html(results).hide().fadeIn();
        })
    });
</script>

php part: task.php

<?php
class Task {
    private $title;
    private $description;

    function SetTitle($t) {
        $this->title = $t;
    }

    function GetTitle() {
        return $this->title;
    }

    function SetDescription($d) {
        $this->description = $d;
    }

    function GetDescription() {
        return $this->description;
    }
}

if (isset($_POST['action']) && !empty($_POST['action'])){
    $action = $_POST['action'];
    $value = (isset($_POST['value']) && !empty($_POST['value']))? $_POST['value'] : null;
    $task = new Task();
    $method = (($value)? 'Set' : 'Get') . ucfirst($action);
    if method_exists($task, $method){  // BTW - method name should start with a lowercase letter
        $result = ($value)? $task->$method($value) : $task->$method();
        echo ($result)? $result : "";
        return;
    }
}

You have duplicate the getTitle method:

class Task {
    private $title;
    private $description;

    function SetTitle($t) {
        $this->title = $t;
    }

    function GetTitle() {
        return $this->title;
    }

    function SetDescription($d) {
        $this->description = $d;
    }

    function GetTitle() {
        return $this->description;
    }
}

I recomend you to test the php file as separated file, something like:

$text = "test";

class Task {
    private $title;
    private $description;

    function SetTitle($t) {
        $this->title = $t;
    }

    function GetTitle() {
        return $this->title;
    }

    function SetDescription($d) {
        $this->description = $d;
    }

    function GetDescription() {
        return $this->description;
    }
}

$t = new Task();
$t->SetTitle($text);

$output = $t->GetTitle();
echo $output;

So you will know for sure if the php file hasn't an error. Same in the html/javascript put a console.log(inputValue) to see what are you sending.

If all is working you do the $t->SetTitle($_POST['title']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM