简体   繁体   中英

$(“#”).submit with Ajax refreshing page

Not sure what is the issue as this code was working fine some time earlier, I am trying to submit my form using Ajax and this is my code

Ajax Code

 $(function() {
 $("#login").submit(function() {
   $('#signinPane').showLoading();
 $("#loginError").hide();
 var data = $(this).serializeObject();
    $.ajax({
        'type': "POST",
         'url': "<c:url value="/shop/customer/j_spring_security_check"/>",
         'data':data,
         'success': function(result) {

         }
       });

     return false;
   });
});

HTML Code

<form id="login" method="post" accept-charset="UTF-8">
<input id="userName" style="margin-bottom: 15px;" type="text" name="j_username" size="30" />
<input id="password" style="margin-bottom: 15px;" type="password" name="j_password" size="30" />
<button type="submit" id="login-button"></button>
</form>

My issue is, when I am clicking on submit button, page is getting refresh and no Ajax call is being submitted at all. Not sure what is happening.

I think you need to call preventDefault on event object.

Returning false is okay when you're in the vanilla JS handler, and you're not.

Try passing the event as a parameter and then calling e.preventDefault()

jsfiddle Documentation

$(function() {
    $("#login").submit(function(e) {
        e.preventDefault();
        $('#signinPane').showLoading();
        $("#loginError").hide();
        var data = $(this).serializeObject();
        $.ajax({
            'type': "POST",
            'url': "<c:url value="/shop/customer/j_spring_security_check"/>",
            'data':data,
            'success': function(result) {

            }
        });
    });
});

use

event.preventDefault();


$("#login").submit(function(event) {
    event.preventDefault();
    $('#signinPane').showLoading();

This will prevent default form submit characteristic.

Try:

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

http://api.jquery.com/event.preventDefault/

http://api.jquery.com/event.stopPropagation/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM