tags:

views:

73

answers:

2

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));

?>
+1  A: 

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.

Anthony Forloney
A: 

There is one line that looks weird:

$("img").removeClass('thumb').addClass('thumbV');

means that you remove the class thumb and add class thumbV to all tags, making them visible. Basically meaning that one of them has class="thumbNV thumbV" and the other has class="thumbV"

Unless you intend to use the classes for something else I recommend simply doing

img.thumb { display: none; height:20px; width:20px; }

and then simply use jQuery's $('#up').hide() and $('#down').show() methods.

kb
this line:$("#down").removeClass('thumb').addClass('thumbNV');is supposed to be$("#down").removeClass('thumb').addClass('thumbV');I'm using the classes to basically show an image or hide it. the .thumb class has visibility:hidden; and the .thumbV class has visibility:visible;I didn't even think to use the jquery functions .hide() and .show().Is there one way that is better or is it just personal preference?
Catfish