Inserting variable into PHP header Location URL - javascript

I'm very new to PHP.
I have an HTML membership form that when a user clicks the submit button it goes to a PHP page that compiles the fields passed, sends an email and lastly forwards the user to a "Thank you" Confirmation" html page.
I would like to include two of the form fields into the URL string so that I can then call up in the confirmation page to congratulate the name of the person for joining our club.
Two Questions
How do I concatenate the redirect url to include first name and last name for example:
new_member_confirmation.html?firstname=$firstname&lastname=$lastname
how do I then 'GET' the names in the URL string to display on the confirmation html page. For example "Thank you Bill Smith for becoming a member". I dont have an example of this as I do not know how to call or GET the values from the url string into the HML page
Here is the revised code which does not include every form field variable but gives you the gist of the PHP script.
<?php
// Multiple recipients
$to = 'info#abs.com'; // note the comma
// Form http_post_fields
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$subject = 'New Membership';
$cdateTime = date("l jS \of F Y h:i:s A");
// Message
$message = "
<html>
<head>
<title>New Membership</title>
</head>
<strong>From:</strong> \n $firstname \n $lastname <br>
<strong>Email:</strong> \n $email <br>
<strong>Date/Time Submitted:</strong>\n $cdateTime
</font></p>
<body>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Club Name <info#domain.com>'; // include a comma for more than one recipiant
$headers[] = 'From: Club Name <info#domain.com>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers)) or die("Email was not sent!");
// Here is where the user gets sent to the page below. Id like to append the $firstname $lastname variables into the URL string
header('Location: membership_confirmation.html');
// I thought I could create a URL string variable above like this --
// $urString = "Location: membership_confirmation.html?membername=$firstname \n $lastname";
// and then add it to the last portion of the script like this
// header($urString);
// Unfortunately, that doesn't work after I tried testing it.
?>

