Javascript/PHP Dynamics

Trouble getting Javascript and PHP to go hand-in-hand

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 2427 Views - Last Post: 01 April 2009 - 11:08 AM Rate Topic: -----

#1 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Javascript/PHP Dynamics

Posted 31 March 2009 - 08:06 PM

Hello, I'm a new user on this site, but I've been at this PHP coding game for quite some time, but I've run into a hiccup.

I need to execute a PHP if statement with javascript without reloading the page. It has to do with a 3-step signup, and I'm having difficulty determining how to move from step 1 to step 2. It also includes an error-catcher to help any faulty sign-ups. My plan for the error-catcher was simple, until I realized passing variables between client and server without reloading the whole page is rather tricky.

The form the data on it is posting to a $_SERVER['PHP_SELF'].

This is the IF statement that needs executing: ($_POST and $_GET can be interchanged whenever necessary in terms of the submitted form data.)
if (isset($_POST['stage1'])) {
	//Match the passwords up and ensure they match, else you get an error.
	if ($_POST['password1']===$_POST['password2']) {
		$userpass=$_POST['password1'];
	} else {
		$error="Passwords do not match!  Please try again.";
	}
	
	// Match up the emails and ensure they do, else you get an error.
	if ($_POST['email1']===$_POST['email2']) {
		$error="Your emails do not match!  Please try again.";
	}
	
	// Validate the birthday to see if the applicant is over 18....
	$CurrDate=date("md");
	$ValidYear=date("Y")-18;
	// The two above strings gather intergers for the month and day with leading zeroes.
	
	$validation=$ValidYear.$CurrDate; // The final result of a complete date to validate against.
	
	$UserDate=$_POST['year'].$_POST['month'].$_POST['day']; // This is the user's given date of birth.
	
	if ($validation<$UserDate) {
		$error="You're not over 18!  You cannot apply.";
	}
	
	// Carry on the values from this form! (granted there are no errors)
	if ($error==NULL) {
		$NextStep; //Ignore that this variable is null.  It's rather unimportant other than it changes $_POST to $_GET as I had trouble with $_GET...
	}
}



The only Javascript I really know is EXTREMELY basic. Mostly because I look at all these tutorials and my head explodes beyond getElementById()

Any help would be greatly appreciated :)

This post has been edited by the1corrupted: 31 March 2009 - 09:07 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Javascript/PHP Dynamics

#2 noname_clark  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 75
  • Joined: 22-October 08

Re: Javascript/PHP Dynamics

Posted 31 March 2009 - 09:50 PM

Quote

I need to execute a PHP if statement with javascript without reloading the page. It has to do with a 3-step signup, and I'm having difficulty determining how to move from step 1 to step 2. It also includes an error-catcher to help any faulty sign-ups.


What do you mean by this?
do you mean like you have one page ask you for a username and a password, you click submit, then it goes onto another page where it asks you for your email, click submit, then ask for your birthday? if this is what you're trying to do, I would use "hidden" variables to pass the information from one page to the next, or you can use a cookie/session.
Was This Post Helpful? 0
  • +
  • -

#3 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 05:38 AM

Sorry that I wasn't quite clear enough before. Error-catching will happen onsubmit. Use a javascript function to bring up an alert with the various errors that the user has incurred, but I can't get the error to pass from PHP to javascript without reloading the entire page. I was hoping someone could give me an example of a page where that doesn't happen.

This is also a one-page process... I have it setup correctly if I can get the javascript to talk to the php, then the steps will advance properly.

