doumi9661 2013-04-09 07:16
浏览 49
已采纳

php:如何使用jquery ajax验证文本框

I have a textbox, i would like to validate it using jquery-ajax once user focusout from that textbox.

Validation include:

  • Server side, value goes to the php page and i have to validate it

  • if validation success,show alert("succes"); else if error alert("failed");

I have doubt how jquery ajax will show alert("failure"); Till now , i have only done for success.

I know only the below mention code,furthure what should i do to solve my problem? please help

<script type="text/javascript">
    $(function()
    {
        $('input[id^="datepicker"]').on('focusout',function()
        { 
             $.ajax({
                url: "ajax_frmdate_validation.php?txtval="+$(this).val(),
                success: function(data){
                    alert('Successfully  ...');
                }
            });

        });
    });
</script>

--------------
--------------
<input class="plain" name="frmdate"   value="" size="25" id="datepicker" /> 

And my server side php code is:

$txtval =$_REQUEST['txtval'];
$fromTimestamp = strtotime( $txtval); 
//---------My Logic Code Goes Here -----------------------------
$sid=$_SESSION['id'];
$result12=mysql_query("SELECT * FROM budget where creater_id = '$sid'");
$num_rows = mysql_num_rows($result12);

if($num_rows>0)//check if empty or not
{
    while($test12 = mysql_fetch_array($result12)) {
        $from_date = strtotime($test12['from_date']);//getting all the FROM-Dates_column
        $to_date = strtotime($test12['to_date']);//getting all the TO-Dates_column

        if(isset($to_date) && isset($from_date)) {
            if((($fromTimestamp >= $from_date) && ($fromTimestamp <= $to_date)) || (($toTimestamp >= $from_date) && ($toTimestamp <= $to_date))) {
                $val = 'Y'; //return Y in meet this condition
            }
            else {
                $val = 'N'; // return N if meet this condition
            }
        }
        //---------------------Result of my logic code---------------------------------
        if($val == 'Y') //Returns TRUE
        {
            //VALIDATION FAILS - Returns Validation Error
            break;
        }
        else  if($val == 'N') {
            //VALIDATION TRUE - Returns Validation Error
        }
    }
}
  • 写回答

6条回答 默认 最新

  • dongyumiao5210 2013-04-09 07:23
    关注

    You can do this way:

    $txtval = mysql_real_escape_string($_REQUEST['txtval']);
    $fromTimestamp = strtotime( $txtval); 
     //---------My Logic Code Goes Here -----------------------------
     $sid=$_SESSION['id'];
     $result12=mysql_query("SELECT * FROM budget where creater_id = '$sid'");
     $num_rows = mysql_num_rows($result12);
    
     if($num_rows>0)//check if empty or not
     {
        while($test12 = mysql_fetch_array($result12)) {
        $from_date = strtotime($test12['from_date']);//getting all the FROM-Dates_column
        $to_date = strtotime($test12['to_date']);//getting all the TO-Dates_column
    
        if(isset($to_date) && isset($from_date)) {
             if((($fromTimestamp >= $from_date) && ($fromTimestamp <= $to_date)) || (($toTimestamp >= $from_date) && ($toTimestamp <= $to_date))) {
                 $val = 'Y'; //return Y in meet this condition
             }
             else {
                $val = 'N'; // return N if meet this condition
             }
         }
         //---------------------Result of my logic code---------------------------------
         if($val == 'Y') //Returns TRUE
         {
            echo "failed";
            exit();
         }
         else  if($val == 'N') 
         {
            echo "success";
            exit();
         }
    

    Now in your ajax call:

    <script type="text/javascript">
        $(function()
        {
           $('input[id^="datepicker"]').on('focusout',function()
           { 
             $.ajax({
                url: "ajax_frmdate_validation.php?txtval="+$(this).val(),
                success: function(data){
                   if (data == 'success') {
                        alert("Successfully validated"); 
                   } else {
                        alert("Failed");
                        return false;
                   }
                }
            });
    
          });
       });
    </script>
    

    Rather than alerting, a better way will be to show the error message below the textbox by appending the message if it is failed.

    Also do proper escaping before you do the checking using mysql_real_escape_string

    UPDATE :

    You need to call the ajax whenever the date changes in the input text field, so instead of focusout you can use onSelect from datepicker. So when a new date is selected an ajax call will be initiated.

    So instead of calling the earlier ajax on focusout you can call on onSelect of datepicker

    $(function(){
        $('#datepicker').datepicker({
            onSelect:function(date,instance){
               $.ajax({
                  url: "ajax_frmdate_validation.php?txtval="+date,
                  success: function(data){
                     if (data == 'success') {
                        alert("Successfully validated"); 
                     } else {
                        alert("Failed");
                        return false;
                     }
                  }
               });
            }
        });
    }); 
    

    NEW UPDATE

    Try with this :

     <script type="text/javascript">
         $(document).ready(function() { 
           $("#datepicker").datepicker({ 
              dateFormat: "yy-mm-dd" ,
              onSelect:function(date,instance){
                              $.ajax({
                                url: "ajax_frmdate_validation.php?txtval="+date,
                                success: function(data){
                                if (data == 'success') {
                                     alert("Successfully validated"); 
                                } else {
                                     alert("Failed");
                                      return false;
                                }
                         }
                     });
                }
         }); 
      }); 
     </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?