Skip to main content

Ajax in Django, Ajax Tutorials in Django



Ajax in Django, Ajax Tutorials in Django:


Ajax means Asynchronous JavaScript or Jquery and XML, it is used to partially update the content of the web page excluding complete web form.

Ajax improves the performance of web application and provide dynamic programming approach without reloading and submit the data.


for example, if we create a registration form and we want to check that the email already exists when the user switches to the next text field then we can create ajax code to check the email id.


when we select the country then the state list and when we select the state then the city list will be populated by AJAX.


when we search from Facebook or Google search box then data will be populated when we press any key that will be managed by Ajax.



Role of JavaScript or Jquery:-

It is used to handle the event in Ajax Process, which means if we select a dropdown list and display data into another dropdown list, it will be managed by AJAX.



Role of XML:-

XML means Extensible markup language which is used to transfer data from client machine(Browser) to server machine (Apache Server) and server machine to the server machine.

XMLHttpRequest:-  this class is used to send data from browser to web server.

XMLHttpResponse:-  It is used to get web server response using XML form.


Assignment:

Create Search Box which will search respective record from the database and show into the browser?

1) Create Two Different Method to load and action using views.py and define into urls.py

path('ajaxload',views.ajaxload,name='ajaxload'),
path('ajaxdata',views.ajaxdata,name='ajaxdata'),


def ajaxload(request):
    return render(request,"scsapp/ajaxsearch.html")

def ajaxdata(request):
    data = request.GET["q"]
    result = Register.objects.filter(fullname__contains=data)
    return render(request,"scsapp/ajaxdata.html",{'res':result})


2)  Create html page under views folder ajaxsearch.html and ajaxdata.html


    Write code ajaxsearch.html of AJAX using JS

    <!DOCTYPE html>
<html>
<head>
<title></title>
    <script type="text/javascript">
    function showdata(a)
    {
             xmlhttp = new XMLHttpRequest();
             xmlhttp.onreadystatechange=function()
             {
              document.getElementById("res").innerHTML=xmlhttp.responseText; 

             }
             xmlhttp.open("get","ajaxdata?q="+a,true);
             xmlhttp.send();


    }

    </script>
</head>
<body>
   Type and char to search user's<br>
   <input type="text" id="txtseaarch" onkeyup="showdata(this.value)">
   <div id="res"></div>
</body>
</html>

3)  ajaxdata.html

<table border="1">
<tr><th>EmailID</th><th>Password</th><th>Fullname</th></tr>
 {% for q in res %}
     <tr>  <td>{{ q.emailid }} </td><td> {{ q.password }} </td><td> {{ q.fullname }}</td></tr>
 {% endfor %}

</table>


ANOTHER TASK:
NOW I have explained another example of AJAX.

I will create Course Model and display selected course using AJAX:-


Create Course Model

    class Course(models.Model):
courseid=models.IntegerField()
coursename= models.CharField(max_length=50)
coursefees=models.CharField(max_length=20)
def __str__(self):
return "courseid "+str(self.courseid) + " coursename is "+str(self.coursename) + " fees is " + str(self.coursefees)



Step2nd:-

Create URLs to load Ajax view and Action Ajax View.

path('courseinfo',views.courseinfo,name='courseinfo'),
path('coursedata',views.coursedata,name='coursedata'),



Step3rd:-


Write Following Code on Views.py file under respective method

def courseinfo(request):
courses = Course.objects.all()
return render(request,"dbapp/courseinfo.html",{'res':courses})

def coursedata(request):
data = Course.objects.get(pk=int(request.GET["q"]))
return render(request,"dbapp/coursedata.html",{'res':data})



Step4th:-

Create HTML file to load and action view of AJAX

Code of CourseInfo.html


<!DOCTYPE html>
<html>
<head>
<title></title>

<script type="text/javascript">
        function showcourse(a)
        {
            xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange=function()
            {
           document.getElementById("result").innerHTML = xmlhttp.responseText;
            }

            xmlhttp.open("GET","coursedata?q="+a,true);
            xmlhttp.send();


        }


