Jump to content

Communication between PHP and Javascript


HenryCan

Recommended Posts

I'm writing code to validate a form and I'd like to be able to set the position of the cursor to the field of my choice when I detect an error. I'm getting the strong impression that I have to use Javascript to set the position of the cursor via the focus() function. But how do I pass information from my PHP code to Javascript to tell it which field I want the focus on?

 

For example, let's say I've got a simple form contain Name, Email address, Subject and Message. I check for bad data in all of those fields and I want to put the cursor (or focus) on the first field that has an error. How does my PHP code tell Javascript that the first field in error is the Email Address or the Message or whatever? An example showing what happens in PHP and what happens in Javascript would be very handy if someone can point me to one or throw one together....

Output a small script that will run onload which sets the focus to the field.  Indicate the field through a PHP variable.  Eg

 

<?php
$fieldToFocus=null;
if (isset($_POST['submit'])){
   //do all your validation here
   //assign the ID of any problem field to $fieldToFocus
}
?>
<script type="text/javascript">
//This example uses jQuery.  Modify as necessary if you are using a different library (or no library).
$(function(){
   $(<?php echo json_encode('#'.$fieldToFocus); ?>).focus();
});
</script>

I'm not sure what JQuery is or even what you mean by a library in this context. How would the coding change if I was sticking strictly to Javascript and PHP?

 

I'm using a hosting server, not my own server, and I don't think they'll let me install something like JQuery....

jQuery is not something you install on the server.  It's a Javascript library that you just include using a <script> tag.  It helps remove cross-browser compatibility issues and make a bunch of stuff easier to do. 

 

http://jquery.com/

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.