Jump to content

Recommended Posts

Hi

I am new to AJAX and have a problem!

I have created a script (see below) that basically checks to see if the input fields are to a certain format and if they are display text saying that it is correct and if it doesnt text saying it is incorrect. I then want it to display a button if the input is all correct.

I have created the code however if the user then changes the information the button still appears (even though I could prevent them from adding the data to the database through PHP or Javascript) I want the button to then disappear when the input is incorrect.

Another problem I have encountered is that I can only seem to get the AJAX to work if I use the onblur in one of the input text fields, however if the user fills in the field first and then another field the AJAX wont be retrieved correctly, I have looked for some kind of timmed function but cannot seem to find anything.

Can anyone help?

 

Code:

register.php

<?php
session_start();
?>
<html>
<head>
<script type="text/javascript" language="javascript" src="ajaxrequestusernames.js"></script>
<script type="text/javascript" language="javascript" src="ajaxrequestpasswords.js"></script>
<script type="text/javascript" language="javascript" src="ajaxrequestemail.js"></script>
<script type="text/javascript" language="javascript" src="ajaxrequestallow.js"></script>
</head>
<body>
<!-- EXTERNAL PHP FILES -->
<?php 
$pagename = "Register";
include "banner.php";
include "headinfo.php";
?>
<!-- LEFT MENU TAG -->
<?php 
include "leftmenu.php"; 
echo '</div>';
?>
<!-- END OF LEFT MENU TAG -->
<!-- END OF EXTERNAL PHP FILES TAG -->
<?php 
echo "<div id='normal'>"; 
if($logged['username'] != ""){
echo '
<script type="text/javascript">
//window.location = "http://www.rasclerhys.com/lounge.php";
</script>';
}
?>


<?php
if($logged['usertype'] == "admin"){
echo '
<h1><center>Register</center></h1>
<form action="get">
Username: <div id="registercentre"><input type="text" name="username" id="username" onblur="javascript: AjaxRequest(\'main\',\'ajaxfile.php?username=\',\'username\');" maxlength="50" size="50" class="input1"></div><div id="main"></div><div id="help"><a href="#" onMouseover="fixedtooltip(\'Please Enter Your Username, this cannot be Changed Later!\', this, event, \'200px\')" onMouseout="delayhidetip()">[?]</a>

Password: <div id="registercentre"><input type="text" name="password" id="password" onblur="javascript: MyAjaxRequest(\'main2\',\'ajaxfile.php?passwordcon=\',\'passwordcon\',\'password\')" maxlength= "50" size="50" class="input1"></div><div id="help"><a href="#" onMouseover="fixedtooltip(\'Please Enter Your Password. This can be changed later.\', this, event, \'200px\')" onMouseout="delayhidetip()">[?]</a></div><br/>

Confirm Password: <div id="registercentre"><input type="text" name="passwordcon" id="passwordcon" onblur="javascript: MyAjaxRequest(\'main2\',\'ajaxfile.php?passwordcon=\',\'passwordcon\',\'password\')" maxlength= "50" size="50" class="input1"></div><div id="main2"></div><div id="help"><a href="#" onMouseover="fixedtooltip(\'Please Re-Enter Your Password. This can be changed later.\', this, event, \'200px\')" onMouseout="delayhidetip()">[?]</a></div><br/>

Email Address: <div id="registercentre"><input type="text" name="emailaddress" maxlength="50" id="emailaddress" onblur="javascript: EmailAjaxRequest(\'main3\',\'ajaxfile.php?email=\',\'emailaddress\'); AllowAjaxRequest(\'main4\',\'ajaxfile.php?check=\',\'passwordcon\',\'password\',\'username\',\'emailaddress\');"  size="50" class="input1"></div><div id="main3"></div><div id="help"><a href="#" onMouseover="fixedtooltip(\'Please Enter Your Email Address this must be a valid address, This Will Not Be Shown Unless Selected, For More Info Please Read Our Privacy Statement.\', this, event, \'200px\')" onMouseout="delayhidetip()">[?]</a></div><br/><br/>
<div id="main4"></div>
';

echo '</div>';
}
else{
echo "This page is currently under construction";
}
?> 



</div>
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />

<?php include "footer.php"; ?>
</body>
</html>

(the ajaxrequestusername.js file isnt necessary as it works)

ajaxrequestallow.js

