This is a simple example fo using jQuery along with PHP to perform Ajax function on your website. Not this is my method, not neccesarily the best but it works well for me. If anyone knows a easier way or more effecient way please leave a comment. Im always willing to learn. 🙂
Anyway here we go.
I know there are different ways using different methods ( JSON, etc ) but I will be using the simplest method for this example.
First of include the jQuery Library in the <head> section of your website.
You can download the library on to your server and link to it or link directly to the Hosted on :
Next lets create the structure of the example. Add this into the body of your website:
What is your name? <input type="text" id="MyName"/><br> <span class="button">Click Here</span><br> <hr> <div id="Result"></div>
Now in the above code we have three elements.
1. Question and Input is where we get the user input.
2. This <span> will act as the the Event Trigger so clicking this will innitiate the Ajax function.
3. The Result <div> is where the result will be posted to via ajax.
Next we create the function that will proccess the user input.
Create a page called ajax.php and put this in the root of you project. In the Ajax.php file you can do .. well what ever you want. This will basicly be a normal php page who get $_POST data so in this example I will keep it simple.
Add this code to ajax.php:
<?php // Catch the data being passed and add to a variable name $UserInput = $_POST['PostItem']; // Proccess the Data captured $newString = "Hello My Name Is ".$UserInput; // Print the Result after Proccess echo $newString; ?>
Right so the structure is done lets link it all together.
Add the following code right before the </head> tag on your page:
Ok so exlained what happens here:
1. The script runs when the when the DOM is fully loaded.
2. Event Trigger, When the <span> button is clicked the code in that event function will execute.
3. $.post tell jquery that you want to send data to a external file and receive data back.(Load data from the server using a HTTP POST request)
4. We specify a file to pass the data to as you notice the path is the same as the php file we created earlier.
5. Next you specify the data you want to send through as $_POST data. For Example. First is the Variable name and then the data. so in the above case we called it PostItem so the data on the other side will be avaiable as $_POST[‘PostItem’] and the value after the : is the value of the $_POST field.
6. Next we catch the data and do with it what we want. In this case it wil just append it to the Result <div> we created. So what happens is you enter your name , click the button and the resulting text will be added to the <div> without a page refresh.
7. We just specify what data type we want to receive back.