signup.php
include ("signup.inc.php");
//More code ...  Code
	echo "
				<tr>
					<td>
						First Name:
					</td>
					<td>
						<input type=\"text\" name=\"first\" length=\"15\">
					</td>
				</tr>
				<tr>
					<td>
						Last Name:
					</td>
					<td>
						<input type=\"text\" name=\"last\" length=\"15\">
					</td>
				</tr>
				<tr>
					<td>
						E-Mail Address:
					</td>
					<td>
						<input type=\"text\" name=\"email1\" length=\"15\">
					</td>
				</tr>
				<tr>
					<td>
						Retype E-Mail:
					</td>
					<td>
						<input type=\"text\" name=\"email2\" length=\"15\">
					</td>
				</tr>
				<tr>
					<td>
   						Date of Birth:
					</td>
					<td>
						<select name=\"day\">".$dayoption."
	   					</select>
	   					<select name=\"month\">".$monthoption."
	   					</select>
	   					<select name=\"year\">".$yearoption."
	   					</select>
   					</td>
				</tr>
				<tr>
					<td colspan=\"2\">
						<hr>
   					</td>
				</tr>
				<tr>
					<td>
						Username:
					</td>
					<td>
						<input type=\"text\" name=\"user\" length=\"15\">
					</td>
				</tr>
				<tr>
					<td>
						Password:
					<td>
						<input type=\"password\" name=\"password1\" length=\"15\">
					</td>
				</tr>
				<tr>
					<td>
						Retype Password:
					</td>
					<td>
						<input type=\"password\" name=\"password2\" length=\"15\">
					</td>
				</tr>";
}

/* 
	*						*
	*						*
	*	STEP 2 PROCESSING			*
	*						*
	*						*
 */

//Step 2 processing will go here once step 1 has been solved...
/*
if ($_GET['stage']==2) {
}
*/

// End the content table and re-use that javascript function above in the beginning.  We hate writing redundant code.
echo "
				<tr>
					<td colspan=\"2\">
						<center>
							<input type=\"hidden\" value=\"1\" name=\"stage".$_GET['stage']."\">
							<br>
							<input type=\"submit\" value=\"Proceed\" onsubmit=\"NextStep()\">
						</center>
					</td>
				</tr>
			</table>
";



signup.inc.php
if (isset($_POST['stage1'])) {
	//Match the passwords up and ensure they match, else you get an error.
	if ($_POST['password1']===$_POST['password2']) {
		$userpass=$_POST['password1'];
	} else {
		$error="Passwords do not match!  Please try again.";
	}
	
	// Match up the emails and ensure they do, else you get an error.
	if ($_POST['email1']===$_POST['email2']) {
		$error="Your emails do not match!  Please try again.";
	}
	
	// Validate the birthday to see if the applicant is over 18....
	$CurrDate=date("md");
	$ValidYear=date("Y")-18;
	// The two above strings gather intergers for the month and day with leading zeroes.
	
	$validation=$ValidYear.$CurrDate; // The final result of a complete date to validate against.
	
	$UserDate=$_POST['year'].$_POST['month'].$_POST['day']; // This is the user's given date of birth.
	
	if ($validation<$UserDate) {
		$error="You're not over 18!  You cannot apply.";
	}
	
	// Carry on the values from this form! (granted there are no errors)
	if ($error==NULL) {
		$NextStep;
	}
}

if (isset($_POST['step2'])) {
	
}

// This is used to post all the collected data.

if (!isset($error) AND isset($_POST['form_complete'])) {
	include ("sql/connect.php");
	include ("sql/create_user.post.php");
}
//Setup the function to advance to the next step.
echo "
	<script type=\"text/javascript\">
		function NextStep() {
			window.location=\"".$NextStep."\";
		}
	</script>";


This post has been edited by the1corrupted: 01 April 2009 - 05:49 AM

Was This Post Helpful? 0
  • +
  • -

#4 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 06:24 AM

Ok im guessing you are wanting errors such as blank fields or invalid data?!

// use this to post to the javascript first
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" onsubmit="return checkform(this);">



than just use some javascript to do a little error checking for you

<script language="Javascript" type="text/javascript">
<!--
function checkform ( form )
{
  if ((form.first.value == "")||(form.last.value == "")) {
	alert( "One or more of the required fields was left blank, please fill in the required fields and resubmit your request." );
	return false;
  }
  return true;
}
//-->
</script>



