0

I have a login page, when user write username and password, I want to pass this information to server(post) and if I have error i want to just show error message and if I have not error so I want to submit it, in this case always prevent form submit. In the below code always prevent submit and get error message from server and show it:
login.js

   $('#login-form').submit(function(e){

    var message;
    $.post('/login/', $(this).serialize(), function(data){
        obj = JSON.parse(data);
        message = obj.message;
        alert(message);
});
    e.preventDefault();
});


view.py

// if username and password is faild
message="login information is failed"
return HttpResponse(json.dumps({'message': message}))
//else with specific data
return render(request, 'front/member.html', data)

I want to do like this:

if(message) e.preventDefault();
// else submit

but first e.preventDefault(); execute and then message set from server what can i do for this problem?

  • are you using Django's form ? – JPG Sep 11 '18 at 03:21
  • @JPG yes, and in `// if username and password is faild` I used form.valid – Ebrahim Abdollahian Sep 11 '18 at 03:23
  • You can use [**`form.is_valid()`**](https://docs.djangoproject.com/en/2.1/ref/forms/api/#django.forms.Form.is_valid) to check the validation and can show the errors by [**`form.errors`**](https://docs.djangoproject.com/en/2.1/ref/forms/api/#django.forms.Form.errors). Can't you? – JPG Sep 11 '18 at 03:25
  • @JPG In .js file? – Ebrahim Abdollahian Sep 11 '18 at 03:29
  • Actually, I don't know how to alter the js file, I'm unaware of that. But, it could be possible without altering js file – JPG Sep 11 '18 at 03:31
  • You can post data into form. The form will take care about the validation. If the validation broke, (username and password not matched) form will return an `HTTP 400` status code. – JPG Sep 11 '18 at 03:34
  • Can you add complete `view` ? – JPG Sep 11 '18 at 03:34

1 Answers1

0

but first e.preventDefault(); execute and then message set from server what can i do for this problem?

This is because JavaScript is asynchronous: the function completes before you can get the response from the server because $.post request will run in the background.


You have two options to fix this:

  1. Instead of catching $('#login-form').submit, you can catch $('submit-button').click.
  2. Or you can serialize the form data and send it using another $.post.
xyres
  • 20,487
  • 3
  • 56
  • 85