Rachit Agarwal
Rachit Agarwal

Reputation: 57

javascript-POST request using ajax in Django issue

I am a beginner and self learned programmer and have written a code on my own. I am attempting to use Javascript post request using ajax and facing some continuous problem. There are lot of mistakes in code and want you guys to correct it with an explanation. Here is my base.js file:

var user = {
signup : function() {
    var firstname = document.signupform.first_name.value;
    var lastname = document.signupform.last_name.value; 
    var username = document.signupform.username.value;
    var email = document.signupform.email.value;
    var password = document.signupform.password.value;
    var confirmpassword = document.signupform.confirmpassword.value;
    if (firstname == "")
    {
        alert("Please provide your first name!")
        document.signupform.first_name.focus();
    }
    else if (username == "")
    {
        alert("Please provide the username!")
        document.signupform.username.focus();
    }
    else if (email == "")
    {
        alert("Please provide your Email!")
        document.signupform.email.focus() ;
    }

    else if (password == "")
    {
        alert("Please enter a valid password")
        document.signupform.password.focus() ;
    }
    else if (password != confirmpassword) 
    {
        alert("Passwords do not match.");
        document.signupform.confirmpassword.focus() ;
    }
    else
    {
        data = {"firstname":firstname, "lastname":lastname, "username":username, "email":email,"password":password};
        this.postRequest(data);
    }
    return false
},

postRequest:function(data,url,form) 
{
    $.ajax({
              type: "POST",
              url: '',
              data: data,
              success: function(data){
                if(data["success"])
                    {

                    window.location.href = '{% url home %}'

                    }
                else
                    {
                        alert(data["error"])
                    }
                }
            });
},

views.py:

class UserFormView (TemplateView):
template_name = "signup.html"
#display signup blank form
def get(self, request,*args,**kwargs):
    context = super(UserFormView,self).get_context_data(**kwargs)
    return self.render_to_response(context)


#process form data
def post(self, request,*args,**kwargs):
    context = {}
    data = request.POST
    user = get_user_model().objects.create(username=data["username"],first_name=data["firstname"],email=data["email"],last_name=data["lastname"])
    user.set_password(data["password"])
    user.save()
    user.backend = "django.contrib.auth.backends.ModelBackend"
    if user is not None:
        login(request, user)
        context["success"] = True
        # return redirect("home")
    else:
        context["success"] = False
        context["error"] = "The username is already taken!"  

        return self.render_to_response(context)

I am putting 'onclick' function in my signup.html:

<a class="btn btn-success" href="javascript:void(0)" onclick="user.signup()">Sign Up</a>

I am getting an error of csrf as well.

Upvotes: 1

Views: 65

Answers (1)

user5662309
user5662309

Reputation:

if you direct pass the data to the server you need to pass csrf token, or else just put {% csrf_token %} inside the form and submit the form data after the validation.

var formData = new FormData($(this)[0]);  ## Active   
$.ajax({
        url: "{% url 'apply_job' %}",
        type: 'POST',
        data: formData,
        async: true,
        cache: false,
        contentType: false,
        processData: false,

        success: function (returndata)
          {
              if(returndata.status == 'success')
                {document.getElementById('result').innerHTML = returndata.result
                  Callback();
                }
              else if(returndata.status == 'error')
                {
                    document.getElementById('result').innerHTML = returndata.result

                    Callback();
                }

          }

      });

Upvotes: 1

Related Questions