Wednesday, June 29, 2016

Jquery - disable the default action, reload datatables, and others


When I worked on a form submit, I would like to use the js code to submit the form. But I found out  it submitted twice. Then I realized I need to disable the default action from the form.

Also after finished the action, I would like the data table to be reloaded again. The code is as below.


     $("button").click(function(e)  
     {  
       e.preventDefault(); // default form action of the event will not be triggered  
       var data = {  
         'id[]' : []  
       };  
       $.each($("input[name='id[]']:checked"), function()  
       {  
         data['id[]'].push($(this).val());  
       });  
       $.ajax({  
         url : contextPath  
           + "/reloadTranscepta", type : "POST", dataType : "json", data : data, success : function(data)  
         {  
           table.ajax.reload(null, false); // Reload the table  
           $('#transcepta-select-all').prop('checked', false);  
           if (data.status == '200 OK')  
           {  
             $("#result").html('<strong>Success!</strong> The POs you selected have been sent successfully.');  
             $("#result").attr('class', 'alert alert-success');  
           }  
           else  
           {  
             $("#result").html('<strong>Error!</strong> A problem has been occurred while sending POs to Transcepta.');  
             $("#result").attr('class', 'alert alert-danger alert-error');  
           }  
         }, error : function(xhr, textStatus, errorThrown)  
         {  
           $("#result").html('<strong>Error!</strong> A problem has been occurred while sending POs to Transcepta.');  
           $("#result").attr('class', 'alert alert-danger alert-error');  
         }  
       });  
     });