2016-04-23 82 views
0

這是我的問題,Ajax工作很好,處理所有數據,但由於某種原因,我目前忽略它,它不顯示加載程序和成功div。AJAX後顯示加載程序和消息不會工作

HTML是一樣的東西

<form id="msform" action="#"> 
    <fieldset> 
    <!-- some fields --> 
    <input type="submit" Value="submit"> 
    </fieldset> 
</form> 

<div id="processing" class="row" style="display:none"></div> 

<div id="apf-response" class="row" style="display:none"></div> 

我的jQuery/AJAX是看着像:

$(document).ready(function(){ 
    $('#msform').submit(function(event){ 
    event.preventDefault(); 
    apfaddpost(); 
    }) 
}) 

function apfaddpost() { 
    var fd = new FormData($('#msform')[0]); 
    fd.append("main_image", $('#main_image')[0].files[0]); 
    fd.append("action", 'apf_addpost');  

    //Append here your necessary data 
    jQuery.ajax({ 
    type: 'POST', 
    url: apfajax.ajaxurl, 
    data: fd, 
    processData: false, 
    contentType: false, 
    beforeSend: function(){ 
     //here should be the issue. I'm hiding the form and showing the loader div 
     $('#msform').hide(); 
     $('#processing').show(); 
    }, 
    success: function(data, textStatus, XMLHttpRequest) { 
     //when it's completed hide loader and show success message 
     $('#processing').hide(); 
     $('#apf-response').show(); 
     var id = '#success'; 
     jQuery(id).html(''); 
     jQuery(id).append(data); 
     resetvalues($('#msform')); 
    }, 
    error: function(MLHttpRequest, textStatus, errorThrown) { 
     alert(errorThrown); 
    } 
    }); 
} 

這是正確的方法是什麼?我做錯了什麼?

編輯 這是可能的,這個問題可以通過event.preventDefault();action="#"給予?

解決

我已經改變了我的jQuery代碼到

function apfaddpost() { 
    var fd = new FormData($('#msform')[0]); 
    fd.append("main_image", $('#main_image')[0].files[0]); 
    fd.append("action", 'apf_addpost'); 

    $('#form-container').hide(); 
    $('#processing').show(); 
    var postProject = $.ajax({ 
     type: 'POST', 
     url: apfajax.ajaxurl, 
     data: fd, 
     processData: false, 
     contentType: false, 
    }); 

    postProject.done(function(data, textStatus, XMLHttpRequest) { 
      $('#processing').hide(); 
      $('#apf-response').show(); 
      var id = '#success'; 
      jQuery(id).html(''); 
      jQuery(id).append(data); 
      resetvalues($('#msform')); 
    }); 

    postProject.fail(function(MLHttpRequest, textStatus, errorThrown) { 
      alert(errorThrown); 
    }); 
} 

它的工作!

+0

嘗試把$( 「#處理」)顯示()。在ajax請求開始之前。 –

+0

@DharaParmar不幸的是,它不能在 – XiLab

+1

之前把這個工作放在一邊。你能夠確認在AJAX調用時成功處理程序被觸發嗎?另外,如果你使用'.done()'和'.fail()'作爲承諾,而不是使用嵌套的'success'或'error'處理程序,它實際上更容易被鏈接到你的AJAX對象。 – Terry

回答

-1

如果添加loader在表單標籤將正常工作

<form id="msform"> 
    <fieldset> 
    <!-- some fields --> 
    <input type="submit" Value="submit"> 
    </fieldset> 

    <div id="processing" class="row" style="display:none"></div> 
    <div id="apf-response" class="row" style="display:none"></div> 
</form> 
+0

它不工作,因爲我隱藏整個表單,你可以看到我的代碼。 – XiLab