SCS SCS - 5 months ago 14
Ajax Question

Ajax code form wont work on submit

[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. ]

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

Answer

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