skip to Main Content

I want to call a function when the user click on the related button.

The button is located in the directory views/TableauDeBord.php and here is the code (that don’t work).

class TableauDeBord
{
    public function show():void
    {
        ob_start();
        ?>
<!--What I was trying to do : -->
<!--            <script type="text/javascript">-->
<!--                JQuery.Ajax({-->
<!--                    type:"POST",-->
<!--                    url:'app/controllers/TableauDeBord.php'-->
<!--                    dataType:'json',-->
<!--                    data: {functionname: 'test'},-->
<!--                    -->
<!--                })-->
<!--            </script>-->

        <form method="post">
            <input type="button" name="creerSalle" value="creerSalle" onclick=""/>
        </form>
        <?php
        (new ModelePage('Tableau De Bord', ob_get_clean(), 'tableauDeBord'))->show();
    }
}

On click I want to call one of the function/method that are located in controllers/TableauDeBord.php

Here is for example the function I want to call :

    public static function test():void
    {
        echo 'called the test function';
    }

In the end I will have 3 buttons that will mostly do SQL queries in PHP.

I Tried stuff with JQuery and AJAX stuff but I don’t understand how to call the JQuery function in the script in views/TableauDeBord.php

In controllers/TableauDeBord.php I tried somethin with switch case using post

switch ($_POST['functionname']){
    case 'test':
        TableauDeBord::test();
        break;
}

In any case I want an explanation of how to call a function according to my code structure. And if you provide me code I would like to know where to write it because in other topic I saw people usually don’t say where you should put code so i’m lost (and sad)

notes : I’m using MVCfor my whole site that’s why i’m only using class everywhere and not just php file.

Thank you for helping.

2

Answers


  1. An AJAX request doesn’t run a function on the server, it just requests a URL. For the most part, loading a URL over AJAX just works like loading a normal page, PHP doesn’t care about the type of request.

    Here’s a trick I find generally helps understand this: open the URL you’re trying to fetch via AJAX in a new browser tab; whatever you see there is what your JavaScript will get back.

    So if you’ve already got an MVC framework set up for full pages, the URLs you load over AJAX can use exactly the same system.

    Login or Signup to reply.
  2. You cannot run a specific function in an PHP file using AJAX with Jquery, however you can call a full PHP file to be executed. In your case you would be creating a new PHP file yourfile.php and paste the function’s code into there.

    Generally speaking this is the normal flow you should be using:

    Diagram

    You can create a click listener for the "creerSalle" button the following way:

    <input type="button" name="creerSalle" value="creerSalle" id="creerSalleButton">
    
    <script>
      $(document).ready(function() {
        $('#creerSalleButton').click(function() {
          alert('Button clicked!');
        });
      });
    </script>
    

    Inside this event listener you can then call yourfile.php with the parameters using Jquery AJAX. Here is an example:

    var postData = {
      "parameter": "value"
    };
    
    // Request type "POST"
    $.post("yourfile.php", postData, function(response) {
      // This section handles your response from yourfile.php
      console.log(response);
    }, "json")
    .fail(function(error) {
      // If an error occurs, this function is called
      console.error("Error:", error.responseText);
    });
    

    To read these values given to the file, you need to use the $_GET or $_POST variables in PHP. This depends on what type of request you use.

    Example on how to handle POST request:

    <?php
    if ($_SERVER["REQUEST_METHOD"] != "POST") {
       echo json_encode(["status" => "error", "message" => "Please use POST"]);
       return;
    }
    if(empty($_POST["property"])) {
       echo json_encode(["status" => "error", "message" => "Missing value "property""]);
       return;
    }
    
    // Request well formed
    
    // Process data
    
    echo json_encode(["status" => "success", "message" => "Data received successfully"]);
    

    ?>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search