2017-09-25 80 views
-1

第4行給出了表單元素,但第5行在這裏沒有提供任何內容。我該怎麼辦?formData()在追加數據後沒有給出數據

$('#btnSave').click(function() { 
       var form = $("#myForm"); 
       var formData = new FormData($(form)[0]); 
       console.log(form);//this gives form elements 
       console.log(formData);// but this gives nothing 
       var url = '<?php echo base_url() ?>' + 'product/add'; 
        $.ajax({ 
         type    : 'post', 
         url     : url, 
         processData: false, 
         contentType: false, 
         data: formData, 
         success: function (response) { 
          if (response){ 
           $('#myModal').modal('hide'); 
           $('#myForm')[0].reset(); 
           $('.alert-success').html('Record Added').fadeIn().delay(4000).fadeOut('slow'); 

          } else { 
           alert('Error'); 
          } 
         }, 
         error: function() { 
          alert('could not add data'); 
         } 
        });      
       }); 
      }); 

// formData對象沒有附加任何東西。任何解決方案,請

回答

0

請嘗試下面的代碼,並在ajax代碼中做一些更改。在代碼中添加以下參數。

過程數據:假的,
的contentType:假的,

並添加var formData = new FormData($("#formID")[0]);線阿賈克斯開始之前。

或者檢查以下代碼並根據您的代碼進行更改。

$('#btnSave').click(function (event) { 
     var form = $("#myForm"); 
     var formData = new FormData($(form)[0]);;   
     var url = '<?php echo base_url() ?>' + 'product/add'; 
     if($('#picture').val()==''){ 
      alert("please select the file"); 
     } else{ 
      $.ajax({ 
       type: 'ajax', 
       data: formData, 
       url: url, 
       method: 'POST', 
       processData: false, 
       contentType: false, 
       success: function (response) { 
        if (response) { 
         $('#myModal').modal('hide'); 
         $('#myForm')[0].reset(); 
         $('.alert-success').html('Record Added').fadeIn().delay(4000).fadeOut('slow'); 
         setTimeout(function() {// wait for 5 secs(2) 
          location.reload(); // then reload the page.(3) 
         }, 1); 
        } else { 
         alert('Error'); 
        } 
       }, 
       error: function() { 
        alert('could not add data'); 
       } 

      }); 
     } 
    }); 
}); 
+0

謝謝@pankaj但我仍然有這個問題。再次查看這個plz –

+0

你是否正確地檢查了我的代碼? –

+0

只保留我在代碼中添加的東西,並相應地添加代碼 –

0

在你的代碼中有一個以上的錯誤,在這裏我有我正在使用AJAX代碼

  var form=document.getElementById('form_id'); 
      var fdata=new FormData(form); 
      $.ajax({ 
       type: "POST", 
       url: 'Your_url', 
       dataType: 'json', 
       data:fdata, 
       processData: false, 
       contentType: false, 
       beforeSend: function() { 

       }, 
       success: function (data) { 

        //Do something on response 
       }, 
       complete: function() { 

       } 
      }); 

這裏你的錯誤是您使用type: "ajax"未寫,因爲正確的方式您必須指定數據傳遞方法POST或GET,

代碼中的第二個錯誤是,您在代碼的第三行完成了兩個分號(;),所以這就是javascript無法正常工作的原因。

我希望這會對你有用。