javascript - validation false but the form is still submitted -


i want validate whether number inputted user exist in database have action return json object , check input before post server. problem return false.

javascript:

<script type="text/javascript">         var pid = $("#productid").val();         var flag = false;          $("#button1").click(function () {             $.get('/invoice/getdata',                 function (data) {                     (var = 0; < data.length; i++) {                         if (data[i] == pid) {                             flag = true;                         }                     }                 });             if (flag == false) {                 alert("invalid product id");                 location.reload();                 return false;             }             else {                 alert("validations passed");                 return true;             }         }); </script> 

form (asp.net mvc4)

@using (html.beginform("addinvoicedetails","invoice",formmethod.post)) {     @html.validationsummary(true)      <fieldset>         <legend>invoice_detail</legend>          <div class="editor-label">             @html.labelfor(model => model.invoiceid)         </div>         <div class="editor-field">             @html.textbox("invoiceid", (string)viewbag.invoiceid,new { @readonly="readonly" })         </div>          <div class="editor-label">             @html.labelfor(model => model.productid)         </div>         <div class="editor-field">             @html.editorfor(model=>model.productid)             @html.validationmessagefor(model => model.productid)         </div>          <div class="editor-label">             @html.labelfor(model => model.quantity)         </div>         <div class="editor-field">             @html.editorfor(model => model.quantity)             @html.validationmessagefor(model => model.quantity)         </div>          <p>             <input id="button1" type="submit" value="create" />         </p>     </fieldset> }  

you using ajax asynchronous, if statements executed before $.get() done executing. this:

    $("#button1").click(function (event) {           $.get('/invoice/getdata',             function (data) {                 (var = 0; < data.length; i++) {                     if (data[i] == pid) {                         flag = true;                     }                 }                 if (flag == false) {                     alert("invalid product id");                     location.reload();                     event.preventdefault(); //prevents post server                 }                 else {                     alert("validations passed");                                 }         });  }); 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -