Overview: load(), get(), and post() in AJAX
In the last two episodes we learned about the load function inside AJAX. In this episode we're going to learn about the get function and the post function. When it comes to getting data from a server using AJAX we have a couple of different functions we can use in order to do something very specific.
In the last episodes we talked about the load function which basically takes data from a server and inserts it inside your website somewhere, like inside a div box. Now when it comes to the get and post functions we can do something different. Let's say I want to just get data from a server without actually inserting it inside my website; I can use the get function inside AJAX to do so.
If I wanted to I could also take the data and insert it inside my website, but the get function inside AJAX allows us to do more things with our data other than just inserting it inside the website. The second function we have is something called the post function and this one basically allows users inside the website to interact with the website and do something using AJAX.
Get() function: concept and basic usage
To give you an example of this: let's say we have a place where you can create a user account inside the website where we allow users to type in a username and a password. If I want to notify the user that a certain username has already been taken before he clicks submit, we can do it using AJAX. Another example could be notifying if the password is strong enough.
So we can do a bunch of things using the get and post functions inside AJAX. Now let's actually go and do an example using the get function inside AJAX. If I go inside my website here you can see I have a button that says "Click me to get data" and I also have a paragraph that has an ID set to "test." What I want to do here is using the script up here tell my page to fetch some data and insert it inside this paragraph down here when I click this button.
The first thing I'm going to do is create the actual document or the data that I want to get from somewhere. I'm going to create a new document and save it inside my server where I have my front page. I'll save this one as something like test.txt. It doesn't have to be a text document; it can be HTML files, JavaScript files, PHP files, or text documents. You can have all sorts of documents with data inside of it that we can get using the get method.
I'll save this inside my root folder and type some text in here: "This is some random data." Then I'll go back inside my index file and inside my script text start out by saying that we want to wait with actually loading the jQuery code till after everything else inside the website has loaded. So we'll write $(document).ready(); and inside the parentheses we'll use a function and include the jQuery code.
The first code is a selector to select the button and say once we click it something needs to happen. We'll use button.click(function() { ... }). Inside that function we want to use the get function inside AJAX: $.get(...). Inside the parentheses we have parameters. One is the actual document we want to load data from, which right now is called test.txt. The second parameter is optional, but we'll use it; it returns the data from test.txt and also tells us the status of the get request.
Get() callback: handling data and status
We can pass a callback function that receives two parameters: data and status. Because we have two pieces of data — the actual data and the status — we include parameters like function(data, status) { ... }. Inside the function we can decide what to do with the data we got from test.txt. I'll tell it to insert the data into our paragraph with ID "test": $('#test').html(data).
We don't have to use the status, but if we want to we could alert the status to know if it succeeded or failed. Before we check if this actually works I'll correct a small mistake: I wrote text.txt but it is actually test.txt, so I'll fix that and refresh the browser. When I click the button you can see we get a success message that says this ran correctly. When I click OK I get the data.
This is how we can get data using a get method inside jQuery AJAX. We basically did the same thing as using the load function, but get() lets us do whatever we want with the data, whereas load() usually just inserts the data inside our document. So we can do a bunch more things when it comes to getting data besides loading it into the page.
Post() function: input, keyup, and sending data
Now let's create something using the post function inside AJAX. I'll delete the button and add a text input with name="name". What I want is: when the user types something inside the input I want to check if the username already exists on the server. In the jQuery code I'll run code each time I type, using $('input').keyup(function() { ... }).
Inside that function the first thing is getting the value of the input: var name = $('input').val();. Underneath we run the post function: $.post(...). The syntax differs from get: post can have three parameters. The first is the path to the URL file we want to call, which I will call suggestions.php. The second parameter is the data object to pass to suggestions.php using POST. I'll write an object like { suggestion: name } to send the typed value under the key "suggestion."
The third parameter is the callback, similar to get: function(data, status) { ... }. Inside it I'll take the result from the post and insert it into the paragraph with ID "test" using $('#test').html(data). I won't alert the status because this runs on each keyup and alerting would be annoying each time.
Server-side PHP: matching names and final notes
Next we need to create suggestions.php which does something with the data the user typed and returns the data immediately. We don't have to use PHP — this could be any server-side file — but I'll use PHP. Inside suggestions.php I'll open PHP tags and create a list of names as an array: $existing_names = array('Daniel', 'Dennis', 'Danny', 'Jane');
Below I'll check if we actually have a POST parameter passed from jQuery. We'll use if (isset($_POST['suggestion'])) { ... } and set $name = $_POST['suggestion'];. Now we loop through the array with foreach ($existing_names as $existing_name) { ... } and each iteration check if the typed name matches anything in the array using strpos($existing_name, $name). If it's not equal to false, it's a match and we'll echo the existing name and a break so multiple matches appear on separate lines.
When testing in the browser, typing "Daniel" shows "Daniel, Dennis, Danny" as matches; adding more letters reduces matches. One quick fix: if the input becomes empty, strpos would get an empty second parameter and produce an error, so include a check to only run the foreach loop if the input is not empty.
This is basically how we can use the get() and post() functions inside jQuery AJAX. Quick differences: get() is typically used to retrieve non-sensitive data from the server; post() is used when sending user input or more sensitive data. I'll follow up with suggested future episodes and then move into JavaScript AJAX next. Hope you enjoyed and I'll see you next time.