13

I have a registration form in HTML, which I have attached below.

<form id="registerForm">
            <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required>
            <input type="text" pattern="[A-Za-z]{1,20}" placeholder="Last Name" name="guestLName" title="Up to 20 alphabetical characters" required>
            <input type="email" placeholder="Email" name="guestEmail" title="Must be a valid email address" required>
            <input type="text" pattern="08[36579]-\d{7}" placeholder="Phone Number" name="guestPhone" title="Must be an irish mobile number of format 08?-7 digits" required>
            <input type="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}" placeholder="Password" name="guestPassword" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
            <br>
            <button id="myButton">Register</button>
</form> 

I am trying to post the information from the form when someone fills it out to a python API which will then insert the information to a MySQL Database.

I want the functionality of the required and patterns in the HTML.

I am using jQuery 3.1.1 and Ajax to post the form data to the API.

My JQuery/Ajax is attached below:

$("#registerForm").submit(function() 
{
    $.ajax(
    {
        url: "URL_GOES_HERE",
        data: $('#registerForm').serialize(),
        type: 'POST',
        async: false
    })
    .done(function(response) 
    {
        console.log(response);

        var result = JSON.parse(response);      
    })
});

I think this should work however if I fill out the form and click the Register Button it reloads the page and just adds the form information to the URL.

An example of this is :

URL_GOES_HERE/register.html?guestFName=Joe&guestLName=Bloggs&guestEmail=bloggs%40gmail.com&guestPhone=087-1111111&guestPassword=TestPassword1

Why is this behaving like this?

All help is extremely appreciated

EDIT: e.preventDefault(); doesn't fix the issue.

Fendec
  • 367
  • 1
  • 5
  • 23

13 Answers13

4

I think you should use <input type='button'> instead <button> and just use .click() event of that <input type='button'> as below.

Change

<button id="myButton">Register</button>

To

<input type='button' id='btnRegeister' value='Register'/>

And in JS

Change