function AllowAjaxRequest(target_div,file,check_div,check_div2,check_div3,check_div4)
{
var MyHttpRequest = false;
var MyHttpLoading = '<p>Loading...</p>'; // or use an animated gif instead: var MyHttpLoading = '<img src="loading.gif" border="0" alt="running" />';
var ErrorMSG = 'Unfortunately, you browser does not currently suppoer XMLHTTP';

if(check_div != ""){
var check_value = document.getElementById(check_div).value;
}
else{
var check_value = '';
}
if(check_div2 != ""){
var check_value2 = document.getElementById(check_div2).value;
}
else{
var check_value2 = ''
}
if(check_div3 != ""){
var check_value3 = document.getElementById(check_div3).value;
}
else{
var check_value3 = ''
}
if(check_div4 != ""){
var check_value4 = document.getElementById(check_div4).value;
}
else{
var check_value4 = ''
}

if(window.XMLHttpRequest){ // client using Non Microsoft product
try{
MyHttpRequest = new XMLHttpRequest();
}catch(e){
MyHttpRequest = false;
}}
else if(window.ActiveXObject){ // client is using Internet Explorer
try{
MyHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
MyHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
MyHttpRequest = false;
}}}
else{
MyHttpRequest = false;
}

if(MyHttpRequest){ 
var random = Math.random() * Date.parse(new Date()); // make a random string to prevent caching

var file_array = file.split('.'); // prepare to check if we have a query string or a html/htm file
if(file_array[1] == 'php') // no query string, just calling a php file
{
  var query_string = '?rand=' + random;
}
else if(file_array[1] == 'htm' || file_array[1] == 'html') // calling a htm or html file
{
  var query_string = '';
}
else // we have presumable a php file with a query string attached
{
var query_string = check_value + '&cpassword=' + check_value2 + '&cusername=' + check_value3 + '&cemail=' + check_value4 + '&rand=' + random;
}


MyHttpRequest.open("get", url_encode(file + query_string), true); // <-- run the httprequest using GET


// handle the httprequest
MyHttpRequest.onreadystatechange = function ()
{
if(MyHttpRequest.readyState == 4) // done and responded
{
document.getElementById(target_div).innerHTML = MyHttpRequest.responseText;
}
else
{
document.getElementById(target_div).innerHTML = MyHttpLoading; // still working
}
}
MyHttpRequest.send(null);
}
else 
{
document.getElementById(target_div).innerHTML = ErrorMSG; 
}
}

function url_encode(string)
{
var string;
var safechars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/-_.&?=";
var hex = "0123456789ABCDEF";
var encoded_string = "";
for(var i = 0; i < string.length; i++)
{
var character = string.charAt(i);
if(character == " ")
{
encoded_string += "+";
}
else if(safechars.indexOf(character) != -1)
{
encoded_string += character;
}
else
{
var hexchar = character.charCodeAt(0);
if(hexchar > 255)
{
encoded_string += "+";
}
else
{
encoded_string += "%";
encoded_string += hex.charAt((hexchar >> 4) & 0xF);
encoded_string += hex.charAt(hexchar & 0xF);
}
}
}
return encoded_string;
}

ajaxfile.php

<?php
//HOW IT WORKS IS THAT WE DISPLAY THE CODE OF PHP WE WANT TO OCCUR HERE AND THEN IT DISPLAYS THROUGH A SORT OF IFRAME WITH AJAX ONTO THE PAGE. THIS CODE CHECKS TO SEE IF A USERNAME IS IN A DATABASE AND THEN RETURN IF IT IS.
if(!empty($_GET['username'])){
include "headinfo.php";
$connect = mysql_connect("localhost","b25rasc_b25rasc","rasclewelsh");  
mysql_select_db(b25rasc_userlogin) or die(mysql_error());  
$name = $_GET['username'];

$name = mysql_real_escape_string($name);
$query = mysql_query("SELECT * FROM members WHERE username = '$name'");
$query = mysql_num_rows($query);
if($query == 0){
echo '<font color="green"><img src="http://www.rasclerhys.com/webimages/tick.gif" alt="Username is Available">Username is Available</font>';
}else{
echo '<font color="red"><img src="http://www.rasclerhys.com/webimages/delete.png" alt="Username is Unavailable">Username is Unavailable</font>';
}
}


if(!empty($_GET['passwordcon'])){
if($_GET['password'] == $_GET['passwordcon']){
echo '<font color="green">Passwords Match</font>';

}else{
echo '<font color="red">Passwords Do Not Match</font>';
}
}

if(!empty($_GET['email'])){
$email = $_GET['email'];
if(preg_match("/@/",$email) && preg_match("/.c/",$email) && strlen($email)>5){
echo '<font color="green">Email Address is Valid</font>';
}else{
echo '<font color="red">Email Address is Invalid</font>';
}
}

