banner



Can You Use Ajax On Sofa To Clean

AJAX or Asynchronous JavaScript And XML is a prepare of web development techniques using web technologies on the customer-side to create asynchronous web requests.

In simpler words, AJAX allows web pages to exist updated asynchronously by exchanging information with a web server behind the scenes. This means that updating parts of a web page is possible, without reloading the whole page.

We can make AJAX requests from Django templates using JQuery. With the jQuery AJAX methods, you tin can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post and you lot can load the external data straight into the selected HTML elements of your web page.

In this tutorial, we volition learn how to make AJAX HTTP Go and Mail service requests from Django templates.

Pre-Requirements

I am assuming y'all have a bones working noesis of Django. Therefore, I am non going into the projection setup function in instance you need help with that I recommend reading the following articles.

  • How To Create A 'Hello, Globe!' Application With Django
  • Building A Blog Application With Django

This is a very basic projection with an app called AJAX and I am using bootstrap and Django crispy form for styling.

Github repo -https://github.com/TheAbhijeet/Django-with-JQuery-and-AJAX

Making AJAX Go requests with Django and JQuery

The HTTP Go method is used to retrieve data from the server.

In this section, we will create a signup folio where we will bank check the availability of a username using JQuery and AJAX in Django templates. This is a very common requirement for almost modernistic apps.

views.py

          from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.views.generic.edit import CreateView from django.urls import reverse_lazy   @login_required def habitation(request):     render return(asking, 'abode.html')   class SignUpView(CreateView):     template_name = 'signup.html'     form_class = UserCreationForm     success_url = reverse_lazy('home')      def form_valid(self, course):         valid = super().form_valid(form)         login(self.request, self.object)         render valid   def validate_username(request):     """Check username availability"""     username = asking.GET.get('username', None)     response = {         'is_taken': User.objects.filter(username__iexact=username).exists()     }     return JsonResponse(response)                  

So here nosotros have three views first one is the dwelling house view which is basically rending a simple template.

Next is SignUpView inheriting from Django's CreateView course to create users using Django's builtin UserCreationForm class which provides a very basic course for user signup and on successful signup nosotros are logging in the user and and then redirecting them to the homepage.

Finally validate_username view is our AJAX view which returns a JSON object with boolean from the username exists query.

The JsonResponse course returns an HTTP response with an application/json content type, converting the given object into a JSON object. So if the username already exists in the database it will return a JSON object as follows.

          { 'is_taken': truthful }        

urls.py

          from django.urls import path from .views import  home, SignUpView, validate_username  urlpatterns = [     path('', home, proper noun='home'),     path('signup', SignUpView.as_view(), proper name='signup'),     path('validate_username', validate_username, proper name='validate_username') ]        

dwelling.html

          <h1>Welcome, {{ user.username }}!</h1>        

