0

I am trying to make a sign up and login forms in a project that follows MVC pattern. So we can divide the process into 3 parts: 1- the front-end which is html,css and javascript. 2-Server-side which is PHP 3- database which is MySQL. The problem I have is that when I submit the form either Login or sign up I get a strange behavior that depend on the values i'm sending to the PHP code.

for the sign up process. when I submit the email and password the ajax request send successfully the data and the username and password are correctly inserted into the database, but the on success function is not called. and the page is refreshed. for the login processes. consider we have an already existing user in database 'user1@gmail.com' and password '1234'. if I entered the correct username and password I get the same behavior as the signup the page is refreshed and on success function is not called and the correct behavior that should happen based on the following codes that it should overwrite the page with the response, but if I send the correct username and password field is empty the onsuccess function is called and write in the document the response 'Hello from login wrong'. In the codes I wrote document.write() function to show only the response but it's not for the real implementation.

  • I see that your INSERT makes a correct prepare/execute call to DB, why did you not follow the same approach with SELECT? – Dharman Jun 07 '19 at 17:00
  • You need to use the javascript method [`preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) if you want to perform a function instead normal form action processing. – tshimkus Jun 07 '19 at 17:02
  • 1
    You do not cancel form submissions.... – epascarello Jun 07 '19 at 17:02
  • 1
    `mysqli_error()` should be `mysqli_error($conn)`, better yet: [How to enable MySQLi exception mode?](https://stackoverflow.com/a/22662582/1839439) – Dharman Jun 07 '19 at 17:08
  • 1
    You will need to either update your javascript so that it disabled the form submission or simply change your button from `type="submit"` to `type="button"`. Otherwise you are both submitting the form (which is your page redirect) and sending to `ajax`. – imvain2 Jun 07 '19 at 17:14
  • @Dharman Thank you so much for your advises and tips, I was going to implement these functions after the whole project works first. – Mohamed Moustafa Jun 07 '19 at 17:57
  • @imvain2 Thank you so much !. it worked. – Mohamed Moustafa Jun 07 '19 at 17:59
  • @tshimkus I just changed the button type from submit to button and it worked. – Mohamed Moustafa Jun 07 '19 at 17:59

1 Answers1

0

There are multiple ways to stop your form from submitting during ajax processing, one easy solution is to change your submit button to a button.

You do this by changing:

type="submit"

to

type="button"
imvain2
  • 15,480
  • 1
  • 16
  • 21