I have this email newsletter field that works. I just dont want the person to be directed away from the page they are on when they submit the form.

Is there a way to process the form then have a window pop-up saying:
Thank you for submitting $email!

My HTML

<form action="/includes/submitEmail.php" method="post">
        Email: <input type="text" name="email" />
        <input type="submit" value="Submit" />
        </form>

My PHP

//Gather information
$email = $_POST['email'];

//Submit information
$query = ("INSERT INTO emails (id, email) VALUES ('NULL', '".$email."')");
mysql_query($query) or die (mysql_error()); 

echo "updated with: ".$email." successfully";

Is there a way I can have javascript Validate that its a real email address then process the form?

Member Avatar for P0lT10n

you can use AJAX for dont reditect and refesh anything you want

Yes AJAX is the solution.
For your ease, you may try Jquery AJAX, which is really really simple and effective.
Example-

$.ajax({
   type: "POST",
   url: "submitEmail.php",
   data: "email=example@example.com",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

This code will not work for you, but it does exactly the kind of thing you want.
Once the email is inserted the alert (or any other function you want) will automatically get called.

For complete info : http://api.jquery.com/jQuery.ajax/
Vinayak

ok so I have now tried 3 different jquery.ajax tutorials and none of them have successfully worked within my site. I have also tried to modify them to get them to work with no luck.

Does anyone know of any good tutorials to look at to try and get this to work?

ok so I have now tried 3 different jquery.ajax tutorials and none of them have successfully worked within my site. I have also tried to modify them to get them to work with no luck.

This is strange. Please post your entire script (if possible) here.
Jquery is quite easy to use, but you can always try AJAX without Jquery.
Vinayak

This is the last one I have tried. This one doesnt do anything as I can see.

Header code:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
//I deleted all the elements for name and phone number. I left the one for email in here.
<script type="text/javascript">
$(document).ready(function() {
	
	//if submit button is clicked
	$('#submit').click(function () {		
		
		//Get the data from all the fields
		var email = $('input[name=email]');

		//Simple validation to make sure user entered something
		//If error found, add hightlight class to the text field		
		if (email.val()=='') {
			email.addClass('hightlight');
			return false;
		} else email.removeClass('hightlight');
	
		//organize the data properly
		var data = 'email=' + email.val();
		
		//disabled all the text fields
		$('.text').attr('disabled','true');
		
		//show the loading sign
		$('.loading').show();
		
		//start the ajax
		$.ajax({
			//this is the php file that processes the data and send mail
			url: "process.php",	
			
			//GET method is used
			type: "GET",

			//pass the data			
			data: data,		
			
			//Do not cache the page
			cache: false,
			
			//success
			success: function (html) {				
				//if process.php returned 1/true (send mail success)
				if (html==1) {					
					//hide the form
					$('.form').fadeOut('slow');					
					
					//show the success message
					$('.done').fadeIn('slow');
					
				//if process.php returned 0/false (send mail failed)
				} else alert('Sorry, unexpected error. Please try again later.');				
			}		
		});
		
		//cancel the submit button default behaviours
		return false;
	});	
});	
</script>
</head>

My footer code, this has the form:

<div id="footerForm" class="loginForm">Join our monthly newsletter:<br />
    	<form name="email" action="includes/process.php" method="post">
        Email: <input type="text" name="email" id="email" class="text" size="30" />
        <input type="submit" value="Submit"/>
        </form>       
    </div>

Then lastly, my php.
This script was for submitting an email, I just took out the part that submits the email and put in my input query.

//Retrieve form data. 
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];

//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;

//Simple server side validation for POST data, of course, you should validate the email
if (!$email) $errors[count($errors)] = 'Please enter your email.'; 

//if the errors array is empty, send the mail
if (!$errors) {

  	$query = ("INSERT INTO emails (id, email) VALUES ('NULL', '".$email."')");
	mysql_query($query) or die (mysql_error());    
	
	//if POST was used, display the message straight away
	if ($_POST) {
		if ($result) echo 'Thank you! We have received your email.';
		else echo 'Sorry, unexpected error. Please try again later';
		
	//else if GET was used, return the boolean value so that 
	//ajax script can react accordingly
	//1 means success, 0 means failed
	} else {
		echo $result;	
	}

//if the errors array has values
} else {
	//display the errors message
	for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
	echo '<a href="form.php">Back</a>';
	exit;
}
	
	if ($result) return 1;
	else return 0;
?>

This last script does exactly what I do not want it to do, redirect the user away from the current page. it sends me to ./includes/process.php. One of the earlier tutorials I tried doesn't do that(but also didnt work), but I no longer have the code for that.

This is the last one I have tried. This one doesnt do anything as I can see.

Before trying to debug your current problem do this.
1.Download jquery to your server (any version), instead getting it from their server. This will prevent any version mismatch
2.If your script doesn't do anything try out simple scripts.
3.Also change GET to POST for "submitting data using AJAX"

you may try w3schools jquery scripts. http://www.w3schools.com/jquery/default.asp

Yeah, my simple script that I wrote that didnt even verify if it was even an email address worked fine. The only downside is it redirected the user. I tried using my script with a small ajax that I do know, and for some reason it didnt work. But maybe I have some misspelling or something, I will start from there again and try this over.

jquery does look pretty simple, I will see if I can put something together and make something work along with my script.

So I tried making my simple ajax code to work. and I got an error saying invalid email, but it did process the form and not redirect the user. So I tried to use a jquery code snippet I found online, I would try to write my own but I still don't quite understand how.

Maybe someone can help me figure out my problem from this stage. Here is my header code, the commented out code is the ajax code that would give me an error message.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!--
<script type="text/javascript">
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",url,false); //I tried also using POST to see if that wuld make a difference.
xmlhttp.send(null);
document.getElementById('footerForm').innerHTML=xmlhttp.responseText;
}
</script>-->
<script type="text/javascript">
bodyContent = $.ajax({
      url: "includes/submitEmail.php",
      global: false,
      type: "POST",
      data: ({id : this.getAttribute('footerForm')}),
      dataType: "html",
      async:false,
      success: function(msg){
         alert(msg);
      }
   }
).responseText;
</script>

