Staying on A Page

I have a small Email program that send an Email after some enters their email address and clicks on submit.  I want to stay on the original page, but now its going to a blank page with Email sent on it.  How can I make this not happen.  I removed the message at the bottom and it just goes toa blank page now,  It needs to return to / or stay on the restaurantpage.php.
Thank you.

<?php
include("config.php");
$Lid = $_POST['Lid'];
$Lid = mysql_real_escape_string($Lid);  
mysql_query("SET CHARACTER SET utf8");
$sql=mysql_query("SELECT tblRestaurants.RestName,tblLocations.StreetNumber,tblLocations.Street,
	tblLocations.CrossOne, tblLocations.CrossTwo, tblCities.CityName,tblStates.StateName,tblZipCodes.ZipCodeName,
	tblLocations.Phone,tblLocations.Email, tblLocations.Fax, tblLocations.SMS, tblLocations.LocationID
	FROM tblLocations
	INNER JOIN tblRestaurants ON tblRestaurants.RestID = tblLocations.RestID
	INNER JOIN tblCities ON tblCities.CityID = tblLocations.CityID
	INNER JOIN tblStates ON tblStates.StateID = tblLocations.StateID
	INNER JOIN tblZipCodes ON tblZipCodes.ZipCodeID = tblLocations.ZipCodeID
	WHERE tblLocations.LocationID = '$Lid'");
	while($row=mysql_fetch_array($sql))
	{
	$RestName = $row['RestName'];
	$StreetNumber = $row['StreetNumber'];
	$Street = $row['Street'];
	$CrossOne = $row['CrossOne'];
	$CrossTwo = $row['CrossTwo'];
	$City = $row['CityName'];
	$State = $row['StateName'];
	$ZipCode = $row['ZipCodeName'];
	$Phone = $row['Phone'];
	$Email = $row['Email'];
	$Fax = $row['Fax'];
	$SMS = $row['SMS'];
	$Lid = $row['LocationID'];
	}
 
    $to = $_POST['ESend'];
 	$subject = "Menuhead.com";
 	$RestName = $_POST['RestName'];
	$Email = $_POST['Email'];
	$message="
	Name: " . $_POST['RestName']." \n
	Emai: $Email \n";
 	$from = "Menuhead";
 	$headers = "From:" . $from;
 	mail($to,$subject,$message,$headers);
 	echo "Mail Sent.";
 ?>

Open in new window

DS928Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
GaryConnect With a Mentor Commented:
<script type="text/javascript">
$(document).ready(function() {
$('#popup-wrapper').modalPopLite({
		openButton: '#clicker',
		closeButton: '#close-btn',
		isModal: true });

$("#send").click(function(e){
	e.preventDefault();
	var Lid = location.search.match(new RegExp("[\\?&]LocationID=([^&#]*)")).pop();
	$("form").append("<input type='hidden' name='Lid' value='" + Lid + "' >");
	$.ajax({
		type:'POST',
		url:'/Scripts/send_form_email.php',
		data:$(this).closest("form").serialize(),
		success:function(response) { 
			if(response=="Mail Sent."){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
$('#close-btn').trigger('click')
})
})
</script> 

Open in new window

0
 
GaryCommented:
Not sure I'm following you but if you want to stay on the Contact Us page then you will need to use Ajax to send the data to the server (your email code) Don't have time now but some reading
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/serialize/

An example

$("#Contactus").click(function(e){
	e.preventDefault();
	$.ajax({
		type:'POST',
		url:'/emailpage.php',
		data:$('#Contactus').closest("form").serialize(),
		success:function(response) {
			alert("Your message has been sent")
		}
	});
})

Open in new window

0
 
Dave BaldwinFixer of ProblemsCommented:
Or you can simply POST to the page that the form is on and include all the PHP code there.  Here's my demo page.  Put your own info in for the email addresses and test it yourself.
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');

# some settings of POST vars
if (!isset($_POST['send']))  $send = ''; else $send = $_POST['send'];
if (!isset($_POST['toText'])) $toText = ''; else $toText = $_POST['toText'];
if (!isset($_POST['subjectText'])) $subjectText = ''; else $subjectText = $_POST['subjectText'];
if (!isset($_POST['msgText'])) $msgText = ''; else $msgText = $_POST['msgText'];
if (!isset($_POST['ccText'])) $ccText = ''; else $ccText = $_POST['ccText'];
if (!isset($_POST['bccText'])) $bccText = ''; else $bccText = $_POST['bccText'];
if (!isset($_POST['nameText'])) $nameText = ''; else $nameText = $_POST['nameText'];
if (!isset($_POST['fromText'])) $fromText = ''; else $fromText = $_POST['fromText'];

if ($send == "") {
    $title="Test Email Page";
    $announce="---";
}
else {
	if($fromText === "") die("No name!");
  $toText="youremail@yourdomain.com";
	$title="Test Email Page";
  $announce="Your Message has been Sent!";
	$header = "From: ".$fromText."\r\n";
//	$header .= "Cc: ".$ccText."\n";
	$header .= "Reply-To : ".$fromText."\r\n";
	$header .= "Return-Path : ".$fromText."\r\n";
	$header .= "X-Mailer: PHP\r\n";
	$header .= "MIME-Version: 1.0\r\n";
	$header .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
//	ini_set(sendmail_from,$fromText);  
	mail($toText, $subjectText, $msgText, $header, '-f'.$fromText);
//	ini_restore(sendmail_from);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title><?php echo($title)?></title>
<style type="text/css">
<!-- 
A:link { color: #999999; }
A:visited { color: #999999; }
A:hover {color: #0099ff;}
-->
</style>
<script type="text/javascript">
<!--
function check()
{
var at=document.getElementById("fromText").value.indexOf("@");
var eml=document.getElementById("fromText").value;
var nam=document.getElementById("nameText").value;
var alerttxt="";
var submitOK="true";

if (eml.length < 5 || at == -1)
    {
    alerttxt=alerttxt+"Please enter a valid e-mail address!\r\n";
    submitOK="false"
    //return false;
    }
if (nam.length < 3)
    {
    alerttxt=alerttxt+"Please enter your name.\r\n";
    submitOK="false"
    //return false;
    }
if (submitOK=="false")
    {
    alert(alerttxt);
    return false;
    }

}
// -->
</script>
</head>

<body bgcolor="#ddeedd">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" summary="" width="580">
<tr><td align="center">

<?php
if ($send != "") {
   	echo ("To: ".$toText."<br>\r\nSubject: ".$subjectText."<br>\r\n".$msgText."<br>\r\n".$header);
		}
?>

<p><b><font color="#000000" size="5">Test Email</font></b></p>
<font size="4" color="#000000">

<form method="POST" action="Email.php" onsubmit="return check();">
    <p><font size="3"><b>Name: <input type="text" name="nameText" id="nameText" size="46"></b></font></p>
    <p><font size="3"><b>Email: <input type="text" name="fromText" id="fromText" size="46"></b></font></p>
    <input type="hidden" name="subjectText" value="Web Mail">
    <p><font face="Arial" size="3"><b>Message Text:</b></font></p>
    <p><font face="Arial" size="3"><b><textarea rows="6" name="msgText" cols="60"></textarea></b></font></p>
    <p><font size="3"><b><input type="submit" value="Send" name="send" style="font-family: Arial; font-size: 12pt; font-weight: bold"></b></font></p>
    <input type="hidden" name="state" value="1">
  </form>
  <b><font face="Arial" size="4" color="#e00000"><?php echo($announce)?></font></b><br><br>

</font>
</td></tr>
</table> 
</div>

</body>
</html>

Open in new window

0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
DS928Author Commented:
Two very good suggestions!
Trying the bottom one first.  Ok I have it going back to the restaurantpage.php from where it began.  But I need to pass the value of Lid so the restaurantpage.php shows the same restaurant that it was on.  This what I tried...

<form name="contactform" method="post" autocomplete="off" action="restaurantpage.php?LocationID=$Lid">

Open in new window


But I know I don't have it right.  When I put a 1 in place of Lid it goes back to the page it was on.  But it has to be a variable.

The restaurantpage.php at the top...
$Lid = $_GET['LocationID'];
$Lid = mysql_real_escape_string($Lid);  

And the form is a POST.........
0
 
Olaf DoschkeSoftware DeveloperCommented:
action="restaurantpage.php?LocationID=$Lid"

That part is returning to the restaurantpage. Instead you should stay there, by not making a php script call.

Instead using ajax techniques you make a javascript call there and javascript creates a httprequest. jQuery simplifies that, once you get your head into it.

Here are some other ways also based on jquery: http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form

This means, your javascript function does a post request to your mail.php script and the result coming from it wold be show via a messagebox. That means just return "mail sent" or something like that, not a whole html page. You need to just extract the php taking in the mail form values and sending the mail.

To get jquery into your page you simply load it via a script tag in the header:
<header>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
...

Open in new window


Bye, Olaf.
0
 
DS928Author Commented:
Well so much for solution two.  After I get some sleep I will delve into the Ajax route.  This seems logica not to leave the page at all!  Thank you.
0
 
Julian HansenCommented:
How does this relate to your other two questions - one of them has an extensive discussion around posting through AJAX - does that not address this issue?
0
 
Chris StanyonCommented:
If you want to pass in the variable to the querystring you need to echo it out, not just type it in:

<form name="contactform" method="post" autocomplete="off" action="restaurantpage.php?LocationID=<?php echo $Lid; ?>">

Open in new window

0
 
GaryCommented:
Upload solution two and I will have a look at it, it's probably just something small
0
 
DS928Author Commented:
Here is the file.  This is set for the second solution which is still not working.  Your suggestion sounds even better (Ajax).  Thank you for your help.
restaurantpage.php
0
 
Ray PaseurCommented:
HTML documents render web pages.  PHP scripts create HTML documents.  It follows that a PHP script can be used to create any HTML web page.  This will be true for either your <form> page or your action script.

There is no such thing as "staying on the original page" however you can create this effect by using AJAX to send the request in the background, without reloading the entire page.  This article shows the bare-essence of the jQuery AJAX request.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html

You can also create this effect by packaging the <form> and the action script into a single script file.  This code snippet shows how to do that.  You can install it and run it to see the moving parts.

<?php // RAY_form_to_email.php
error_reporting(E_ALL);


// SEND MAIL FROM A FORM


// REQUIRED VALUES ARE PREPOPULATED - CHANGE THESE FOR YOUR WORK
$from  = "NoReply@Your.org";
$subj  = "Contact Form";

// THIS IS AN ARRAY OF RECIPIENTS - CHANGE THESE FOR YOUR WORK
$to[]  = "You@Your.org";
$to[]  = "Her@Your.org";
$to[]  = "Him@Your.org";


// IF THE DATA HAS BEEN POSTED
if (!empty($_POST['email']))
{
    // CLEAN UP THE POTENTIALLY BAD AND DANGEROUS DATA
    $email      = clean_string($_POST["email"]);
    $name       = clean_string($_POST["name"]);
    $telephone  = clean_string($_POST["telephone"]);

    // CONSTRUCT THE MESSAGE THROUGH STRING CONCATENATION
    $content    = NULL;
    $content   .= "You have a New Query From $name" . PHP_EOL . PHP_EOL;
    $content   .= "Tel No: $telephone" . PHP_EOL;
    $content   .= "Email: $email" . PHP_EOL;

    // SEND MAIL TO EACH RECIPIENT
    foreach ($to as $recipient)
    {
        if (!mail( $recipient, $subj, $content, "From: $from\r\n"))
        {
            echo "MAIL FAILED FOR $recipient";
        }
        else
        {
            echo "MAIL WORKED FOR $recipient";
        }
    }

    // PRODUCE THE THANK-YOU PAGE
    echo '<p>THANK YOU</p>' . PHP_EOL;
}


// A FORM TO TAKE CLIENT INPUT FOR THIS SCRIPT
$form = <<<ENDFORM
<form method="post">
Please enter your contact information
<br/>Email: <input name="email" />
<br/>Phone: <input name="telephone" />
<br/>Name:  <input name="name" />
<br/><input type="submit" />
</form>
ENDFORM;

echo $form;


// A FUNCTION TO CLEAN UP THE DATA - AVOID BECOMING AN OPEN-RELAY FOR SPAM
function clean_string($str)
{
    // IF MAGIC QUOTES IS ON, WE NEED TO REMOVE SLASHES
    $str = stripslashes($str);

    // REMOVE EXCESS WHITESPACE
    $rgx
    = '#'                // REGEX DELIMITER
    . '\s'               // MATCH THE WHITESPACE CHARACTER(S)
    . '\s+'              // MORE THAN ONE CONTIGUOUS INSTANCE OF WHITESPACE
    . '#'                // REGEX DELIMITER
    ;
    $str = preg_replace($rgx, ' ', $str);

    // REMOVE UNWANTED CHARACTERS
    $rgx
    = '#'                // REGEX DELIMITER
    . '['                // START OF A CHARACTER CLASS
    . '^'                // NEGATION - MATCH NONE OF THE CHARACTERS IN THIS CLASS
    . 'A-Z0-9'           // KEEP LETTERS AND NUMBERS
    . '"'                // KEEP DOUBLE QUOTES
    . "'"                // KEEP SINGLE QUOTES
    . '@&+:?_.,/\-'      // KEEP SOME SPECIAL CHARACTERS (ESCAPED HYPHEN)
    . ' '                // KEEP BLANKS
    . ']'                // END OF THE CHARACTER CLASS
    . '#'                // REGEX DELIMITER
    . 'i'                // CASE-INSENSITIVE
    ;
    $str = preg_replace($rgx, NULL, $str);

    return trim($str);
}

Open in new window

HTH, ~Ray
0
 
GaryCommented:
Seems to be working fine but there is no response from post_comment.php.
What do you want it to respond with?
0
 
DS928Author Commented:
Not sure about what you mean by post_comment.php thats in another section.

GaryC123 Here is the code calling another page instead of running the code on the restaurantpage.php.

<div id="popup-wrapper" display="hidden">
		<form name="contactform" method="POST" autocomplete="off" action="Scripts/send_form_email.php">
        <div align="center" >Enter Your E-Mail Address</div><br />
        <div align="center"><input name="ESend" type="text" id="Esend" maxlength="80" size="30"/></div><br />
        <div align="center"><input name="Send" type="submit" id="send" value="Submit" /></div><br />
        <div align="center"><input name="Cancel" type="button" id="close-btn" value="Cancel" /></div><br />
        </form>
</div>

Open in new window


I am not sure at this point.  Is it better to run the email code from the same page?  Or another page?  Or does it make no difference?  I just want that after the email is went, the user ends uo in the same place before the email was sent.  I hope this makes sense.  Thank you.
0
 
GaryCommented:
What page is this on the website.
The email code should be in its own page - you call this with the ajax.
0
 
GaryCommented:
<div id="popup-wrapper" display="hidden">
		<form name="contactform" method="POST" autocomplete="off" action="Scripts/send_form_email.php">
        <div align="center" >Enter Your E-Mail Address</div><br />
        <div align="center"><input name="ESend" type="text" id="Esend" maxlength="80" size="30"/></div><br />
        <div align="center"><input name="Send" type="submit" id="send" value="Submit" /></div><br />
        <div align="center"><input name="Cancel" type="button" id="close-btn" value="Cancel" /></div><br />
        </form>
</div> 

<script>
$("#send").click(function(e){
	e.preventDefault();
	$.ajax({
		type:'POST',
		url:'/emailpage.php', // This is the page that should contain your email code.
		data:$(this).closest("form").serialize(),
		success:function(response) { // The email page should send something back - like the number 1 if ok
			if(response==1){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
}) 
</script>

Open in new window

0
 
DS928Author Commented:
Its on the restaurantpage.php It's the attached file except for the form at the bottom. I changed restaurant page to the send_form_email.php.  Right now it's not returning,  It's the white page with mail sent.
restaurantpage.php
0
 
GaryCommented:
You have a problem with
 $("input[name='Send']").click(function(evt) {
var Lid = location.search.match(new RegExp("[\\?&]LocationID=([^&#]*)")).pop();
$("form").append("<input type='hidden' name='Lid' value='" + Lid + "' >");
}) 

Open in new window

..because there are no url params.
See my code above that should be part of the click function I have there.
Might be easier to just place this directly in an hidden field in the form at the server since you have this data before you send the page to the user.
0
 
Chris StanyonCommented:
In the page you uploaded, you don't seem to be creating the querystring in your form correctly - you are not setting a GET variable called LocationID!!

You have:
<form name="contactform" method="POST" autocomplete="off" action="restaurantpage.php?=<?php echo $Lid; ?>">

Open in new window

should be:
<form name="contactform" method="POST" autocomplete="off" action="restaurantpage.php?LocationID=<?php echo $Lid; ?>">

Open in new window

0
 
GaryCommented:
I cannot test further (after adding an ID) as I cannot see the ajax code on the page.
You have ajax for the other form.
0
 
GaryCommented:
When I manually inject the ajax code then it works fine and I get a response of Mail Sent.

<script>
$("#send").click(function(e){
	e.preventDefault();
	$.ajax({
		type:'POST',
		url:'/Scripts/send_form_email.php',
		data:$(this).closest("form").serialize(),
		success:function(response) { 
			if(response=="Mail Sent."){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
}) 
</script>

Open in new window

0
 
DS928Author Commented:
No.  I don't have Ajax on the restaurantpage.php yet.  Still trying to figure it out.
0
 
GaryCommented:
Just paste that code above exactly as is (without the script tags in one of your document.ready blocks )- it works, I just got an email (without leaving the page)
0
 
DS928Author Commented:
Thank you.  I am getting somewhat confused here.  This is wha I have for the script.

<script type="text/javascript">
$(function () {
$('#popup-wrapper').modalPopLite({
		openButton: '#clicker',
		closeButton: '#close-btn',
		isModal: true });
});


$(function () {
$("#send").click(function(e){
	e.preventDefault();
	$.ajax({
		type:'POST',
		url:'/Scripts/send_form_email.php',
		data:$(this).closest("form").serialize(),
		success:function(response) { 
			if(response=="Mail Sent."){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
}) 
</script>

Open in new window


And this is on the form...
<form name="contactform" method="POST" autocomplete="off">
        <div align="center" >Enter Your E-Mail Address</div><br />
        <div align="center"><input name="ESend" type="text" id="Esend" maxlength="80" size="30"/></div><br />
        <div align="center"><input name="Send" type="submit" id="send" value="Submit" /></div><br />
        <div align="center"><input name="Cancel" type="button" id="close-btn" value="Cancel" /></div><br />
        </form>

Open in new window


Now when I click "Email Info" The small form to put your email address in does not open.  I'm doing something wrong here.
0
 
GaryCommented:
You have a stray script tag in the js code at the top of the page.

</script>
      
            //$(function () {
                  //$('#popup-wrapper').modalPopLite({
                        //openButton: '#clicker',
                        //closeButton: '#close-btn',
                        //isModal: true });

            //});
0
 
GaryCommented:
Full script should be, (you've disabled the location id so I've added it back in )

$(function () {
$('#popup-wrapper').modalPopLite({
		openButton: '#clicker',
		closeButton: '#close-btn',
		isModal: true });
});


$(function () {
$("#send").click(function(e){
	e.preventDefault();
	var Lid = location.search.match(new RegExp("[\\?&]LocationID=([^&#]*)")).pop();
	$("form").append("<input type='hidden' name='Lid' value='" + Lid + "' >");
	$.ajax({
		type:'POST',
		url:'/Scripts/send_form_email.php',
		data:$(this).closest("form").serialize(),
		success:function(response) { 
			if(response=="Mail Sent."){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
}) 

Open in new window

0
 
DS928Author Commented:
Pasted exactly as put.  Can you try the page to see if it works for you?  I still dont get a response from the Email Info button.  The form to input the email does not open.
0
 
GaryCommented:
Wrap the script in the document.ready function.

$(document).ready(function() {

})

Open in new window

0
 
DS928Author Commented:
Did this, still not opening.

<script type="text/javascript">
$(document).ready(function() {
$(function () {
$('#popup-wrapper').modalPopLite({
		openButton: '#clicker',
		closeButton: '#close-btn',
		isModal: true });
});


$(function () {
$("#send").click(function(e){
	e.preventDefault();
	var Lid = location.search.match(new RegExp("[\\?&]LocationID=([^&#]*)")).pop();
	$("form").append("<input type='hidden' name='Lid' value='" + Lid + "' >");
	$.ajax({
		type:'POST',
		url:'/Scripts/send_form_email.php',
		data:$(this).closest("form").serialize(),
		success:function(response) { 
			if(response=="Mail Sent."){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
})
})
</script>

Open in new window

0
 
GaryCommented:
<script type="text/javascript">
$(document).ready(function() {

$('#popup-wrapper').modalPopLite({
	openButton: '#clicker',
	closeButton: '#close-btn',
	isModal: true
});

$("#send").click(function(e){
	e.preventDefault();
	var Lid = location.search.match(new RegExp("[\\?&]LocationID=([^&#]*)")).pop();
	$("form").append("<input type='hidden' name='Lid' value='" + Lid + "' >");
	$.ajax({
		type:'POST',
		url:'/Scripts/send_form_email.php',
		data:$(this).closest("form").serialize(),
		success:function(response) { 
			if(response=="Mail Sent."){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
})
</script> 

Open in new window

0
 
GaryCommented:
Try that again - missing closing brackets.

<script type="text/javascript">
$(document).ready(function() {
$('#popup-wrapper').modalPopLite({
		openButton: '#clicker',
		closeButton: '#close-btn',
		isModal: true });

$("#send").click(function(e){
	e.preventDefault();
	var Lid = location.search.match(new RegExp("[\\?&]LocationID=([^&#]*)")).pop();
	$("form").append("<input type='hidden' name='Lid' value='" + Lid + "' >");
	$.ajax({
		type:'POST',
		url:'/Scripts/send_form_email.php',
		data:$(this).closest("form").serialize(),
		success:function(response) { 
			if(response=="Mail Sent."){
				alert("Your message has been sent")
			}
			else{
				alert("There was a problem")
			}
		}
	});
})
})
</script> 

Open in new window

0
 
DS928Author Commented:
Thank you. Yeah!  It works!  But the form to input the emal address isn't closing. ...Also I amtrying to take out the alerts.
0
 
DS928Author Commented:
YESS!
I did this to remove the alerts.  Is that OK?

data:$(this).closest("form").serialize(),
            success:function(response) {
                  if(response=="Mail Sent."){
                        //alert("Your message has been sent")
                  }
                  else{
                        //alert("There was a problem")
                  }
0
 
GaryCommented:
Yes, but you should give some indication that an email has been sent.
You should also add in a error routine as well in case there are problems
0
 
DS928Author Commented:
Thank you very much!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.