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

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

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...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...