</script>
</head>
<body>
<select onchange="showcourse(this.value)">
<option value="">Select Course</option>
{%  for r in res  %}

<option value="{{r.id}}">{{r.coursename}}</option>

{% endfor  %}


</select>

<div id="result">


</div>

</body>
</html>



Code of Coursedata.html

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>COURSE ID IS:-  {{res.id}}</p>
<p>COURSE NAME IS:-  {{res.coursename}}</p>
<p>COURSE FEES IS:-  {{res.coursefees}}</p>




</body>
</html>




TASK 
NOW I am explaining another example of AJAX to check User Already Exist under userid textfiled.

STEP1st:-

Create Model Class


class Reg(models.Model):
uname= models.CharField(max_length=20)
pwd=models.CharField(max_length=10)
email=models.CharField(max_length=20)
mobile = models.CharField(max_length=12)
def __str__(self):
return "rno is "+str(self.uname)+ " password is "+self.pwd + " emailid is "+self.email+ "mobile no  is "+str(self.mobile)




Step2nd:-

Create urls.py

path('reg',views.reg,name='reg')
path('checkuser',views.checkuser,name='checkuser')



Create Views.py:-

def reg(request):
if request.method=="POST":
r = Reg(uname=request.POST["txtuser"],pwd=request.POST["txtpass"],email=request.POST["txtemail"],mobile=request.POST["txtmobile"])
r.save()
return redirect('login')
return render(request,"dbapp/reg.html")




def checkuser(request):
data = Reg.objects.filter(uname=request.GET['q'])
r= ''
if data.count()>0:
r = 'Userid already exist'
else:
r= ''
return HttpResponse(r)

    

Html page to create Ajaxview of Registration Page

<!DOCTYPE html>
<html>
<head>
<title></title>
   <script type="text/javascript">
    function checkusername(a)
    {
    xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange=function()
            {
            if(xmlhttp.responseText!='')
            {
            document.getElementById("result").innerHTML = xmlhttp.responseText;
            document.getElementById("txtuser").focus();
            }
            else
            {
            document.getElementById("txtpass").focus();
            }
            }

            xmlhttp.open("GET","checkuser?q="+a,true);
            xmlhttp.send();
    }


   </script>

</head>
<body>
<form action="" method="post">
{%  csrf_token %}
<input type="text" name="txtuser" id="txtuser" placeholder="Enter username" onblur="checkusername(this.value)" /> <span id="result"></span>
<br><br>
<input type="password" name="txtpass" id="txtpass" placeholder="Enter password" />
<br><br>
<input type="text" name="txtemail" placeholder="Enter email" />
<br><br>
<input type="text" name="txtmobile" placeholder="Enter mobile" />
<br><br>
<input type="submit" name="btnsubmit" value="Reg" />
</form>

</body>
</html>
    

    









Comments

  1. Sir,

    def ajaxdata(request):
    data = request.GET["q"]
    result = Register.objects.filter(fullname__contains=data)
    return render(request,"scsapp/ajaxdata.html",{'res':result})


    What is Register Here??

    ReplyDelete
  2. #
    Register is table name of database

    ReplyDelete

Post a Comment

POST Answer of Questions and ASK to Doubt

Popular posts from this blog

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

Conditional Statement in Python

It is used to solve condition-based problems using if and else block-level statement. it provides a separate block for  if statement, else statement, and elif statement . elif statement is similar to elseif statement of C, C++ and Java languages. Type of Conditional Statement:- 1) Simple if:- We can write a single if statement also in python, it will execute when the condition is true. for example, One real-world problem is here?? we want to display the salary of employees when the salary will be above 10000 otherwise not displayed. Syntax:- if(condition):    statements The solution to the above problem sal = int(input("Enter salary")) if sal>10000:     print("Salary is "+str(sal)) Q)  WAP to increase the salary of employees from 500 if entered salary will be less than 10000 otherwise the same salaries will be displayed. Solution:- x = int(input("enter salary")) if x<10000:     x=x+500 print(x)   Q) WAP to display th...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...