0

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
        }
    }
}
4
  • just return the error message from the server and alert it in the success function Commented Apr 9, 2013 at 7:19
  • @Sabari please post it as an answer with few code as reference Commented Apr 9, 2013 at 7:22
  • Just offtopic. But escape this query $result12=mysql_query("SELECT * FROM budget where creater_id = '$sid'"); at least with mysql_real_escape_string() Commented Apr 9, 2013 at 7:24
  • @user2180861 Done. Please check Commented Apr 9, 2013 at 7:25

6 Answers 6

1

Change

if($val == 'Y') //Returns TRUE
{
    //VALIDATION FAILS - Returns Validation Error
    break;
}
else  if($val == 'N') {
    //VALIDATION TRUE - Returns Validation Error
}

into

echo $val;

Then in your js simply grab response and do alert msg:

success: function(data){
    if (data == 'Y') {
        alert('Successfully  ...');
    } else {
        alert('Oh no...');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>

18 Comments

Above i shown you event focusout . And ,my textbox is getting input from calender(jquery calender opens when user focus on the textbox) . So according to my requirement which event of jquery is suitable for this?
@user2180861 I am not clear of what you mean. The event focusout you have used for the text box is correct for your requirement
I have a text-box , when i click on it. One j-query Calender is opening . so for this case i used focusout event. But focusout is not seems good . Can you suggest which event shall i use for this case??
@user2180861 Please check my update. Hope this is what you need
@user2180861 what is the response from the server. Use firebug to check for the ajax call
|
0

its easy use

 if($val == 'Y') //Returns TRUE
            {
                echo 'success';
            }
            else  if($val == 'N') {
                echo 'fail';
            }exit;

you will get this success/fail in the data param of your success call back.

Comments

0

Your php code will be

if($val == 'Y') //Returns TRUE
            {
              echo "Success";   
             //VALIDATION FAILS - Returns Validation Error
                break;
            }
            else  if($val == 'N') {
              echo "Fail";   
                //VALIDATION TRUE - Returns Validation Error
            }

And In JS

$.ajax({
                           url: "ajax_frmdate_validation.php?txtval="+$(this).val(),
                           success: function(data){
                                      if(data == "Success")
                                        alert("success");
                                      if(data == "Fail")
                                        alert("Fail");

                           }
                         });

Comments

0

Until and unless you set the HTTP Response as an error code , ajax will not callback to fail: function.

An easy way to do is , send a JSON string back from the server side even if validation fails or is a success as shown in the format below.

If validation is a success

 {'status':'OK','message':'Validation success'}

If validation is a failure

{'status':'NOK','message':'Please enter your name'}

Now you can get this JSON string in the success callback and take appropriate action.

Comments

0

you can use ajax type and data option to send the data instead of passing it through url.

 $.ajax({
           url: "ajax_frmdate_validation.php",
           type:'GET',
           data:{"txtval":$(this).val()},
           success: function(data){
                 if(data=="success"){
                   alert('successful');
                 }else{
                    alert('error');
                 }
            }
         });

and you serverside code include this

  if($val == 'Y') //Returns TRUE
        {
           echo "success"
            break;
        }
        else  if($val == 'N') {
             echo "error";
             break;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.