最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling a PHP class method and getting the return value using jQuery and AJAX - Stack Overflow

programmeradmin5浏览0评论

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: ".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 plete 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: ".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?

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./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 plete 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./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?

Share Improve this question edited Jan 6, 2016 at 17:43 JKase asked Jan 6, 2016 at 16:06 JKaseJKase 1572 silver badges10 bronze badges 13
  • 2 Normally you would have one PHP file per "action" as each request address is supposed to perform one operation only. Then you just change the request URL based on the function you wish to call. – iCollect.it Ltd Commented Jan 6, 2016 at 16:08
  • How would these PHP files be formed? I guess that's pretty much the core of my question :) – JKase Commented Jan 6, 2016 at 16:11
  • SetTitle.php, GetTitle.php, SetDescription.php... You get the idea :) – iCollect.it Ltd Commented Jan 6, 2016 at 16:12
  • Haha, yeah :) But what's the content and how do I get them to return stuff back? :) – JKase Commented Jan 6, 2016 at 16:14
  • Send content via URL query string parameters or posted data, and process the returned data (most simply as strings for this example)... You need to know how to return data from PHP if you are going to use PHP :) – iCollect.it Ltd Commented Jan 6, 2016 at 16:15
 |  Show 8 more ments

4 Answers 4

Reset to default 2

As of the long ment 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 pletely 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./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./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 reend 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']);

发布评论

评论列表(0)

  1. 暂无评论