0

[okay, i am sorry if i posted a duplicate question but i am just new to ajax so i somehow misused the words while searching. ] - Jquery Form Submit Keeps Refreshing

I cant find the what is wrong with my code. This is my form code:

  <form id="UploadExcel" enctype="multipart/form-data" >
                            <input name="file" type="file" />
                            <input id="submit" type="submit" value="Submit" />
                        </form>

then this is my ajax form

$('#UploadExcel').submit(function(){
        $.ajax({
            url:'UploadServlet',
            type:'POST',
            dataType:'json',
            data: $('#UploadExcel').serialize(),
           success: function(data){
               if(data.isValid){
                   $("#ShowSheets").modal("show");
               }else{
                   alert('Please Put a Valid Excel Sheet');
               }
           }
        });
        return false;
    });

everything is just reloading which i think is not supposed to happen since i am using ajax. There is no error or anything in the console, so i dont think I have any problem with my servlet...

Community
  • 1
  • 1
SCS
  • 1,162
  • 3
  • 17
  • 31
  • Possible duplicate of [Stop form refreshing page on submit](http://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit) – nicael Jun 11 '16 at 17:46

2 Answers2

2

use preventDefault()

$('#UploadExcel').submit(function(e){
  e.preventDefault();
        $.ajax({
            url:'UploadServlet',
            type:'POST',
            dataType:'json',
            data: $('#UploadExcel').serialize(),
           success: function(data){
               if(data.isValid){
                   $("#ShowSheets").modal("show");
               }else{
                   alert('Please Put a Valid Excel Sheet');
               }
           }
        });
        return false;
    });
Ravisha Hesh
  • 1,504
  • 13
  • 19
1

You need to cancel the default action (form submit) first:

$('#UploadExcel').submit(function(e){
        // Prevent default action
        e.preventDefault()
        $.ajax({
            url:'UploadServlet',
            type:'POST',
            dataType:'json',
            data: $('#UploadExcel').serialize(),
           success: function(data){
               if(data.isValid){
                   $("#ShowSheets").modal("show");
               }else{
                   alert('Please Put a Valid Excel Sheet');
               }
           }
        });
        return false;
    });
James Hill
  • 60,353
  • 20
  • 145
  • 161