that javascript just checks for blank entries... again not entirely sure this is what your looking for but thought i would throw something out there maybe trigger something :)

P.S. is it just me or are all the user avatars the same... its freakin me out lol

This post has been edited by RPGonzo: 01 April 2009 - 06:32 AM

Was This Post Helpful? 0
  • +
  • -

#5 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 06:34 AM

I was actually about to try that...

*headesks*

But thanks for the snippet!

I can rework it to look for more specifics.

EDIT: Grah! The code isn't working. It isn't alerting me when it should be...

This post has been edited by the1corrupted: 01 April 2009 - 07:24 AM

Was This Post Helpful? 0
  • +
  • -

#6 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 07:26 AM

What are you trying to get it to do exactly?
Was This Post Helpful? 0
  • +
  • -

#7 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 07:30 AM

I'm building a signup page and I want it to catch errors on a form. I'm playing with javascript to do so.

This post has been edited by the1corrupted: 01 April 2009 - 07:32 AM

Was This Post Helpful? 0
  • +
  • -

#8 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 07:32 AM

Okie dokie good to hear :)
Was This Post Helpful? 0
  • +
  • -

#9 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 07:50 AM

Here's my latest attempt at the javascript... (Don't mind the \" as I'm embedding it in PHP.) Somehow, it doesn't work.