$("#registerForm").submit(function()

To

$("#btnRegeister").click(function()

So your entire code become as below now ..

<form id="registerForm">
            <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required>
            <input type="text" pattern="[A-Za-z]{1,20}" placeholder="Last Name" name="guestLName" title="Up to 20 alphabetical characters" required>
            <input type="email" placeholder="Email" name="guestEmail" title="Must be a valid email address" required>
            <input type="text" pattern="08[36579]-\d{7}" placeholder="Phone Number" name="guestPhone" title="Must be an irish mobile number of format 08?-7 digits" required>
            <input type="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}" placeholder="Password" name="guestPassword" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
            <br>
            <input type='button' id='btnRegeister' value='Register'/>
</form>

$(document).ready(function(){
    $("#btnRegeister").click(function() 
    {
       $.ajax(
       {
           url: "URL_GOES_HERE",
           data: $('#registerForm').serialize(),
           type: 'POST',
           async: false
       })
       .done(function(response) 
       {
           console.log(response);

           var result = JSON.parse(response);      
       })
   });
});

Try Above code, it is working for me

prog1011
  • 3,425
  • 3
  • 30
  • 57
1

EDIT: You should include the 'type' attribute to your HTML:

<button type="submit" name="submit"></button>

Using the 'preventDefault' function will prevent the default form submit / redirect- This will stop the unintended behavior

$("#registerForm").submit(function(e) 
{
    e.preventDefault(); // Add this

    $.ajax(
    {
        url: "URL_GOES_HERE",
        data: $(this).serialize(),
        type: 'POST',
        async: false
    })
    .done(function(response) 
    {
        console.log(response);
        var result = JSON.parse(response);      
    })
});
DeclanPossnett
  • 376
  • 1
  • 5
  • 13
0

you need a preventDefault() to prevent the default behaviour of the form

$("#registerForm").submit(function(e) 
{
    e.preventDefault();

    $.ajax(
    {
        url: "URL_GOES_HERE",
        data: $('#registerForm').serialize(),
        type: 'POST',
        async: false
    })
    .done(function(response) 
    {
        console.log(response);

        var result = JSON.parse(response);      
    })
});
Sepultura
  • 997
  • 1
  • 9
  • 28
0

are you working on Safari browser by any chance?? because it is the only browser that i know who doesn't support required and pattern attributes and he will send the form any way if it is the case i can give you a good solution if not the only option you have is to remove the form tag and fire the ajax request on button click.

  • I am working on Firefox and Chrome. I switched from one to the other becuase I thought that maybe it was an issue with the browser but it wasn't. – Fendec Mar 07 '17 at 17:12
  • i am working on some site and i have form built like the way you want it, open this link and click on the send button if an alert shows up that means the problem is in your code if not then it is your browser's problem. here is the form link http://locationvacancesmaamoura.com/vinaigre/contact – Souhail Ben Slimene Mar 07 '17 at 17:17
0

There are a couple of hints, which I assume, may get it work.

  1. Wrap your jQuery code into $(function() { ... }.
  2. Don't use async: false with your jQuery AJAX call.
  3. Use event's stopPropagation() and preventDefault() to prevent the form submit event to bubble up.

Other than these, I didn't change anything and got your form to work. I used HTTPBin to post your data, and got appropriate response.

Here is a fiddle of the same.

$(function() {

  $("#registerForm").submit(function(e) {
    e.stopPropagation();
    e.preventDefault();

    $.ajax({
        url: "https://httpbin.org/post",
        data: $('#registerForm').serialize(),
        type: 'POST'
      })
      .done(function(response) {
        console.log(response);
        //var result = JSON.parse(response);
      });
  });

});
31piy
  • 23,323
  • 6
  • 47
  • 67
0

Check if dollar sign $ belongs to jQuery by typing this $.fn.jquery to the console window. If you don't get the jQuery version like 3.1.1, then jQuery isn't loading or something else gets to be assigned to the dollar $ sign.

Change your code as this here:

jQuery(function($)
{
    $("#registerForm").submit(function(e) 
    {
        console.log('Form submitting');
        e.preventDefault();

        $.ajax(
        {
            url: "URL_GOES_HERE",
            data: $('#registerForm').serialize(),
            type: 'POST',
            async: false
        })
        .done(function(response) 
        {
            console.log(response);

            var result = JSON.parse(response);      
        })
    });
});

Also, is doesn't really matters, but try to add POST method to your form just to check this case:

<form id="registerForm" method="POST">
    <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required>
    <input type="text" pattern="[A-Za-z]{1,20}" placeholder="Last Name" name="guestLName" title="Up to 20 alphabetical characters" required>
    <input type="email" placeholder="Email" name="guestEmail" title="Must be a valid email address" required>
    <input type="text" pattern="08[36579]-\d{7}" placeholder="Phone Number" name="guestPhone" title="Must be an irish mobile number of format 08?-7 digits" required>
    <input type="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}" placeholder="Password" name="guestPassword" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
    <br>
    <button id="myButton">Register</button>
</form>

And try to submit your form after you check the console window for errors.

Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
0

I recommend you delete the "button" tag and use "a" tag with some css to transform this "a" tag in a button (For example with "btn" class from bootstrap)

<form id="registerForm">
            <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required>
            <input type="text" pattern="[A-Za-z]{1,20}" placeholder="Last Name" name="guestLName" title="Up to 20 alphabetical characters" required>
            <input type="email" placeholder="Email" name="guestEmail" title="Must be a valid email address" required>
            <input type="text" pattern="08[36579]-\d{7}" placeholder="Phone Number" name="guestPhone" title="Must be an irish mobile number of format 08?-7 digits" required>
            <input type="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}" placeholder="Password" name="guestPassword" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
            <br>
            <a class="btn btn-default">Register</a>
</form> 

Then in your JS code:

$("#registerForm a").click(function() 
{

    $.ajax(
    {
        url: "URL_GOES_HERE",
        data: $('#registerForm').serialize(),
        type: 'POST',
        async: false
    })
    .done(function(response) 
    {
        console.log(response);

        var result = JSON.parse(response);      
    })
})
Null_teke
  • 96
  • 4
  • 1
    This is misleading. Changing `button` to `a` is not required at all. Plus, it adds extra burden of including the relevant CSS. – 31piy Mar 16 '17 at 04:34
0

It seems like other event has been triggered when the form submit, try event.stopImmediateProgapation() or your event is behind another event which will reload the page in event queue.

LeonDWong
  • 11
  • 3
0

You can stop default behaviour of submit by using: e.preventDefault()

$("#registerForm").submit(function(e) 
{
    e.preventDefault();
    console.log("it doesn't reload")
    // your ajax call
});

Hope it's helpfull! ;)

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
0

You are doing submit form by ajax so form_id.submit() is not a good one ! If you want to do form submit by button clicked as ajax format ,catch click event with button id and add preventDefault() or return false from preventing page load.

$("#myButton").click(function(e) 
{
    e.preventDefault();
    $.ajax(
    {
        url: "URL_GOES_HERE",
        data: $('#registerForm').serialize(),
        type: 'POST',
        async: false
    })
    .done(function(response) 
    {
        console.log(response);

        var result = JSON.parse(response);      
    });
    //return false;
});
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
0

You need to prevent the default behavior of the form by adding e.preventDefault(); (after recieving the e as a param) to the end of your .submit handler like so:

$("#registerForm").submit(function(e)  //  <-- Add the e as param
{
    $.ajax(
    {
        url: "URL_GOES_HERE",
        data: $('#registerForm').serialize(),
        type: 'POST',
        async: false
    })
    .done(function(response) 
    {
        console.log(response);

        var result = JSON.parse(response);      
    })
    e.preventDefault();   //  <-- Here is where the magic happens
});

The e.preventDefault(); prevents the actual native submission of the form (the page reload...)

Ronen Cypis
  • 21,182
  • 1
  • 20
  • 25
0

Try this:

$(document).on('submit','form',function(){
   // code
   $.ajax({
    url: "URL_GOES_HERE",
    data: $('#registerForm').serialize(),
    type: 'POST',
    async: false
   }).done(function(response){
    console.log(response);
    var result = JSON.parse(response);      
   })
});
Ram Depala
  • 51
  • 3
-1

I am able to replicate and fix your problem with NodeJS, Express, Multer and Internet Edge.

When I edit:

<form id="registerForm">

to

<form method="post" id="registerForm">

I am also sending it a valid Response with Express.

allegory
  • 124
  • 1
  • 1
  • 10
  • I was just stating what I was using in my environment. You have to make sure you send a valid response when submitting a form or strange things can happen to the browser. Also my fix is with plain HTML. – allegory Mar 16 '17 at 16:32