My php

//get email 
$email = $_POST['email'];
$address = $email;
//echo "$email";
//When using the ajaz code instead of $msg it was an echo statement. so I got the error message right after the !preg_match. So to see what I was getting I did the echo "$email"; and was getting nothing.
//the current code is for the jqury.
// Get email address from the query string
// Validate Address

if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $address)) {
   $msg = "<strong>Error</strong>: An invalid email address was provided.";
 }
 else {
	$query = ("INSERT INTO emails (id, email) VALUES ('NULL', '".$address."')");
	mysql_query($query) or die (mysql_error()); 
if(mysql_error()){
        $msg = "<strong>Error</strong>: There was an error storing your email address.";
      }
      else {
        $msg = "Thanks for signing up!";
      }
    }
$return = $msg;
?>

My footer code

<div id="prefooter">
    <div id="footerForm" class="loginForm">Join our monthly newsletter:<br />
    	<form name="email" method="post">
        Email: <input type="text" name="email" id="footerForm" class="text" size="30" />
        <input type="submit" value="Submit" />
With the ajax I did have the last line as this:
        <input type="submit" value="Submit" onclick="loadXML(includes/'processEmail.php')" />
        </form>
    </div>
Member Avatar for P0lT10n

Why async: false ??? Change it to true...

async: true didnt change anything.

Maybe I can leave it the way is where it redirects the user away, but at the bottom of the script re-direct the user back the current page that they were on. Is there a way I can do that?? Maybe a hidden field in the form that captures the sites url then redirects them back to that url.

Ok there is a way I can redirect the user back. My form code is:

