最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - Ajax post request loads same page with form data added to URL - Stack Overflow

programmeradmin1浏览0评论

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&guestPhone=087-1111111&guestPassword=TestPassword1

Why is this behaving like this?

All help is extremely appreciated

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

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.

Share Improve this question edited Mar 7, 2017 at 16:43 Fendec asked Mar 7, 2017 at 16:28 FendecFendec 3671 gold badge6 silver badges24 bronze badges 13
  • One thing that is missing in your submit function is the event.preventDefault() function. If you add that the page should not be reloaded. See for example this post – Locco0_0 Commented Mar 7, 2017 at 16:35
  • What happens when you use preventDefault()? Still appends the data to the url? – DeclanPossnett Commented Mar 7, 2017 at 16:45
  • Yeah the exact same thing happens everytime – Fendec Commented Mar 7, 2017 at 16:46
  • And the 'URL_GOES_HERE' is replaced with a different url to the current html file? – DeclanPossnett Commented Mar 7, 2017 at 16:48
  • 'URL_GOES_HERE' is replaced with the url to the Python API which is hosted on PythonAnywhere – Fendec Commented Mar 7, 2017 at 16:49
 |  Show 8 more comments

13 Answers 13

Reset to default 4 +50

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

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

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

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.

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.

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

});

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

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.

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! ;)

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

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...)

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

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.

发布评论

评论列表(0)

  1. 暂无评论