if(!empty($_GET['check'])){
$ccpassword= $_GET['check'];
$cpassword = $_GET['cpassword'];
$cusername = $_GET['cusername'];
$cemail = $_GET['cemail'];
if(!empty($ccpassword) && !empty($cpassword)&& !empty($cusername) && !empty($cemail)){
if($ccpassword == $cpassword){
echo '<input type="submit" value="Register" class="input1"/>';
}
}else{
echo '<font color="red">There are errors. Please fill in all forms correctly.</font><br/><input type="submit" value="Register" id="submit" disabled="true">';
}}


?>

 

Thanks

Rhys

Link to comment
https://forums.phpfreaks.com/topic/227464-simple-ajax-problem/
Share on other sites

I've done similar stuff using jQuery.  If you're new to AJAX (like I am) take the time to learn jQuery now.  It'll dramatically speed up what you're doing/learning.

 

Anywhoo, code takes a "Customer Type" selection list, and if "other" is selected, it displays an additional input box for me to type in the customer type:

$(document).ready(function(){
$('#custtypeother').hide();
$('#custtypedesc_row').hide();
$('#custtype').click(function(){
	if($("#custtype").val()=='other')
	{
		//alert("Entering if with"+$('#custtype').val());
		$('#custtypeother').show();
		$('#custtypedesc_row').show();
	}
	else
	{
		$('#custtypeother').hide();
		$('#custtypedesc_row').hide();
		if($('#custtypeother').is("visible"))
		{
			$('#custtypeother').hide();
			$('custtypedesc_row').hide();
		}
	}
});
});//end of document ready

 

This code (from the same page) checks the business code being assigned to the new customer.  With each letter typed, it queries the database and ensures the typed indentifier isn't already in use.  It also checks to ensure that the code isn't longer than 6 characters so it doesn't get truncated when inserted into the database.  It also hides the submit button until this business code passes both tests.

 

$(document).ready(function(){ 
$("#buscodeerror").hide();
$("#buscodecounterror").hide();
$("#buscode").keyup(function(e){ 
        //e.preventDefault();
        //alert("A key was pressed!"); 
        ajax_search(); 
        count();
        
    }); 


});//end of document.ready

function ajax_search(){ 
// $("#search_results").show(); 
  var search_val=$("#buscode").val(); 
  $.post("./ajax/findbuscode.php", {buscode : search_val}, function(data){
if (data.length>0){ 
	//alert("Data is: "+data);
	$("#submit").hide();
	$("#buscodecheck").hide();
	$("#buscodeerror").show(); 
}
else
{
	$("#buscodeerror").hide();
	$("#sumbit").show();
	$("#buscodecheck").show();	
} 
  })
}

function count(){	

var busval = $("#buscode").val();
//alert ("the keycount is: "+busval.length);
if(busval.length >6)
{
	$("#submit").hide();
	$("#buscodecheck").hide();
	$("#buscodecounterror").show();
}
else
{
	$("#buscodecounterror").hide();
	$("#submit").show();
	$("#buscodecheck").show();
}

} 

 

 

Both sets of code use jQuery.  Between these two sets you should be able to figure out how to do what you want to do.  Hope this helps!

Link to comment
https://forums.phpfreaks.com/topic/227464-simple-ajax-problem/#findComment-1173311
Share on other sites

A few things I forgot to mention:

 

The business code check script also displays a green check mark or red x to indicate the status of the business code, and a text error to indicate what the problem is--sounds like that's what you want your script to do.

 

Secondly, after re-reading your post I saw your comment about still being able to prevent the data from being inserted into the db using php.  DON'T RELY ON AJAX FOR FORM VALIDATION.  The client-side validation is to make things easier for the user and give them a chance to correct anything before it's submitted.  It is NOT a substitute for validating the data before it goes into the database.  ALWAYS double check the data by validating on the server side before working with it, especially if it's going into a database. 

Link to comment
https://forums.phpfreaks.com/topic/227464-simple-ajax-problem/#findComment-1173313
Share on other sites

jQuery is a javascript library that not only greatly simplifies javascript coding, it handles most cross-browser issues.

 

It is FREE :)

 

Just download it and link to it in your head (it's also possible to dynamically link to the most updated version hosted at google, but IMO I wouldn't do that until you get a chance to test your code with any new update coming down the pike.  It's rare, but there are a few cross-browser issues that worked magically in an older version that is broken in the current release.

 

jQuery is awesome, makes AJAX much easier, and really speeds up most of what you'll be using javascript for. 

jquery.com to get started.  Trust me.  If you're learning js/AJAX, you might as well learn this first. 

 

Link to comment
https://forums.phpfreaks.com/topic/227464-simple-ajax-problem/#findComment-1173369
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.