<!--
	function checkform(form) {
		var errors;
		if ((document.getElementById('firstn')==\"\") || (document.getElementById('lastn')==\"\")) {
			errors=\"<br>One of your names is missing.\";
		}
		if ((document.getElementById('email1')!=document.getElementById('email2')) || (document.getElementById('email1')==\"\") || (document.getElementById('email2')==\"\")) {
			errors+=\"<br>Your emails are either blank or do not match.\";
		}
		if (document.getElementById('user')==\"\") {
			errors+=\"<br>Your username is blank.\";
		}
		if (document.getElementById('password1')==document.getElementById('password2') || (document.getElementById('password1')==\"\") || (document.getElementById('password2)==\"\")) {
			errors+=\"<br>Your passwords are either blank or do not match.\"
		}
		if (errors!=\"\") {
			alert(\"Your submission had the following errors:\"+error+\"<br>Please fix them.\");
			return false;
		}
		return true;
	}
	//-->


This post has been edited by the1corrupted: 01 April 2009 - 07:50 AM

Was This Post Helpful? 0
  • +
  • -

#10 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 08:00 AM

easiest way to use this is to just end your php tag at the bottom of the page and use this as normal HTML script code....

// end PHP
?>

<!-- INSERT Javascript CODE HERE -->



reason being is that sometimes Javascript likes to not "play" nice with escaped characters. Not saying it will not or couldn't work. But this just takes the guess work out.

and using

document.getElementById('FIELD_ID')



im assuming your storing this in a .JS file?! or is that just the method of choice you like to use?

Just asking because the

checkform( form )



part of the Javascript function actually defines 'form' as 'this' in the onsubmit so it just takes a little less coding to write what you want.

This post has been edited by RPGonzo: 01 April 2009 - 08:01 AM

Was This Post Helpful? 0
  • +
  • -

#11 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 08:04 AM

If I put it at the end, it'll explode rather randomly because the script will be either after or before all the displayed content and will not end up between the <html> or <head> tags as it does now. If I "View Source" on the page, this is the javascript it displays.

<!--
	function checkform(form) {
		var errors;
		if ((document.getElementById('firstn')=="") || (document.getElementById('lastn')=="")) {
			errors="<br>One of your names is missing.";
		}
		if ((document.getElementById('email1')!=document.getElementById('email2')) || (document.getElementById('email1')=="") || (document.getElementById('email2')=="")) {
			errors+="<br>Your emails are either blank or do not match.";
		}
		if (document.getElementById('user')=="") {
			errors+="<br>Your username is blank.";
		}
		if (document.getElementById('password1')==document.getElementById('password2') || (document.getElementById('password1')=="") || (document.getElementById('password2)=="")) {
			errors+="<br>Your passwords are either blank or do not match."
		}
		if (errors!="") {
			alert("Your submission had the following errors:"+error+"<br>Please fix them.");
			return false;
		}
		return true;
	}
	//-->



But I could store it in a .js file but that's been known to not work before.
Was This Post Helpful? 0
  • +
  • -

#12 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 08:08 AM

Are you getting any errors or its just not working?

when i use this same code i have it right below the form itself

<form method="post" action="/contact/?id=verify" onsubmit="return checkform(this);">
<input type="hidden" name="send" value="true" />
	<div class="Conleft">
		
		<label class="labelA">First name:<i>*</i></label><br/>
		<input class="inputA" tabindex="1" name="Fname" id="Fname" type="text"></input><br/>
		<label class="labelA">Phone:<i>*</i></label><br/>
		<input class="inputA" tabindex="3" name="Phone" id="Phone" type="text"></input><br/>
		<label class="labelA">Address:</label><br/>
		<input class="inputA" tabindex="5" name="address" id="address" type="text"></input>
		
	</div>

	<div class="Conright">
		
		<label class="labelA">Last name:<i>*</i></label><br/>
		<input class="inputA" tabindex="2" name="Lname" id="Lname" type="text"></input><br/>
		<label class="labelA">E-mail:<i>*</i></label><br/>
		<input class="inputA" tabindex="4" name="email" id="email" type="text"></input><br/>
		<label class="labelA">Zip:</label><br/>
		<input class="inputA" tabindex="6" name="zip" id="zip" type="text"></input>
		
	</div>
	
	<div class="cBoth"></div>
	
	<div class="Conmes">
		
		<label class="labelA">Message:<i>*</i></label>
		<br/>
		<textarea class="textarea" tabindex="7" rows="1" cols="1" id="webmess" name="webmess"><?php 
		if (!empty($inquiry)) {		
			echo 'Inquiry for Stock Number '. $val['StockNumber'] .':';
			echo $val['Year'] .'-'. $val['Manufacturer'] .'-'. $val['Model']; echo "\n"; echo "\n";
			}
		?></textarea>
	
	</div>
	
	<div class="buttonrow">
	
		<input class="reset" tabindex="9" type="reset" name="resetbtn" value=""/>
		
		<input type="submit" tabindex="8" class="submit" id="submit" value=""  name="submit"/>
	
	</div>
</form>
<?php
if (empty($inquiry)) {?>	
	<div id="holder">
	<div class="email">
		
			<div class="main_top_label">Contact us by email:</div>
				<a href="mailto:sales@jandrequip.com">Sales@JandREquip.com</a>
				<br/><br/>
				<a href="mailto:Transport@jandrequip.com">Transport@JandREquip.com</a>
		
	</div>

	<div class="phone">
	
	<div class="main_top_label">Contact us by phone:</div>
		<div class="info_list">
		<?php 	
			echo $OFF_PHONE.'<br/>';
			echo $CELL_PHONE.'<br/>';
			echo $EMER_PHONE.'<br/>';
		?>
		</div>
	</div>
	</div>
<?php  }  ?>
</div>

<script language="Javascript" type="text/javascript">
<!--
function checkform ( form )
{
  if ((form.Lname.value == "")||(form.Phone.value == "")||(form.Fname.value == "")
		(form.email.value == "")||(form.webmess.value == "")) {
	alert( "One or more of the required fields was left blank, please fill in the required fields and resubmit your request." );
	return false;
  }
  return true;
}
//-->
</script>



and that's the exact page copy and paste that is working ..
Was This Post Helpful? 0
  • +
  • -

#13 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 08:48 AM

Well, not to overcomplicate things, but this page is already half a megabyte... Besides, I can get a simple alert() to work in Javascript, but only after PHP caught the errors.

EDIT: The javascript seems to be overlooking all the discrepancies with the page.

This post has been edited by the1corrupted: 01 April 2009 - 08:49 AM

Was This Post Helpful? 0
  • +
  • -

#14 RPGonzo  Icon User is offline

  • // Note to self: hmphh .... I forgot
  • member icon

Reputation: 151
  • View blog
  • Posts: 954
  • Joined: 16-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 09:45 AM

With the file being that big maybe it would be a good idea to split your submission part of it away from the form part.

If you do that you can do all your form submission error checking on the submission page via PHP and carry all your $_POST values in a array and if errors occur return the array, this Javascript was intended to be light and as a small error checking front for the page.

But after saying that i do realize you are trying to do this without reloading the page, and im guessing so that you don't loose the $_POST data. But a Return Array() would solve that.

But than again maybe im thinking in the wrong direction of what you want to achieve. -_-
Was This Post Helpful? 0
  • +
  • -

#15 the1corrupted  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 165
  • Joined: 31-March 09

Re: Javascript/PHP Dynamics

Posted 01 April 2009 - 10:23 AM

Well, I came up with a solution until the site can be reworked.

Create a session!

But the page still reloads, but it does manage to meticulously catch every error the user had input.

if (isset($_POST['stage1'])) {
	// Connect to the database and query for the users.	
	include ("sql/connect.php"); // All SQL-related PHP will go in the SQL/ file.
	$user=$_POST['user'];
	$SelectUser="SELECT `user` FROM `users` WHERE `user`='$user'";
	$QueryUser=mysql_query($SelectUser) or die ("Could not match data because ".mysql_error());
	$UserExist=mysql_num_rows($QueryUser);
	
	if ($UserExist!=0) {
		$error="\\nThe usernmae you have chosen has been taken.";
	} elseif ($_POST['user']==NULL) {
		$error="\\nYou have not typed in your username.";
	}
	//Check if the applicant filled in their name
	if ($_POST['first']==NULL OR $_POST['last']==NULL) {
		$error=$error."\\nPlease fill in your name.";
	}
	// Validate the birthday to see if the applicant is over 18....
	$CurrDate=date("md");
	$ValidYear=date("Y")-18;
	// The two above strings gather intergers for the month and day with leading zeroes.
	
	$validation=$ValidYear.$CurrDate; // The final result of a complete date to validate against.
	
	$UserDate=$_POST['year'].$_POST['month'].$_POST['day']; // This is the user's given date of birth.
	//Validate that the user is over 18
	if ($validation<$UserDate OR $UserDate==NULL) {
		$error=$error."\\nYou are not over 18!";
	}
	// Check the passwords
	if ($_POST['password1']!=$_POST['password2']) {
		$error=$error."\\nYour passwords do not match.";
	} elseif ($_POST['password1']==NULL OR $_POST['password2']==NULL) {
		$error=$error."\\nOne of your passwords are blank!";
	}
	//Check the emails
	if ($_POST['email1']==NULL OR $_POST['email2']==NULL) {
		$error=$error."\\nOne of your emails are blank!";
	} elseif ($_POST['email1']!=$_POST['email2']) {
		$error=$error."\\nYour emails do not match.";
	}
	// Carry on the values from this form! (granted there are no errors)
	if ($error!=NULL) {
		echo "
<script type=\"text/javascript\" language=\"Javascript\">
	alert(\"You have the following errors on your submission:\\n".$error."\\n\\nPlease fix them.\");
	history.go(-1);
</script>";
	} else {
		// Create a cache limiter and set the session to expire in 45 minutes.
		session_cache_limiter("private");
		session_cache_expire(45);
		$fullname=$_POST['first']." ".$_POST['last'];
		$dob=$_POST['year']." ".$_POST['month']." ".$_POST['day'];
		$_SESSION['stage1']=array($_POST['user'], $_POST['password1'], $_POST['email1'], $fullname, $dob);
	}
	mysql_close($link);
}


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2