简体   繁体   中英

Page is reloading when form submit usng jquery ajax

I am trying to submit a form using jquery ajax. My problem is when I submitting the form its submitting but my page is reloading. I tried using preventDefault() . But I still couldn't figure this out.

This is the HTML for my form:

<form action="" method="post" id="addCategoryForm">
    <div class="form-group">
        <input type="text" class="form-control" id="new_category" name="new_category" autofocus>
    </div>
    <div class="form-group">
        <select class="form-control" name="parentCategoryList">
            <option value="">-- Parent Category --</option>
            <option value="">Lorem ipsum</option>
            <option value="">Lorem ipsdffum</option>
        </select>   
    </div>      
    <div class="form-group">
        <button class="btn btn-default" id="addCategory">Add New Category</button>
    </div>  
</form> 

This is how I tried it using jQuery:

$(document).on('click', 'button#addCategory', function (e) {    
    //e.preventDefault();       

    var data = $("form#addCategoryForm").serialize();

    $.ajax({
        type: "POST",
        url: "./includes/process.php",
        data: data,
        cache: false,
        beforeSend: function() {
            window.tr.animate({'backgroundColor':'#fb6c6c'},300);
        },
        success: function (response) {

            $('#success').html(response);
            $("#success-alert").fadeTo(2000, 500).slideUp(1000, function(){
                $("#success-alert").alert('close');
            });             
        }           
    });

    //return false;

});

When I uncomment e.preventDefault(); form is not sumbitting. If I comment it form is submitting but page is reloading.

Can anybody tell me whats the problem of this?

Hope somebody may help me out. Thanks in advance.

You should listen to the submit event, your elements were enclosed by a form

Try this event

  $('#addCategoryForm').on('submit', function(e) {
        e.preventDefault();

        //Do ajax here

  }

try this

<div class="form-group">
    <button type="button" class="btn btn-default" id="addCategory">Add New Category</button>
</div> 

Please note that i have added type="button" . This is because, when no type is mentioned, by default it takes it as a submit button. And that is the reason why page reloads

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