AJAX is an acronym for Asynchronous JavaScript and XML. This technology allows a browser to asynchronously communicate with the server using JavaScript. Refreshing the web page is not necessarily required to perform an action on the server.
Many web applications have been released that run on AJAX. A web application is often described as a website containing only one page and which performs all operations with an AJAX server.
If you are not using a library, using AJAX requires a lot of lines of code to be compatible with several browsers. When including jQuery, it is possible to make easy AJAX requests while at the same time being compatible with many browsers.
In this chapter, we will cover:
- Working with JQuery
- JQuery basics
- Working with AJAX in the task manager
In this chapter, we use jQuery to make AJAX requests. Before using jQuery, let's understand its basics.
CSS selectors used in style sheets can effectively retrieve an item with very little code. This is a feature that is so interesting that it is implemented in the HTML5 Selector API with the following syntax:
item = document.querySelector('tag#id_content');
jQuery also allows us to use CSS selectors. To do the same thing with jQuery, you must use the following syntax:
item = $('tag#id_content');
At the moment, it is better to use jQuery than the Selector API because jQuery 1.x.x guarantees great compatibility with older browsers.
It is possible to get back the HTML code between two tags with the html()
method:
alert($('div#div_1').html());
This line will display an alert with the HTML content of the <div id="div_1">
tag. Concerning the input and textarea tags, it is possible to recover their content in the same way as with the val()
method.
Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.
Thus, the following instruction will add a button in the div tag:
$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');
jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each()
method as shown in the following example:
var cases = $('nav ul li').each(function() { $(this).addClass("nav_item"); });
To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:
- Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
- Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.
In this chapter, we will host jQuery on our web server to not be dependent on a host.
We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js
file.
Then, you must add the following line in the head tag of the base.html
file:
<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script> {% block head %}{% endblock %}
With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head
block from the template which extends base.html
.
CSS selectors in jQuery
CSS selectors used in style sheets can effectively retrieve an item with very little code. This is a feature that is so interesting that it is implemented in the HTML5 Selector API with the following syntax:
item = document.querySelector('tag#id_content');
jQuery also allows us to use CSS selectors. To do the same thing with jQuery, you must use the following syntax:
item = $('tag#id_content');
At the moment, it is better to use jQuery than the Selector API because jQuery 1.x.x guarantees great compatibility with older browsers.
It is possible to get back the HTML code between two tags with the html()
method:
alert($('div#div_1').html());
This line will display an alert with the HTML content of the <div id="div_1">
tag. Concerning the input and textarea tags, it is possible to recover their content in the same way as with the val()
method.
Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.
Thus, the following instruction will add a button in the div tag:
$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');
jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each()
method as shown in the following example:
var cases = $('nav ul li').each(function() { $(this).addClass("nav_item"); });
To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:
- Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
- Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.
In this chapter, we will host jQuery on our web server to not be dependent on a host.
We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js
file.
Then, you must add the following line in the head tag of the base.html
file:
<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script> {% block head %}{% endblock %}
With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head
block from the template which extends base.html
.
Getting back the HTML content
It is possible to get back the HTML code between two tags with the html()
method:
alert($('div#div_1').html());
This line will display an alert with the HTML content of the <div id="div_1">
tag. Concerning the input and textarea tags, it is possible to recover their content in the same way as with the val()
method.
Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.
Thus, the following instruction will add a button in the div tag:
$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');
jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each()
method as shown in the following example:
var cases = $('nav ul li').each(function() { $(this).addClass("nav_item"); });
To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:
- Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
- Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.
In this chapter, we will host jQuery on our web server to not be dependent on a host.
We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js
file.
Then, you must add the following line in the head tag of the base.html
file:
<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script> {% block head %}{% endblock %}
With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head
block from the template which extends base.html
.
Setting HTML content in an element
Changing the content of a tag is very simple because we're using the same method as the one we used for recovery. The main difference between the two is that we will send a parameter to the method.
Thus, the following instruction will add a button in the div tag:
$('div#div_1').html($('div#div_1').html()+'<button>JQuery</button>');
jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each()
method as shown in the following example:
var cases = $('nav ul li').each(function() { $(this).addClass("nav_item"); });
To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:
- Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
- Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.
In this chapter, we will host jQuery on our web server to not be dependent on a host.
We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js
file.
Then, you must add the following line in the head tag of the base.html
file:
<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script> {% block head %}{% endblock %}
With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head
block from the template which extends base.html
.
Looping elements
jQuery also allows us to loop all the elements that match a selector. To do this, you must use the each()
method as shown in the following example:
var cases = $('nav ul li').each(function() { $(this).addClass("nav_item"); });
To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:
- Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
- Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.
In this chapter, we will host jQuery on our web server to not be dependent on a host.
We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js
file.
Then, you must add the following line in the head tag of the base.html
file:
<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script> {% block head %}{% endblock %}
With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head
block from the template which extends base.html
.
Importing the jQuery library
To use jQuery, you must first import the library. There are two ways to add jQuery to a web page. Each method has its own advantages, as outlined here:
- Download jQuery and import it from our web server. Using this method, we keep control over the library and we are sure that the file will be reachable if we have our own website too.
- Use the hosted libraries of the Google-hosted bookstores reachable from any website. The advantage is that we avoid an HTTP request to our server, which saves a bit of power.
In this chapter, we will host jQuery on our web server to not be dependent on a host.
We will import jQuery in all the pages of our application because we might need multiple pages. In addition, the cache of the browser will keep jQuery for some time so as not to download it too often. For this, we will download jQuery 1.11.0 and save it on the TasksManager/static/javascript/lib/jquery-1.11.0.js
file.
Then, you must add the following line in the head tag of the base.html
file:
<script src="{% static 'javascript/lib/jquery-1.11.0.js' %}"></script> {% block head %}{% endblock %}
With these changes, we can use jQuery in all the pages of our website, and we can add lines in the head
block from the template which extends base.html
.
In this section, we will modify the page that displays the list of tasks for deleting the tasks to be carried out in AJAX. To do this, we will perform the following steps:
- Add a
Delete
button on thetask_list
page. - Create a JavaScript file that will contain the AJAX code and the function that will process the return value of the AJAX request.
- Create a Django view that will delete the task.
We will add the Delete button by modifying the tasks_list.html
template. To do this, you must change the for
task in task loop in tasks_list
as follows:
{% for task in tasks_list %} <tr id="task_{{ task.id }}"> <td><a href="{% url "task_detail" task.id %}">{{ task.title }}</a></td> <td>{{ task.description|truncatechars:25 }}</td> <td><a href="{% url "update_task" task.id %}">Edit</a></td> <td><button onclick="javascript:task_delete({{ task.id }}, '{% url "task _delete_ajax" %}');">Delete</button></td> </tr> {% endfor %}
In the preceding code, we added an id
property to the <tr>
tag. This property will be useful in the JavaScript code to delete the task line when the page will receive the AJAX response. We also replaced the Delete link with a Delete button that executes the JavaScript task_delete()
function. The new button will call the task_delete()
function to execute the AJAX request. This function accepts two parameters:
- The identifier of the task
- The URL of the AJAX request
We will create this function in the static/javascript/task.js
file by adding the following code:
function task_delete(id, url){ $.ajax({ type: 'POST', // Here, we define the used method to send data to the Django views. Other values are possible as POST, GET, and other HTTP request methods. url: url, // This line is used to specify the URL that will process the request. data: {task: id}, // The data property is used to define the data that will be sent with the AJAX request. dataType:'json', // This line defines the type of data that we are expecting back from the server. We do not necessarily need JSON in this example, but when the response is more complete, we use this kind of data type. success: task_delete_confirm, // The success property allows us to define a function that will be executed when the AJAX request works. This function receives as a parameter the AJAX response. error: function () {alert('AJAX error.');} // The error property can define a function when the AJAX request does not work. We defined in the previous code an anonymous function that displays an AJAX error to the user. }); } function task_delete_confirm(response) { task_id = JSON.parse(response); // This line is in the function that receives the AJAX response when the request was successful. This line allows deserializing the JSON response returned by Django views. if (task_id>0) { $('#task_'+task_id).remove(); // This line will delete the <tr> tag containing the task we have just removed } else { alert('Error'); } }
We must add the following lines after the title_html
block in the tasks_list.html
template to import task.js
in the template:
{% load static %} {% block head %} <script src="{% static 'javascript/task.js' %}"></script> {% endblock %}
We must add the following URL to the urls.py
file:
url(r'^task-delete-ajax$', 'TasksManager.views.ajax.task_delete_ajax.page', name="task_delete_ajax"),
This URL will use the views contained in the view/ajax/task_delete_ajax.py
file. We must create the AJAX module with the __init__.py file
and our task_delete_ajax.py
file with the following content:
from TasksManager.models import Task from django.http import HttpResponse from django import forms from django.views.decorators.csrf import csrf_exempt # We import the csrf_exempt decorator that we will use to line 4. import json # We import the json module we use to line 8. class Form_task_delete(forms.Form): # We create a form with a task field that contains the identifier of the task. When we create a form it allows us to use the Django validators to check the contents of the data sent by AJAX. Indeed, we are not immune that the user sends data to hack our server. task = forms.IntegerField() @csrf_exempt # This line allows us to not verify the CSRF token for this view. Indeed, with AJAX we cannot reliably use the CSRF protection. def page(request): return_value="0" # We create a variable named return_value that will contain a code returned to our JavaScript function. We initialize the value 0 to the variable. if len(request.POST) > 0: form = Form_task_delete(request.POST) if form.is_valid(): # This line allows us to verify the validity of the value sent by the AJAX request. id_task = form.cleaned_data['task'] task_record = Task.objects.get(id = id_task) task_record.delete() return_value=id_task # If the task been found, the return_value variable will contain the value of the id property after removing the task. This value will be returned to the JavaScript function and will be useful to remove the corresponding row in the HTML table. # The following line contains two significant items. The json.dumps() function will return a serialized JSON object. Serialization allows encoding an object sequence of characters. This technique allows different languages to share objects transparently. We also define a content_type to specify the type of data returned by the view. return HttpResponse(json.dumps(return_value), content_type = "application/json")
In this chapter, we learned how to use jQuery. We saw how to easily access the DOM with this library. We also created an AJAX request on our TasksManager
application and we wrote the view to process this request.
In the next chapter, we will learn how to deploy a Django project based on the Nginx and PostgreSQL server. We will see and discuss the installation step by step.