{% csrf_token %} {% csrf_token %} {% csrf_token %}

CSRF verification failed. Request aborted . im trying to send data from AJAX to views.py but it's showing this error

48 Views Asked by At

registration.html

 <form method="POST" id="someForm">
          {% csrf_token %}

          <label for="name">Name:</label>
          <input type="text" id="name" name="name" required />

          <label for="email">Email:</label>
          <input type="email" id="email" name="email" required />

          <label for="password">Password:</label>
          <input type="password" id="password" name="password" required />

          <input type="submit" value="Register" name="createuser" />
        </form>
      </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
      let URLd = "{% url 'defaultpg' %}";
      let nameInput = document.getElementById("name");
      let emailInput = document.getElementById("email");
      let passwordInput = document.getElementById("password");
      const someForm = document.getElementById("someForm");

      someForm.addEventListener("submit", (e) => {
        e.preventDefault(); // prevent default behavior of the form

        var csrfToken = $("input[name='csrfmiddlewaretoken']").val();
        let nameValue = nameInput.value;
        let emailValue = emailInput.value;
        let passwordValue = passwordInput.value;
        let isNameValid = /^[a-zA-Z]+$/.test(nameValue);
        let isEmailValid = /^\S+@\S+\.\S+$/.test(emailValue);
        let isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(
          passwordValue
        );

        if (isNameValid && isEmailValid && isPasswordValid) {
          alert("Successful");
          $.ajax({
            type: "POST",
            url: /defaultpg/,
            headers: { "X-CSRFToken": csrfToken },
            data: {
   
              name: nameValue,
              email: emailValue,
              password: passwordValue,
              csrfmiddlewaretoken: csrfToken,
            },
            
            dataType: "json",
            success: function (data) {
              // Handle success response
              alert("Successful msg");
            },
            error: function () {
              // Handle error response
              alert("Failure");
            },
          });
        } else {
          // Handle validation errors
          if (!isNameValid) {
            alert("Please enter a valid Name");
          } else if (!isEmailValid) {
            alert("Please enter a valid Email Address");
          } else {
            alert(
              "Password must contain letters, capital letter, small letter, special character, and numbers with a length above 8"
            );
          }
        }
        // rest of your logic goes here....
      });
    </script>

this is the html file that receives input from forms and then over to js so that AJAX can send data to views.py im getting 403 error when the url ie /defaultpg is called

urls.py

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

Views.py

@csrf_protect
def defaultpg(request):
    print("-----------------------")
    if request.method == "POST":
        # Use request.POST.get() to retrieve form data
        name = request.POST.get("name")
        email = request.POST.get('email')
        password = request.POST.get('password')
        print(name, email, password)
        return render(request, 'Entry/login.html')

    # You may want to handle the case when the request method is not POST
    return render(request, 'Entry/login.html')

settings.py

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    'django.middleware.csrf.CsrfViewMiddleware',  # Include CSRF middleware only once
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

I tried to manually put defaultpy in url it works fine but its not working now when I do it with ajax

2

There are 2 best solutions below

1
alvaro avila On

You have to set the withCredentials parameter to true in your request. Check this question Sending credentials with cross-domain posts?

3
Hetvi On

First by doing console.log(csrfToken) just make sure that your are getting csrf token

Another thing you need do is try to pass data as shown below

data:function (d) {
    d.name = nameValue;
    d.email= emailValue;
    d.password= passwordValue
    d.csrfmiddlewaretoken = csrfToken;
    return d;
},