如果动态字段为空,则阻止表单提交.... Php / Jquery / Ajax [英] Prevent Form Submission if dynamic field is blank....Php / Jquery / Ajax

查看:181
本文介绍了如果动态字段为空,则阻止表单提交.... Php / Jquery / Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友我需要你的帮助,



如下图所示,我在下拉列表中动态加载问题选择框和问题答案选项从mysql数据库基于资产标题值。 (这是正常的)



但是我的主要问题是我希望用户选择所有问题的答案,然后只运行ajax函数并将数据库插入到mysql中。



注意:有些资产有1个问题,有的有3个,有些资产有问题,这就是为什么我没有使用下面的代码。 / p>

if(assettitle&& &customquestion1&&" customquestion2){
ajax etc *** [如果我使用这个代码,将面临无任何问题的资产问题。]



解决方案

您可以将一个计数器添加到资产的一些数据中,并在AJAX之前一次验证。 on('change',function(){
$($)$ $ $ $ $ $ $ $ $ $这个).data(selecteds,$(this).find('option')。length);
});

function checkAssets(){
$('。assets-selected')。each(function(){
if(typeof $(this).data('selecteds' )== undefined || $(this).data('selecteds')< 1){
return false;
} else {
return true;
}
});
}

if(checkAssets()){
//将表单提交给服务器
$ .ajax({
url:'../ page / php_action / addnewlead / creatlead.php',
type:'POST',
data:form.serialize(),
dataType:'json',
success:function (响应){


//删除错误
$(。form-group)。removeClass('has-error')。removeClass('has-successful ');

if(response.success == true){
$(。messages)。html('< div class =alert alert-success alert-dismissible role =alert>'+
'< button type =buttonclass =closedata-dismiss =alertaria-label =Close>< span aria-hidden = true>& times;< / span>< / button>'+
'< strong>< span class =glyphicon glyphicon-ok-sig n>< / span>< / strong>'+ response.messages +
'< / div>');

//重置窗体
$(#newleadform)[0] .reset();
// 7秒后重新加载页面
setInterval(function(){
location.reload(null,false);
},7000);

} else {
$(。messages)。html('< div class =alert alert-warning alert-dismissiblerole =alert>'+
'< button type =buttonclass =closedata-dismiss =alertaria-label =Close>< span aria-hidden =true>& times;< ; / span>< / button>'+
'< strong>< span class =glyphicon glyphicon-exclamation-sign>< / span>< / strong>'+ response.messages +
'< / div>');
} // / else
} // success
}); // ajax subit
} ///如果

提取资产问题&从数据库(PHP)的答案 - 把我在我的例子中显示的类



看你正在调用所有问题一次。在这之前做一个检查,以避免错误和其他问题

 <?php 
//load_data.php
$ connect = mysqli_connect(localhost,root,,test);
$ output ='';
if(isset($ _ POST [assetid]))
{

if($ _ POST [assetid]!='')
{
$ sql =SELECT * FROM customquestions WHERE assetid ='。$ _ POST [assetid]。';

}
else
{
$ sql =SELECT * FROM customquestions WHERE assetid ='akash';

}
$ result = mysqli_query($ connect,$ sql);
$ quesno = 1;

while($ row = mysqli_fetch_array($ result))
{
//可怜的丑陋的方式来做某事来过滤,最好的解决方案是问题有一个表1到N,其中1表被覆盖,主要信息和N的问题,所以你的数组中的每个索引将只填充数据库已存储的问题,否则将不会产生任何东西,您可以更好地验证前端,除了提供更多可扩展性。
if($ row ['colqa1'] ==''&& $ row ['colqa2'] ==''&& $ row ['colqa3'] ==''&& ; $ row ['colqa4'] ==''&& $ row ['colqa5'] ==''&& $ row ['colqa5'] ==''&& $ row [' colqa6'] ==''&& $ row ['colqa7'] ==''&& $ row ['colqa8'] ==''&& $ row ['colqa9'] == ''&& $ row ['colqa10'] ==''){
continue;
//如果没有问题,请不要显示下拉列表
}
$ output。='< div class =col-sm-6>';
$ output。='< div class =form-group>';
$ output。='< label for =campaignname>'。$ row [cqname]。'< / label>';
$ output。='< select name =cq'。$ quesno。'size =5class =form-control assets-selectedrequired>';
// $ output。='< div style =border:1px solid #ccc; padding:20px; margin-bottom:20px;>'$ row [product_name]。 / DIV>';
// $ output。='< tr>< td>'。$ row [cqname]。'< br>< / td>
$ output。='< option value =required>选择自定义问题答案< / option>
< option value ='。$ row [cqa1]。'>'。$ row [cqa1]。'< / option>
< option value ='。$ row [cqa2]。'>'。$ row [cqa2]。'< / option>
< option value ='。$ row [cqa3]。'>'。$ row [cqa3]。'< / option>
< option value ='。$ row [cqa4]。'>'。$ row [cqa4]。'< / option>
< option value ='。$ row [cqa5]。'>'。$ row [cqa5]。'< / option>
< option value ='。$ row [cqa6]。'>'。$ row [cqa6]。'< / option>
< option value ='。$ row [cqa7]。'>'。$ row [cqa7]。'< / option>
< option value ='。$ row [cqa8]。'>'。$ row [cqa8]。'< / option>
< option value ='。$ row [cqa9]。'>'。$ row [cqa9]。'< / option>
< option value ='。$ row [cqa10]。'>'。$ row [cqa10]。'< / option>
< / select>';
// $ output。='< tr>< td colspan =10>< hr>< / td>< / tr>
$ output。='< / div>< / div>< / div>';
$ quesno ++;
}
echo $ output;
}
?>


Hello friends i need your help,

As you can see in the below image i'm dynamically loading questions select box and questions answer options in drop-down list from mysql database based on asset title value. ( this is working fine )

But my main problem is i want user to select all question answers and then only run ajax function and insert database in mysql.

NOTE : Some assets have 1 question some have 3 and some assets have No questions thats why i didnt used below code.

if(assettitle && customquestion1 && customquestion2){ ajax etc*** [If i use this code then i'll be facing problem on assets who dont have any question.]

解决方案

You can add a counter into some data-attr on the assets and validate that before AJAX in one shot.

$('.assets-selected').on('change', function(){
   $(this).data( "selecteds", $(this).find('option').length);
});

function checkAssets(){
   $('.assets-selected').each(function(){
       if (typeof $(this).data('selecteds') == undefined ||  $(this).data('selecteds') < 1) {
            return false;
       } else {
            return true;
       }
   });
}

if(checkAssets()) {
            //submit the form to server
            $.ajax({
                url : '../pages/php_action/addnewlead/creatlead.php',
                type : 'POST',
                data : form.serialize(),
                dataType : 'json',
                success:function(response) {


                    // remove the error 
                    $(".form-group").removeClass('has-error').removeClass('has-success');

                    if(response.success == true) {
                        $(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                          '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                        '</div>');

                        // reset the form
                        $("#newleadform")[0].reset();
                        // reload page after 7 sec.
                        setInterval(function () {
                        location.reload(null, false);
                        }, 7000);

                    } else {
                        $(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                          '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                        '</div>');
                    }  // /else
                } // success  
            }); // ajax subit               
        } /// if

Fetch Assets Questions & Ans from database (PHP) - Put the class I showed in my example

Look you're calling all questions once. Do a checking before do that to avoid errors and other problems

<?php  
 //load_data.php  
 $connect = mysqli_connect("localhost", "root", "", "test");  
 $output = '';
 if(isset($_POST["assetid"]))  
 {  

  if($_POST["assetid"] != '')
  {  
       $sql = "SELECT * FROM customquestions WHERE assetid = '".$_POST["assetid"]."'";

  }  
  else
  {  
       $sql = "SELECT * FROM customquestions WHERE assetid = 'akash'";

  }
  $result = mysqli_query($connect, $sql);
  $quesno = 1;

  while($row = mysqli_fetch_array($result))  
  {  
      //poor and ugly way to do something to filter, the best solution is the questions have a table 1 to N, where the 1 table is cover, main information and the N the questions, so each index from your array will be filled only with the questions that db has stored else will bring nothing and you can validate better the frontend, besides provides more scalability.
        if ($row['colqa1'] == '' && $row['colqa2'] == '' && $row['colqa3'] == '' && $row['colqa4'] == '' && $row['colqa5'] == '' && $row['colqa5'] == '' && $row['colqa6'] == '' && $row['colqa7'] == '' && $row['colqa8'] == '' && $row['colqa9'] == '' && $row['colqa10'] == ''){
             continue;
            //don't show dropdown if you don't have questions!  
       }
       $output .= '<div class="col-sm-6">';
       $output .= '<div class="form-group">';
       $output .= '<label for="campaignname">'.$row["cqname"].'</label>';
       $output .= '<select name="cq'.$quesno.'" size="5" class="form-control assets-selected" required>';
       // $output .= '<div style="border:1px solid #ccc; padding:20px; margin-bottom:20px;">'.$row["product_name"].'</div>';
       // $output .= '<tr><td>'.$row["cqname"].'<br></td>';
       $output .= '<option value="" required>Select Custom Question Answer</option>
                   <option value="'.$row["cqa1"].'">'.$row["cqa1"].'</option>
                   <option value="'.$row["cqa2"].'">'.$row["cqa2"].'</option>
                    <option value="'.$row["cqa3"].'">'.$row["cqa3"].'</option>
                    <option value="'.$row["cqa4"].'">'.$row["cqa4"].'</option>
                    <option value="'.$row["cqa5"].'">'.$row["cqa5"].'</option>
                    <option value="'.$row["cqa6"].'">'.$row["cqa6"].'</option>
                    <option value="'.$row["cqa7"].'">'.$row["cqa7"].'</option>
                    <option value="'.$row["cqa8"].'">'.$row["cqa8"].'</option>
                    <option value="'.$row["cqa9"].'">'.$row["cqa9"].'</option>
                    <option value="'.$row["cqa10"].'">'.$row["cqa10"].'</option>
                   </select>';
       // $output .= '<tr><td colspan="10"><hr></td></tr>';
       $output .= '</div></div></div>';
       $quesno++;
  }  
  echo $output;
 }  
 ?>

这篇关于如果动态字段为空,则阻止表单提交.... Php / Jquery / Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