How to call a PHP class function from an ajax call
animal.php
file
class animal { function getName() { return "lion"; } }
Then in my ajax.php
file I have an ajax request, need to get values from getName function
How to do that getName()
function can I do like this?
<script type=text/javascript> $.ajax({ type: "POST", data: { invoiceno:jobid }, url: "animal/getName", beforeSend: function() { }, dataType: "html", async: false, success: function(data) { result=data; } }); </script>
Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.
A JSON object containing numeric HTTP codes and functions to be called when the response has the corresponding code. A callback function to be executed when Ajax request succeeds.
GET vs POST in AJAX callsUnless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data).
My answer is the same as Surreal Dreams answer, but with the code.
First. Class animal is OK. Leave it like that:
animal.php
<?php class animal { function getName() { return "lion"; } }
Next. Create a new animalHandler.php
file.
<?php require_once 'animal.php'; if(isset( $_POST['invoiceno'] )) { $myAnimal = new animal(); $result = $myAnimal->getName(); echo $result; }
Finally. Change your Javascript.
<script type=text/javascript> $.ajax({ type: "POST", data: { invoiceno:jobid }, url: "animalHandler.php", dataType: "html", async: false, success: function(data) { result=data; } }); </script>
That's is.
You need one additional script, because your animal class can't do anything on its own.
First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.
Use this new script as the target of your Ajax request instead of targeting animal.php.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With