signup.html

          {% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en">  <caput>     <meta charset="UTF-eight">     <meta proper name="viewport" content="width=device-width, initial-scale=i.0">     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.ii/css/bootstrap.min.css"         integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> </caput>  <trunk>     <div grade="container mt-five w-50">         <form id="signupForm" method="POST">             {% csrf_token %}             {{ form|crispy  }}             <input type="submit" name="signupSubmit" class="btn btn-success btn-lg" />         </grade>     </div>      {% cake javascript %}     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>      <script>         $(document).ready(function () {             // grab the form'south submit result             $('#id_username').keyup(office () {                 // create an AJAX telephone call                 $.ajax({                     information: $(this).serialize(), // get the form data                     url: "{% url 'validate_username' %}",                     // on success                     success: function (response) {                         if (response.is_taken == true) {                             $('#id_username').removeClass('is-valid').addClass('is-invalid');                             $('#id_username').after('<div class="invalid-feedback d-block" id="usernameError">This username is not bachelor!</div>')                         }                         else {                             $('#id_username').removeClass('is-invalid').addClass('is-valid');                             $('#usernameError').remove();                          }                      },                     // on error                     fault: part (response) {                         // alert the error if any error occured                         console.log(response.responseJSON.errors)                     }                 });                  return simulated;             });         })     </script>     {% endblock javascript %} </body>  </html>                  

Let's breakdown the template is small pieces to empathize better.

Within the caput tag, we are loading the bootstrap from CDN you can download the library and serve it from static folders likewise.

          <form id="signupForm" method="Postal service">             {% csrf_token %}             {{ form|crispy  }} <input type="submit" name="signupSubmit" class="btn btn-success btn-lg" /> </form>                  

Then we are rending the Django form using crispy tag for styling.

          <script src="https://ajax.googleapis.com/ajax/libs/jquery/iii.5.one/jquery.min.js"></script>                  

Next, inside the javascript cake, nosotros are pulling JQuery from google CDN you lot can download it locally equally well.

          $(document).set up(function () {     ( .... ) })        

Then we have some other script having ready method, The ready() method is used to brand a function available after the document is loaded. The code written within the $(certificate ).ready() method will run once the page DOM is fix to execute JavaScript code.

          $('#id_username').keyup(function() {     // create an AJAX call     $.ajax({         data: $(this).serialize(), // go the course data         url: "{% url 'validate_username' %}",         // on success         success: function(response) {             if (response.is_taken == true) {                 $('#id_username').removeClass('is-valid').addClass('is-invalid');                 $('#id_username').after('<div class="invalid-feedback d-block" id="usernameError">This username is not available!</div>')             } else {                 $('#id_username').removeClass('is-invalid').addClass('is-valid');                 $('#usernameError').remove();              }          },         // on error         error: role(response) {             // alarm the error if any mistake occured             console.log(response.responseJSON.errors)         }     });      render false; });        

The AJAX method is triggered past keyup part it takes two parameters data and the URL  upon successful completion of requests one of either callback i.east success and fault gets invoked. On a successful call, we have a conditional statement to add together or remove the invalid class from the input course field and the return faux at the end of the script prevents forms from submitting, therefore, preventing page reload.

Salvage the files and run the server you should see AJAX in action.

Making AJAX Mail requests with Django and JQuery

The HTTP POST method is used to transport data to the server.

In this department, nosotros will learn how to make Post requests with JQuery and AJAX in Django templates.

Nosotros will create a contact form and relieve the data provided by the user into the database with JQuery and AJAX.

Making AJAX POST requests with Django

models.py

          from django.db import models  form Contact(models.Model):     name = models.CharField(max_length=100)     e-mail = models.EmailField()     bulletin = models.TextField()      def __str__(self):         return cocky.name                  

forms.py

          from django import forms from .models import Contact   form ContactForm(forms.ModelForm):     class Meta:         model = Contact         fields = '__all__'                  

urls.py

          from django.urls import path from .views import contact_form  urlpatterns = [    path('contact-form/', contact_form, name='contact_form') ]        

views.py

          from django.http import JsonResponse from django.shortcuts import return from .forms import ContactForm  def contact_form(request):     form = ContactForm()     if request.method == "Mail" and request.is_ajax():         course = ContactForm(request.Mail service)         if form.is_valid():             name = form.cleaned_data['proper name']             class.salve()             return JsonResponse({"name": proper noun}, condition=200)         else:             errors = grade.errors.as_json()             return JsonResponse({"errors": errors}, status=400)      return render(request, "contact.html", {"course": grade})                  

In the view, we are verifying the ajax request with request.is_ajax() method then if the form is valid we are saving it to the database and returning JSON object with status code and proper name and for an invalid form, we are returning the form errors with condition code 400 i.e bad request.

contact.html

          {% load crispy_forms_tags %}  <!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Contact us</title>     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"         integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">  </head>  <body>     <div class="container mt-5 w-50">         <grade id="contactForm" method="POST">             {% csrf_token %}             {{ form|crispy  }}             <input blazon="submit" name="contact-submit" course="btn btn-success btn-lg" />         </form>     </div>     {% block javascript %}     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.one/jquery.min.js"></script>      <script>         $(certificate).ready(function () {             // take hold of the form's submit event             $('#contactForm').submit(function () {                 // create an AJAX call                 $.ajax({                     data: $(this).serialize(), // get the form data                     type: $(this).attr('method'), // Become or POST                     url: "{% url 'contact_form' %}",                     // on success                     success: part (response) {                         alarm("Thankyou for reaching usa out " + response.name);                     },                     // on mistake                     mistake: function (response) {                         // alert the mistake if any mistake occured                         alert(response.responseJSON.errors);                         console.log(response.responseJSON.errors)                     }                 });                 return false;             });         })     </script>     {% endblock javascript %} </body>  </html>        

Allow'south break downward the template in smaller modules to sympathise it better.

First, nosotros are importing bootstrap inside the head tag from CDN then within the body, we are reading the form with crispy tag for styling.

And then inside the javascript cake offset, we are loading JQuery from the CDN.

                      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.i/jquery.min.js"></script>        

So Inside the $(certificate).ready()role we have our AJAX method.

          $('#contactForm').submit(function() {     // create an AJAX phone call     $.ajax({         data: $(this).serialize(), // become the form data         type: $(this).attr('method'), // GET or Postal service         url: "{% url 'contact_form' %}",         // on success         success: function(response) {             alert("Thankyou for reaching united states out " + response.proper noun);         },         // on error         error: function(response) {             // alarm the fault if any error occured             alert(response.responseJSON.errors);             panel.log(response.responseJSON.errors)         }     });     return false; });        

On course submit we are invoking the ajax method which is serializing the form data and sending it to the given URL. On a successful call, we are showing an alert dialog with a dynamic message based on the user name.

Making AJAX POST requests with Django and JQuery using Grade-based views

views.py

          from django.views.generic.edit import FormView from django.http import JsonResponse    class ContactFormView(FormView):     template_name = 'contact.html'     form_class = ContactForm      def form_valid(self, form):         """         If the course is valid return HTTP 200 condition         code along with name of the user         """         proper noun = form.cleaned_data['name']         form.save()         render JsonResponse({"proper name": name}, status=200)      def form_invalid(cocky, form):         """         If the form is invalid render condition 400         with the errors.         """         errors = grade.errors.as_json()         render JsonResponse({"errors": errors}, status=400)                  

We just need to render a JSON object from the form_valid() method of FormView, y'all can also employ other generic class-based views past overriding post() method.

DJANGO

Source: https://djangocentral.com/django-ajax-with-jquery/

Posted by: waltonshenell.blogspot.com

0 Response to "Can You Use Ajax On Sofa To Clean"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel