2015-12-02 87 views
-2

我使用下面的代碼將一些數據從表單發送到帶有AJAX的PHP腳本。我需要一個快速的答案,我沒有時間,我需要一個非常快速和直接的方式,不要發送數據,如果輸入的form =「」,這意味着如果用戶只需點擊保存在一個空白表格。如何避免提交沒有價值的表單?

<script type="text/javascript"> 
$("document").ready(function(){ 
    $(".ajaxcourse1").submit(function(){ 
    var data = { 
     "action": "test" 
    }; 
    data = $(this).serialize() + "&" + $.param(data); 
    $.ajax({ 
     type: "POST", 
     dataType: "json", 
     url: "course1.php", 
     data: data, 
     success: function(data) { 
     $("#editcourse1").html(
      data["course1"] 
     ); 


    } 
}); 
return false; 
}); 
}); 
</script> 
+0

你試過'if(data){/ * ajax * /} else {/ * notice user * /}'??你應該知道所有輸入的屬性['required'](http://www.w3schools.com/tags/att_input_required.asp)。 –

+2

首先,你可以使用你需要的html表單到一些字段。

+0

var serialized = $(yourform).serialize(); if(serialized.indexOf('=&')> -1 || serialized.substr(serialized.length - 1)=='='){ //你有空值 } – Snm

回答

0
if ($('#whateveryourinputidis').val()) { 
    // send data 
    $.ajax(parameters); 
} else { 
    // don't send data, perhaps alert 
} 
0

我假設你通過點擊一個按鈕提交表單,在這種情況下,你需要表單提交前檢查值,並防止它是否有空白字段:

<input type="submit" value="Login" /> 

$(':submit').click(function(e) { 
    if ($("#some_field").val().length == 0) { 
        e.preventDefault(); 
    }else{ 
     //ajax call 
    } 
}); 
+0

有沒有在移動設備上使用所需的簡單方法?它適用於個人電腦,但在手機上有問題 – Nockingam

+0

如果您使用的是html5,您可以使用必填字段: thepiyush13

+1

需要在手機上無法使用!雖然是的,但我使用html5 – Nockingam

0

可以試試這個

var error = false; 
$(this).find('input').each(function(key, value){ //this -> your form 
    if(!value) 
     error = true; 
}); 
if(error) 
    alert('Input data missing baby !!'); // or your logic 
0

你也可以試試這個

$(".ajaxcourse1").submit(function(e){ 
    var data = { 
     "action": "test" 
    }; 

    var flag = true; 
    // validate your inputs here, 
    // this is just a sample validation 

    $(this).find("input").each(function (i, row){ 
     if($(row).val() == ""){ 
      flag = false; 
     } 
    }); 

    if(flag === false){ 
     return false; // to cancel the form submit 
    }else{ 

     data = $(this).serialize() + "&" + $.param(data); 
     $.ajax({ 
     type: "POST", 
     dataType: "json", 
     url: "/course1.php", 
     data: data, 
     success: function(data) { 
      $("#editcourse1").html(
      data["course1"] 
     ); 
     }, 
     error: function (data) { 
      console.warn(data); 
     }, 
     complete: function() { 
      console.log('request has been completed, either it succeeded or it failed.) 
     } 
     }); 
    } 
+0

夥計們所有的代碼片段在提交時不發送字體的部分工作,但是成功部分永遠不會到達,因此表單不會在空時不被提交!你可以發佈一個完整的代碼工作?謝謝 – Nockingam

0

您可以在提交表單時自己檢查值,如果所有值都不正確,可以中止提交。但爲了解決這個問題,也給你更多的靈活性,你可以使用jquery validation plugin

1

您需要先驗證表單。您是否使用驗證庫如Parsley或者通過檢查表單中的字段是否爲空/無效手動執行。

$(".ajaxcourse1").submit(function(){ 
    var form_validates = $('.ajaxcourse1').parsley().isValid(); 

    if(!form_validates) { return false } // this will stop the form from sending your ajax call. 

    ... your code ... 
} 
相關問題