<?php
        	function curPageURL() {
				 $pageURL = 'http';
				 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
				 $pageURL .= "://";
				 if ($_SERVER["SERVER_PORT"] != "80") {
				  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
				 } else {
				  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
				 }
				 return $pageURL;
				}
        	?>
            <form name="email" method="post" action="/includes/submitEmail.php">
            <input type="hidden" name="url" value="<?php echo curPageURL(); ?>" />
            Email: <input type="text" name="email" id="footerForm" class="text" size="30" />
            <input type="submit" value="Submit" />
            </form>

And my submitEmail.php is:

//get email 
$url = $_POST['url'];
$email = $_POST['email'];
$address = $email;
//echo "$email";
// Get email address from the query string
// Validate Address

if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $address)) {
   $msg = "<strong>Error</strong>: An invalid email address was provided.";
 }
 else {
	$query = ("INSERT INTO emails (id, email) VALUES ('NULL', '".$address."')");
	mysql_query($query) or die (mysql_error()); 
if(mysql_error()){
        $msg = "<strong>Error</strong>: There was an error storing your email address.";
      }
      else {
        $msg = "Thanks for signing up!";
      }
    }
$return = $msg;
?>

<script type="text/javascript">
   /* <![CDATA[ */
      function init() {
         window.location = '<? echo $url; ?>';
      }
      window.onload = init;
	  alert('<? echo $msg; ?>');
   /* ]]> */
</script>

This all works great but is still doesn't really look good when there is blank page. And it doesn't let page load until I hit "ok" on the alert box. Is there a way I can post the alert message back on the previous page?

Member Avatar for P0lT10n

dont echo a message, show results in other box... do this

<div id="email">
   <form id="emailform" method="post" action="">
      <input type="hidden" name="url" value="" /> <!-- Write this --><?php echo curPageURL(); ?><!-- inside value, i didnt do it because it stop showing the HTML colors down here... -->
      Email: <input type="text" name="email" id="footerForm" class="text" size="30" />
      <input type="button" value="Submit" onclick="send();" />
   </form>
   <div id="emailsuccess"></div>
</div>

then, send it with AJAX using jQuery

function send(){
   $.ajax({
      type: "POST",
      url: "/includes/submitEmail.php",
      data: "email="+$('#footerForm').val(),
      success: function(msg){
        $("#emailform").hide();
        $("#emailsuccess").html(msg).show();
      }
   });
}

This is the explain about the code:

1º - You add a general DIV.
2º - Eliminate action="" attribute, living it blank inside.
3º - Change <input type="submit"... /> to <input type="button" value="Submit" onclick="send();" /> and add onClick="send();" for call AJAX and submit...
4º - Dont forget to add JavaScript function send(){...} .
5º - I add data on data: "...", with jQuery ( $('#footerForm').val() ), the val() add to the string the Text value of id="footerForm" .
6º - On success, when I recive the AJAX's answer, hide the email form ( id="emailform" ) and show the DIV for email success ( id="emailsuccess ). Dont forget when I recive AJAX's answer, I will add it to id="emailsuccess with html(msg) .


I hope this really work... If something dont work, let me know !

The first time I tried it with all your code I got an alert message from the bottom of my php script saying invalid email. So I commented out the javascript at the bottom and got nothing. Jquery did remove the form and nothing showed up, just blank.

Member Avatar for P0lT10n

what had you commented ????

In this file at the bottom.

//get email 
$url = $_POST['url'];
$email = $_POST['email'];
$address = $email;
//echo "$email";
// Get email address from the query string
// Validate Address

if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $address)) {
   $msg = "<strong>Error</strong>: An invalid email address was provided.";
 }
 else {
	$query = ("INSERT INTO emails (id, email) VALUES ('NULL', '".$address."')");
	mysql_query($query) or die (mysql_error()); 
if(mysql_error()){
        $msg = "<strong>Error</strong>: There was an error storing your email address.";
      }
      else {
        $msg = "Thanks for signing up!";
      }
    }
$return = $msg;
?>

<!--<script type="text/javascript">
   /* <![CDATA[ */
      function init() {
         window.location = '<? echo $url; ?>';
      }
      window.onload = init;
	  alert('<? echo $msg; ?>');
   /* ]]> */
</script>-->

That's what I did and I still didn't work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.