1

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.

3
  • 1
    the new redirect after ajax guy, why don't you do a simple post request? Commented Sep 7, 2016 at 7:23
  • 1
    You haven't told us what is the problem. Commented Sep 7, 2016 at 7:25
  • 1
    from what i can tell you are not returning a proper json response from your django view Commented Sep 7, 2016 at 7:26

1 Answer 1

1

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();
                }

          }

      });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.