dongyanling9248 2010-01-30 21:15
浏览 59
已采纳

使用Ajax和PHP进行表单验证 - 从PHP返回一个变量以在javascript函数中使用

I'm using Ajax via jQuery for the first time ever. I have an html input and when a user clicks it and types something and then the focus blurs, i'm using jquery to call a php script to validate the user's input.

I'm trying to figure out how to take the variable in PHP and compare it in jQuery. Please give me any advise

Right now when the focus blurs, both of the images are visible.

Thanks in advance!

The html:

<label for="FirstName">First Name</label>
     <input type="text" name="FirstName" title="First Name Here" id="firstName" />
     <img class="thumb" id="up" src="Images/thumbs_up_48.png" />
     <img class="thumb" id="down" src="Images/thumbs_down_48.png" />

The CSS

img.thumb {
 visibility:hidden;
 height:0;
 width:0;
}
img.thumbV {
 visibility:visible;
 height:20px;
 width:20px;
 float:right;
}img.thumbNV {
 visibility:visible;
 height:20px;
 width:20px;
 float:right;
}

The jquery:

$(document).ready(function() {
 //my attempt at ajax using jQuery
 $("#firstName").change(function() {
  sendValue($(this).val());
  $("img").removeClass('thumb').addClass('thumbV');
 });


 function sendValue(str) {
 $.post("ajax.php", {sendValue: str}, 
 function(data) {
  if(data.returnValue === true) {
   $("#up").removeClass('thumb').addClass('thumbV');
  }
  else {
   $("#down").removeClass('thumb').addClass('thumbNV');
  }
  //$("#ajax").html(data.returnValue);
 }, "json");
}

});

and the PHP:

<?php 

$choice = false;

if(isset($_POST['sendValue'])) {
 $value = $_POST['sendValue'];
 if(preg_match('/^[a-zA-Z]$/', $value)) {
  $choice = true;
 }

}

echo json_encode(array("returnValue"=>$choice));

?>
  • 写回答

2条回答 默认 最新

  • dongshanxiao7328 2010-01-30 21:41
    关注

    I would keep what you have right now.

    At this time, I cannot see if there is a better way, but what you have now looks fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?