weixin_33696106 2018-08-25 12:40 采纳率: 0%
浏览 37

通过Ajax运行php函数

I have button on html like this:

<button class="uk-button uk-button-primary uk-modal-close confirm-rules" type="button" onclick="sendStatus('accept_rules')">Rozumiem</button>

and I want to do it when I click on the button, the function in php will be called. I try do this by ajax like this:

    <script type="text/javascript">
    function sendStatus(status) {
        $.ajax({
            method: "POST",
            url: "Controllers/Core/Dashboards/Admin/Dashboard.php",
            data: { status: status }
        }).done(function( msg ) {
            alert("Cookie saved:" + msg );
        });
    }
</script>

The problem is with php file, because it's look like this:

    <?php

declare(strict_types=1);

namespace App\Controllers\Core\Dashboards\Admin;

use App\Controllers\Controller;

use App\Core\SessionManagement;
use App\Core\Request;
use App\Core\Cookies;

class AdminDashboard extends Controller
{

    private $cookies;

    /**
     * AdminDashboard constructor.
     * @param Cookies $cookies
     */
    public function __construct(Cookies $cookies)
    {
      $this->cookies = $cookies; 
    }

    public function acceptDashboardBox()
    {
        if ( isset($_POST['status']) )
        {
            $this->cookies->add( $_POST['status'], 'true', 'time() + (365 * 24 * 60 * 60)');
        }
    }

    /**
     *
     */
    public function index() : void
    {

        Controller::renderView('Core/Dashboards/Admin/Dashboard');

    }

}

Button must run function acceptDashboardBox() on class AdminDashboard. How i can do this?

  • 写回答

1条回答 默认 最新

  • weixin_33699914 2018-08-25 22:00
    关注

    When calling your file Controllers/Core/Dashboards/Admin/Dashboard.php, nothing will happen because nothing calls the function acceptDashboardBox() or anything else in this file.

    Please always make sure that your PHP Classes do have the name of the file that you are currently in (PSR-4). The name of your class is AdminDashboard, so call your file AdminDashboard.php to avoid confusion. Also it is common practice to use Event Listeners for click events instead of calling a function onclick=.

    To let PHP only call your function acceptDashboardBox() you would need a new endpoint/file that does that same as your function and nothing else.

    I would suggest you return a json with a status and catch exceptions that set the status if one occurs to something that indicates an error occurred. You can check the json in your javascript and check if the operation was successful or not. Something like:

    {
        status: "success"
    }
    

    OR

    {
        status: "failure"
    }
    

    would do the deal.

    评论

报告相同问题?