You you can concatenate to the url in your header statement, and use urlcode for your variables:
header('Location: membership_confirmation.html?firstname='.urlencode($firstname).'&lastname='.urlencode($lastname));
The header needs to reference a PHP file instead of an html file:
header('Location: membership_confirmation.php?firstname...
In the membership_confirmation.php file, get the variables via $GET similarly to how you are getting them from $POST in your current file, e.g.:
$firstname = $_GET['firstname'];

Ok here is what I came up with.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var url_string = "https://eaa309.club/membership_confirmation.html?firstname=Kelly&lastname=Brady";
var url = new URL(url_string);
var firstname = url.searchParams.get("firstname");
var lastname = url.searchParams.get("lastname");
//console.log(c);
//Write it out
document.getElementById("demo").innerHTML =
"Page path is: " + firstname + " " + lastname;
</script>
</body>
</html>

Related

PHP form do not show ÆØÅ

So I have made a contact form on my website. Everything works like a charm. However, the result beeing delivered to the email fail to display the ØÆÅ letters and instead only shows as weird symbols.. I have tried everything and feel really lost.
<?php
if (isset($_POST['submit']))
$sword = $_POST['swordy'];
$check = $_POST['check'];
$mailFrom = $_POST['mail'];
$message = $_POST['message'];
$ccname = $_POST['ccname'];
$droppy1 = $_POST['droppy1'];
$tel = $_POST['tel'];
$subject = 'Bryllupsinvitasjon ';
$mailTo = "your#email.com";
$headers = "From: ".$mailFrom;
$txt = " Du har motatt svar på bryllupsinvitasjon fra: ".$ccname."\n\n Svar: $check \n\n Telefonnummer: $tel\n\n Allergier: $droppy1\n\n Andre allergier/intolleranser/spørsmål/henvendelser: $message";
mail($mailTo, $subject, $txt, $headers);
header("Location: index.html?mailsendt");
?>
Try inserting the corresponding Unicode or HTML code for your specific character. I believe all three of your indicated chars are on this page: https://www.rapidtables.com/code/text/unicode-characters.html
Your email headers here aren't specifying UTF-8 encoding. You'll need to add that into the headers, specifically as part of the Content-Type header, like so:
Content-Type: text/html; charset="UTF-8"
With that header, the email should display the characters properly.

inserting the php sendmail fuction into a confirm button within a pop up box

I am trying to use the sendmail function in php threw a pop up box. i have gotten as far as making the sendmail function and the pop up to work separately. but i haven't been able to figure out how to connect the sendmail in the right way. below is the last working git version i have. any help would be wonderful.
{
<tr>
<th align="center">Instrument Serial Number:</th>
<td align="left"><input type="text" class="cInstTravText" name="SerialNumber" id="idSerialNumber"/></td>
<button onclick="drop_check()">comfirm</button>
<p id="drop_check"></p>
<script>
function sendEmail()
{
$to = 'jonsrod1992#gmail.com';
$subject = 'Test email using PHP';
$message = "test";
//$message = 'hello world.\n\n this is a test for functionality\n\n this is the first try\n place instrument serial Number here--> '<$modelNumber>'<-- there.';
$headers = 'From: jonr#twobtech.com' . "\r\n" . 'Reply-To: jonr#twobtech.com' . phpversion();
mail($to, $subject, $message, $headers, '-fwebmaster#example.com');
}
function drop_check() {
var x;
if (confirm("transfer and send email!") == true) {
x = "transfered and email sent!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("drop_check").innerHTML = x;
}
</script>
</tr>
The approach you're attempting isn't going to work. The php on your page runs first (server side), and then your pop-up is triggered using JavaScript. This means you'll need to send the response from the pop-up to another php page which then handles the sendmail. You can do this via POST in a form submission, or better yet, using an AJAX call, like so (this goes between script tags, preferably at the top or bottom of your page, not in the middle of your HTML):
if (confirm("transfer and send email!")) {
//if needed, get values from one or more HTML inputs like so:
var stuff = $('#someInputId').val();
$.ajax({
type: "POST",
url: "sendmail.php",
data: { data: stuff } //if you don't need to send any data from your HTML elements this can be ommitted
}).success(function() {
//optional: let the user know email was sent
});
}
You would then put your sendmail code in sendmail.php. If you're sending any data in the AJAX call, you can retrieve it from $_POST. sendmail.php would look something like:
$body = isset($_POST['stuff']) ? $_POST['stuff'] : 'no stuff';
$to = 'jonsrod1992#gmail.com';
$subject = 'Test email using PHP';
$headers = 'From: jonr#twobtech.com' . "\r\n" .
'Reply-To: jonr#twobtech.com' . "\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$subject,$body,$headers);
Maybe I'm missing something, but... it looks like you may be trying to just throw PHP into your javascript. That is not going to work. Also, if this is just weird reformatting of the code, the sendEmail function is not being called.

jQuery $.post() Logging Me Out On Key Down

I have a dynamic drop down search bar which searches through the members of a data base inside of a form on my webpage. In order to view this webpage you must log in first. When I built the site on my domain everything works just fine. However when I transferred my files over to a different domain and configed it with an identical database everything works perfect, except my dynamic search in this form. If I type my name (sometime the odd different name with work) in the search everything works fine, but if i type anyone else it seems to stay on the page as it should, but it logs me out and reload the login form on top of everything else including my form I was typing on. I am using jQuery .post() to make the search dynamic. I will provide code below
index.php
<script>
// this is the jQuery function used to post to the search document on key up
function searchUserQ(){
var searchTxt = $("input[name='userSearch']").val();
console.log(searchTxt);
if (searchTxt != '') {
$.post("includes/search.php", {searchVal:searchTxt},
function(output){
$("#userResults").html(output);
});
}
}
</script>
<h1 class="editUser">Edit User</h1>
<form class="editUser" action="index.php" method="post">
<h1>Search For Employee</h1>
<input type="text" name="userSearch" id="userSearch" placeholder="Search For Employee By First Name" onkeyup="searchUserQ();" />
<submit type="submit" />
<div id="userResults">
</div>
</form>
Search.php
<?php
// Connect To Secure Login
$cfgProgDir = '../phpSecurePages/';
include($cfgProgDir . "secure.php");
//These are the includes needed to make the php page run
// this file connects to the database
include("connect.inc.php");
if(isset($_POST['searchVal'])){
// turn that the user searched into a varible
$searchQ = $_POST['searchVal'];
// delete any symbols for security
$searchQ = preg_replace("#[^0-9a-z]#i", "", $searchQ);
$output = "";
$link = "";
$searchArray = array();
$searchIndex = 0;
// Search through these columns inside the main database
$userSearchQuery = mysql_query("SELECT * FROM dealerEmployees WHERE
firstName LIKE '%$searchQ%'
");
// count the number of results
$userCount = mysql_num_rows($userSearchQuery);
if($userCount == 0){
// $output = "There Were No Search Results";
}else{
while($row = mysql_fetch_array($userSearchQuery)){
// define dynamic varibles for each loop iteration
$id = $row['id'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$address = $row['address'];
$phone = $row['phone'];
$email = $row['email'];
$password = $row['password'];
$permission = $row['permission'];
$photo = "images/" . $row['profilePhoto'];
$output .= "<li><div class='employeeSearch' style=\"background: url('$photo'); width: 75px; height: 75px\"></div><h6>" . $firstName . "</h6>" . " " . "<h6>" . $lastName . "</h6><a href='#' class='employee' data-firstName='$firstName' data-lastName='$lastName' data-address='$address' data-phone='$phone' data-email='$email' data-password='$password' data-permission='$permission' data-id='$id'>Select Employee</a></li>";
}
}
}
echo $output;
Can you try this?
> "SELECT id, firstName, lastName, address, phone, email, password,
> permission profilePhone FROM dealerEmployees WHERE
> firstName = '".$searchQ."' Limit 1"
Maybe the like condition is giving more than 1 result.
Maybe you could make a select count(id) as id from dealerEmployees where firstName = '".$searchQ."' and check the count with an if clausule. Maybe the problem you have is too many users with the same firstName.
So After some testing i found out what was happening. When the search would load the search results it would change the password variable in the session to the password of the user coming up in the search since both variables had the same name, all I needed to do was change the var name of the password variable in the search results to be different than the sessions password.
Thanks for all the help!!!

php form stay on page with div showing close form

I have the following form that works except for the success message staying on the same page.
I keep racking my brain, but at this point it is mush.
**Problem
I need to have the form close and show the 'success' DIV when the form is submitted.
Right now the only thing I can do is get it to go to a thanks.php page by using a header.
all the code is here at jsfiddle: http://jsfiddle.net/webs4me/hyArd/1/
except the send.hello.php which is below: - Thanks
<?php
// Clean up the input values
foreach($_POST as $key => $value) {
if(ini_get('magic_quotes_gpc'))
$_POST[$key] = stripslashes($_POST[$key]);
$_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}
// Honeypot don't send - THIS WILL BE HIDDEN LATER
if(!empty($_POST["confirm_email"])) {
header("location:spam.php");exit;
}
// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$confirm = $_POST["confirm_email"];
$phone = $_POST["phone"];
$message = $_POST["message"];
// Send the email *********** enter your email address and message info
$to = "myemail#myemail.com";
$subject = "Website message: $name";
$message = "From:\n$name\n\nEmail:\n$email\n\nPhone:\n$phone\n\nMessage:\n$message";
$headers = "From: $email";
mail($to, $subject, $message, $headers);
header('location: thanks.php');
?>
Since you're already using JQuery, use $.POST:
http://api.jquery.com/jQuery.post/
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
data would be constructed from the values of all the form's inputs.
url would be the hello.php page
You'd add either an onsubmit function to the form, or take out the submit button and add a regular input button with an onclick call to a function that builds data and calls $.POST

How to complete $.get() when a form is submitted using jQuery

I am using a third party shopping cart that sends a registration form to a .cgi script.
I want to send information from that form to me, and the customer via a jQuery $.get() function call.
The $.get calls a registration.mail.php script.
The problem is that the form submitting seems to cancel out the ajax call before the ajax call can be completed.
I can think of some inelegant solutions, and I have decided, because I'm about to travel, to use a counter and make the user click 'Register' twice. This solution hurts my soul obviously.
Here's the Javascript, that lives in the footer:
<script type="text/javascript">
var getsuccess = false;
$(document).ready(function() {
$('form#registerWholesale').bind('submit', function() {
$email = $('#email').val();
$username = $('#contactname').val();
$company = $('#company').val();
$phone = $('#billphone1').val();
$message = "A new customer has registered at the wholesale website. \n ";
$message += "They have the username of: " + $username + ". \n";
$message += "Their company is: " + $company + ". \n";
$message += "Their email is: " + $email + ". \n";
$message += "Their phone is: " + $phone + ". \n";
$message += "Please help them ASAP. You can access the back end of the site at: http://location of website admin backend";
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
getsuccess = true;
});
if (getsuccess) {
return true;
}else{
return false;
}
});
</script>
And here is the registration.mail.php code.
<?php
//Vendor email (to us)
$to = "ouremail#OurCompany.com";
$subject = "URGENT--New Registration--URGENT";
$message = htmlentities($_GET['message'], ENT_QUOTES, 'UTF-8');
//$message = $_GET['message'];
$from = htmlentities($_GET['from'], ENT_QUOTES, 'UTF-8');
//$from = trim($_GET['from']);
$headers = "From: $from";
mail($to,$subject,$message,$headers);
//echo "Mail Sent.";
//Customer email (to them)
$to_cust = htmlentities($_GET['email'], ENT_QUOTES, 'UTF-8');
$subject_cust = 'OurCompany Online Wholesale Account Request Recieved';
$message_cust = "Thank you for you interest in OurCompany's new wholesale website. \n\n
We have received your request to create an account. In order to obtain a wholesale account, a OurCompany representative must verify your account information and details by telephone. OurCompany will contact you within 1 business day at the telephone number that we have on file, or feel free to give us a call at 1-xxx-xxx-xxxx anytime if you would like a more rapid approval. \n\n
Thanks Again ~ OurCompany";
$headers_cust = "From: orders#OurCompany.com";
mail($to_cust,$subject_cust,$message_cust,$headers_cust)
?>
Thank you!
Your Ajax get handler sets up an asynchronous callback. In other words, this piece of code:
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
getsuccess = true; <---- THIS
});
The "THIS" line is only called when the Ajax call returns a result. Since you are sending an actual email, it may take a long time.
So, by the time you run this:
if (getsuccess) {
return true;
}else{
return false;
}
The Ajax call has never completed, and this always returns false.
You should basically just decide whether you want to submit the form with Ajax or not, and only use one of those. If you want to do Ajax, the Submit event handler should always return False.
EDIT: I did not realize that the mail sending and form submitting are two different actions, and two separate server calls. (You are not showing the rest of your app, but this is the idea that I get from other answers.) This is bad design that may lead to inconsistent results and bad data. You should redesign your app so that both of these things are handled on server side in the same place, so that the web app only makes one call, no matter if this one call is by Ajax or regular form submit.
One solution is to bind the event to the button click , prevent the default action of the click so the form does not submit, then finally submit the form in the .get callback.
N.B As Jaanus suggests you should really look at the app design and send the mail and save the cart in the same call. What happens if the email gets sent then the form submission action fails?
$(document).ready(function() {
$('#yourSubmitButton').click( function(ev) {
//prevent form submission
ev.preventDefault();
$email = $('#email').val();
$username = $('#contactname').val();
$company = $('#company').val();
$phone = $('#billphone1').val();
$message = "A new customer has registered at the wholesale website. \n ";
$message += "They have the username of: " + $username + ". \n";
$message += "Their company is: " + $company + ". \n";
$message += "Their email is: " + $email + ". \n";
$message += "Their phone is: " + $phone + ". \n";
$message += "Please help them ASAP. You can access the back end of the site at: http://location of website admin backend";
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
//all is well, submit the form
$('#yourForm').submit()
});
});
At the very least, rather than make them click twice, why dont you make the success callback of the $.get submit the form again for them?
$('form#registerWholesale').bind('submit', function() {
if (getsuccess) {
return true;
} else {
$email = $('#email').val();
$username = $('#contactname').val();
$company = $('#company').val();
$phone = $('#billphone1').val();
$message = "A new customer has registered at the wholesale website. \n ";
$message += "They have the username of: " + $username + ". \n";
$message += "Their company is: " + $company + ". \n";
$message += "Their email is: " + $email + ". \n";
$message += "Their phone is: " + $phone + ". \n";
$message += "Please help them ASAP. You can access the back end of the site at: http://location of website admin backend";
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
getsuccess = true;
$('form#registerWholesale').submit();
});
return false;
}
});
Have you tried putting the ajax call in a function, and hooking the onSubmit of the form?
onsubmit="myajaxcallFunc(); return true;"
This is commonly used to stop the submission, with return false, but in this case it may do what you want.
The callback you're passing to $.get will be evaluated after the AJAX request. Since AJAX is asynchronous, your code will continue to evaluate in the mean time, which means your if-condition with the two return-statements will always evaluate before the AJAX callback is called.
What you want to do is for the submit listener to always return false, and in the AJAX callback, you conditionally trigger $('form#registerWholesale').submit();
Of course there's a design consideration here as well: you may want the e-mail sending and wholesale registration to be atomical. If the mail is sent, you always want the stuff that happens in form submit to happen as well, right? In that case you want to move either the email sending to the form postback, or the wholesale registration to the AJAX callback, so it's all handled in one step.

Categories