开发者

How declare a javascript variable and assign the value to a php file which returns a boolean value

For context: I am busy using javascript for checking fields in a form. The problem is to work around being unable to retrieve data from the database. All the checks except for making sure its a unique(not used in db) username are done. I looked around quite a while on the web, but the only answer that came close was this: "until you start needing the php page in question to return a value of some sort. in that case, just use the YUI connection manager or something of that nature". Since php is server side, when the button is clicked, can the php then be called, as there is no point in processing the php until there is text in the username field.

Here is what I have done. When pressing the submit button, a js function is called. The checking works.

<script type="text/javascript" src="regform_checks.js"></script>    

<h1>Welcome to Registration</h1>


<form name="register" action="add_user.php" onsubmit="return validateForm()" method="post">

<table>

<tr>

    <td>Choose a username*</td>

    <td><input type = "text" name="profile_id"/></td>

</tr>

This above is in my registration.php The below is my .js file:

function validateForm()

 {

 var username=document.forms["register"]["profile_id"].value;

 var pw1=document.forms["register"]["profile_password"].value;

 var pw2=document.forms["register"]["profile_password2"].value;

 var invalid = " "; // Invalid character is a space

 var minLength2 = 3; // Minimum username length

 var minLength = 6; // Minimum password length

 var x=document.forms["register"]["profile_email"].value;

 var atpos=x.indexOf("@");

 var dotpos=x.lastIndexOf(".");


 //check for a value in username field

 if (username==null || username=="")

   {

   alert("Please enter a username");

   return false;

     }



 // check for username minimum length

 if (document.register.profile_id.value.length < minLength2) 

  {

  alert('Your username must be at least ' + minLength2 + ' characters long.');

  return false;

  }



 // check for a value in both fields.

 if (pw1 == "" || pw2 == "") 

  {

  alert("Please enter your password in the Password and Re-enter password areas.");

  return false;

  }



 // check for password minimum length

 if (document.register.profile_password.value.length < minLength) 

  {

  alert('Your password must be at least ' + minLength + ' characters long. Try again.');

  return false;

  }



 // check for password consistency

    if (pw1 != pw2) 

  {

  alert ("The passwords you have entered are not the same. Please re-enter your password.");

  return false;

  }



 //check for valid email address

 if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)

   {

   alert("Not a valid e-mail address");

   return false;

     }



 // check for spaces

 if (document.register.profile_id.value.indexOf(invalid) > -1) 

  {

  alert("Sorry, spaces are not allowed in your username.");

  return false;

  }

 else if (document.register.profile_password.value.indexOf(invalid) > -1)

  {

  alert("Sorry, spaces are not allowed in your password.");

  return false;

  }

 else if (document.register.profile_email.value.indexOf(invalid) > -1)

  {

  alert("Sorry, spaces are not allowed in your email.");

  return false;

      }

 else 

  {

   return true;

  }    



}

What I have been unable to do: set a js variable as follows: var username_check=profile_id_check.php; This file looks like this:

$query = "select profile_id from profile";

$result = mssql_query($query);

$names = array();

for ($count=0; $row=@mssql_fetch_array($result); $count++)

    $names[$count]=$row;


$idtest= True;

foreach ($names as $name)

{

if($name[profile_id]==$profile_id)

return false;
print "$name[profile_id]";

}

?>

The php code is still in progress of making, depending on what it needs done I realize I dont need the $idtest, as the if statement returns a boolean value. That last print statement just prints all the profile names(so I can be sure the code works, and it does). And its the profile name entered into the form that needs to be compared with all the profile names in the database to ensure it is unique. The endresult the way I see it: If username is unique, give no error or warning, if it isnt, the js must then... which I kn开发者_Python百科ow how to code. Im open to suggestions that turns away from this method, though my knowledge is restricted to php, some js. (and obviously html) Thanks in advance.


I think you need to get a grasp of certain concepts on how to pass data back and forth between the client and server. You cannot call a php file on the client side by doing var username_check=profile_id_check.php;.

Data can be passed to the server via request methods. The most common of which are $_POST and $_GET. Have a look at the attributes on your form tag below

<form name="register" action="add_user.php" onsubmit="return validateForm()" method="post">

The action is set to add_user.php and your method is set to post. So, you can access the form elements with a name attribute on the server side using the $_POST array. So as an example in your add_user.php you can access the profile_id in the following way.

$profile_id = $_POST['profile_id']; 

Other ways you can send data back to the server is by ajax but i would suggest getting the basics down of submitting data via regular HTTP requests then move onto ajax later on.


You should make an ajax request to the specific php file and register a callback function that handles the php output and sets your variable.
So something like

/* code block #1 */
var username_check=profile_id_check.php;
/* code block #2 */

would be translated into something like :

/* code block #1 */
var username_check;
ajaxCall({
    url : 'profile_id_check.php',
    callback : function(response){
        username_check = response;
        /* code block #2 */
    }
});


I'm not 100% sure what you're asking, as there seems to be a bit of a language barrier issue, but it looks like you're asking how to have your JavaScript interact with your PHP.

PHP is server-side. What's more is that PHP doesn't run as a process (usually...) on the server, so when you run a script, it's a one-shot deal. This ultimately means that by the time your PHP script renders output to the screen, the script itself has finished running. It is not sitting there awaiting input like, say, a console program.

Because of this, you need to use AJAX in order to access your PHP script. What is AJAX? Simply put, it's a way for JavaScript to send HTTP requests to a server-side script, receive the results of those requests, and then dynamically use the DOM (Document Object Model - your HTML) to display those results.

The simplest way to use AJAX is to use jQuery's ridiculously elegant AJAX functions:

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.post/

One final thought: Form validation with JavaScript is not a security measure. Make sure you have validation in your PHP script as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