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
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.
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:
You can create a click listener for the "creerSalle" button the following way:
Inside this event listener you can then call
yourfile.php
with the parameters using Jquery AJAX. Here is an example: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:
?>