Catfish
Catfish

Reputation: 19294

Form validation with Ajax and PHP - return a variable from PHP to use in javascript function

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

?>

Upvotes: 1

Views: 504

Answers (2)

kb.
kb.

Reputation: 2005

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.

Upvotes: 0

Anthony Forloney
Anthony Forloney

Reputation: 91806

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.

Upvotes: 1

Related Questions