Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

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



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>



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>





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>
    

    






1 Comments

If you have any doubt in programming or join online classes then you can contact us by comment .

  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

Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post