$.ajax() in Django, How to use Ajax in Django using $.ajax()?

0




$.ajax() is best  approach to implement Ajax operation, it provide best implementation for ajax operation.


$.ajax() use following code to implement Ajax Operation in Django.


Create Object of FormData to store form content

var formData = new FormData();

$(document).on('click', '#btnsubmit', function(e) {

        formData.append('uid', $('#txtuser').val())

        formData.append('upass', $('#txtpass').val())

        formData.append('email',  $('#txtemail').val())

        formData.append('mobile',  $('#txtmobile').val())

        formData.append('action', 'regcode')

        formData.append('csrfmiddlewaretoken', '{{ csrf_token }}')

          $.ajax({

              type: 'POST',

              url: '{% url "regcode" %}',

              data: formData,

              cache: false,

              processData: false,

              contentType: false,

              enctype: 'multipart/form-data',

              success: function (){

                  alert('The post has been created!')

              },

              error: function(xhr, errmsg, err) {

                  console.log(xhr.status + ":" + xhr.responseText)

              }

          })

      })



Step by Step Ajax implementation in Django:-

1)  Code for design file:-


<!DOCTYPE html>

<html>

<head>

<title></title>


   <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

   <script type="text/javascript">

   

      

        var formData = new FormData();

       

          $(document).on('click', '#btnsubmit', function(e) {

            formData.append('uid', $('#txtuser').val())

            formData.append('upass', $('#txtpass').val())

            formData.append('email',  $('#txtemail').val())

            formData.append('mobile',  $('#txtmobile').val())

            formData.append('action', 'regcode')

            formData.append('csrfmiddlewaretoken', '{{ csrf_token }}')

              $.ajax({

                  type: 'POST',

                  url: '{% url "regcode" %}',

                  data: formData,

                  cache: false,

                  processData: false,

                  contentType: false,

                  enctype: 'multipart/form-data',

                  success: function (){

                      alert('The post has been created!')

                  },

                  error: function(xhr, errmsg, err) {

                      console.log(xhr.status + ":" + xhr.responseText)

                  }

              })

          })


   




   </script>


</head>

<body>

<form>  

<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" id="txtemail" placeholder="Enter email" />

<br><br>

<input type="text" name="txtmobile" id="txtmobile" placeholder="Enter mobile" />

<br><br>

<input type="button" name="btnsubmit" id="btnsubmit" value="Reg" />


<div id="result1"></div>


 </form>

</body>

</html>



2)  Code for views.py


def reg(request):

return render(request,"dbapp/reg.html")


def regcode(request):

print("data is ",request.POST.get("uid"))

print(request.POST.get("upass"))

      r = Reg(uname=request.POST.get("uid"),pwd=request.POST.get("upass"),email=request.POST.get("email"),mobile=request.POST.get("mobile"))

r.save()

return HttpResponse("data inserted successfully")



3)  code of urls.py


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

path('regcode',views.regcode,name='regcode')


4)  code of models.py


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 "uname is "+str(self.uname)+ " password is "+self.pwd + " emailid is "+self.email+ "mobile no  is "+str(self.mobile)







Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)