Match JS string to PHP string - php

I would like to "export" a JS string to a PHP processing script and match them. When they match, i would like to go through a simple validation process and if the validation is successful, send off an email.
To put this in perspective, here is what my code looks like so far:
I have about 40 divs each represnting an item. The below html is an example of just one
HTML
<div class="Post odd postStyles">
<input class="cheap" data-mail="email#sample.com" name="option" type="radio">
<article>
<h6 class="casinoHeading">Grosvenor Casino Birmingham</h6>
<p class="">84 Hill Street, Birmingham, B5 4AH</p>
</article>
</div>
As you can see, i am using html5 data attributes for the string i want to use.
I then retrieve this string using the Jquery data() function.
Please see below:
$("input").click(function(){
var mail = $(this).data();
console.log(mail);
})
And this is the bit in which i get lost, unfortunately. I would like to be able to pass the variable mail to a php script which then runs a loop and finds the correct string.
Runs through some simple validation and then sends off an email.
Here is the PHP script I've written:
<?php
$emails = array(
"email#sample.com",
"email#sample1.com",
"email#sample2.com",
);
foreach($emails as $val) {
print $val;
}
if(isset($_POST ['Name'], $_POST ['Telephone'], $_POST ['Position'], $_POST['Email'], $_POST ['Noparty'], $_POST ['Message'], $_POST ['Adress'], $_POST ['PostCode'],
$_POST ['Date'], $_POST ['Time'])) {
var errors = array();
$name = htmlentities(mysql_real_escape_string(strip_tags($_POST['Name'])));
$telephone = htmlentities(mysql_real_escape_string(strip_tags($_POST['Telephone'])));
$email = strip_tags(mysql_real_escape_string(htmlentities($_POST['Email'])));
$position = strip_tags(mysql_real_escape_string(htmlentities($_POST['Position'])));
$noparty = strip_tags(mysql_real_escape_string(htmlentities($_POST['Noparty'])));
$message = mysql_real_escape_string(htmlentities(strip_tags($_POST['Message'])));
$address = mysql_real_escape_string(htmlentities(strip_tags($_POST['Adress'])));
$postcode = mysql_real_escape_string(htmlentities(strip_tags($_POST['PostCode'])));
$date = mysql_real_escape_string(htmlentities(strip_tags($_POST['Date'])));
$time = mysql_real_escape_string(htmlentities(strip_tags($_POST['Time'])));
if(empty($name) || empty($telephone) || empty($email) || empty($position) || empty($noparty) || empty($message) || empty($address) || empty($postcode) || empty($date)
empty($time)){
$errors [] = "<span class='error'>Please fill in the required fields!</span>";
}else{
if(strlen($name)<=2 || strlen($name)>25){
$errors [] = "<span class='error'>Sorry, username should be between 2 and 25 Charachters</span>";
}
}
//If all runs through sucessfully - send email
}
?>
Essentially i want to be able to send that variable to PHP(maybe with an AJAX request), check it and then run some validation with it.
Can anyone help out?
Much appreciated,
Antonio

Sorry I truly don't understand your point.You can use $.post to send a form and then return JSON by PHP with errors or status OK.
You can grab attributes this way:
var mail;
$("input").click(function(){
mail = $(this).val();
if(!mail)
mail = $(this).attr("data-mail");
});
$("#submit-button").on("click", function(e)
{
e.preventDefault();
$.post({});
});
You should do this with traditional way: html form, hidden inputs and simple submit button.

Related

Send array values in PHP form

I have a HTML form with embedded PHP code that creates a checkbox for each value contained in an array. Just like this:
<?php
$rows = array_map( 'str_getcsv', file( 'file.csv' ) );
$header = array_shift( $rows );
foreach ( $rows as $row ) {
echo '<input type="checkbox" id="'.$row[0].'" name="'.$row[0].'">
<label for="'.$row[0].'">'.$row[0].'</label>
<input type="number" name="'.$row[0].'" placeholder="Some text">';
}
?>
Now, I want to send this form using this code, which is inserted into another PHP file:
<?php
if( isset( $_POST ) == true && empty( $_POST ) == false ) {
$account = $_POST['account'];
$investment = $_POST['row[0]'];
$password = $_POST['password'];
$formcontent=" Account: $account \n $row[0]: $investment \n Password: $password";
$recipient = "my#email.com";
$subject = "My Form";
$mailheader = "From: My Form <my#form.com>";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Some text";
}
?>
But it doesn't work. When you click on submit button the form does nothing.
I've checked it with success with HTML-only code, so I guess I'm making a mistake with PHP.
For those interested, here's a link to my form: Example
EDIT: I've removed preventDefault, as pointed by #DavidJorHpan, but I'm still stuck. I'm unable to make my form.php send $row[0] to my email.
Because you use preventDefault so it will never submit form until you code for submitting form
$("button").click(function(e) {
e.preventDefault();
});
You can remove that code or add code like
$('form').submit();
As David JorHpan pointed out in the second answer, you've got to remove preventDefault() from the button click event. That prevents the form from being submitted.
For every checkbox you have a corresponding number input field. Although possible, its not a good practice to have spaces in your 'name' attribute values. Try replacing those spaces with dashes or underscores. For example you can do something like below:
name="'.str_replace(' ','_',$row[0]).'"
and same can be done to id attribute values.
Your form submit check should work but it will make more sense if you change that as follows:
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// process here
}
After doing these changes try loading the page and see how it goes.

PHP form validation that includes SUBMIT button

I have been trying to find a way to validate email in my PHP code. I can only give you parts of my code cause it is really long. What I want to do is to have a person enter their email address by clicking a submit button and if they have entered their email in an unacceptable format, an error message appears. But my problem is: how can I COMBINE a tag WITH "function validate email($field)"? In other words, I know how to combine (PART A) and (PART B), that is easy enough. But what I really want to do is combine (PART B) with (PART C) and not use (PART A) at all. Is that possible? Can I somehow include "isset" inside "function validate email($field)"? I must have a submit button and I must be able to validate the email.
(PART A) <?php //formtest2.php
if (isset($_POST['email'])) $email = $_POST['email'];
else $email = "(Not entered)";
?>
(PART B) <?php
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
?>
(PART C) <body>
Your email is: $email<br>
<form method="post" action="brownuniversity.php">
What is your email address?
<input type="text" name="email">
<input type="submit">
</form>
</body>
Hi first of all your gonna want to change this whole thing,
function validate_email($field)
{
if ($field == "") return "No email was entered<br>";
else if (!((strpos($field, ".") > 0) &&
(strpos($field, "#") > 0)) ||
preg_match("/[^a-zA-Z0-9.#_-]/", $field))
return "The email address is invalid<br>";
return "";
}
To this little bit.
function validate_email( $field ){
if (preg_match("/^[^#]+#[a-zA-Z0-9._-]+\.[a-zA-Z]+$/", $field)){
return true;
}
return false;
}
You'll have to do the error messages elsewhere, but this is more portable. ( and I give you a much better Regx for emails ), now you can just do this
if(isset($_POST['email'])){
$email = trim( $_POST['email'] ); //remove any whitespaces from pasting email.
if(validate_email($email)){
//send mail or whatever
}else{
//show errors
}
}
You will still have to check if isset( $_POST['email'] inside the validation isn't really the place to check for it, it should only be concerned with if the data is valid or not, not if there is no data. Also you'll need to check that the form was posted anyway before calling the function and the isset serves both these needs. I updated the answer, you don't really need a validation message on the case that it is not set, because if that is the case they didnt submit the form, it should always be set on form submission.

Position PHP code with CSS

I have a form that is positioned on the page with HTML, if the user completes the form then they are thanked with a PHP message. Because the form is positioned with <form id="formIn"> CSS the PHP text is now in the wrong position, does anyone have an idea how this can be positioned so that the PHP echo text is nest to the form?
I have tried to include the code in PHP, i.e.
<div id=\"text\">
But no joy.
Code used so far is:
<?php
echo "* - All sections must be complete"."<br><br>";
$contact_name = $_POST['contact_name'];
$contact_name_slashes = htmlentities(addslashes($contact_name));
$contact_email = $_POST['contact_email'];
$contact_email_slashes = htmlentities(addslashes($contact_email));
$contact_text = $_POST['contact_text'];
$contact_text_slashes = htmlentities(addslashes($contact_text));
if (isset ($_POST['contact_name']) && isset ($_POST['contact_email']) && isset ($_POST['contact_text']))
{
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_text)){
$to = '';
$subject = "Contact Form Submitted";
$body = $contact_name."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject,$body,$headers))
{
echo "Thank you for contacting us.";
}else{
echo 'Error, please try again later';
}
echo "";
}else{
echo "All sections must be completed.";
}
A good way for doing this is to create a div for displaying messages in the form page and return back from the php script to the form page including form.html?error=email or form.html?success to the url. Then with javascript you can identify when this happens and display a message or another.
Comment if you need some code examples.
EDIT:
Imagine your php script detects that email field is not filled, so it would return to the form webpage with a variable in the url:
<?php
if(!isset($_POST["email"]){
header("location:yourformfile.html?error=email")
}
?>
Then, in your form webpage you have to add some javascript that catches that variable in the URL and displays a message in the page:
Javascript:
function GetVars(variable){
var query = window.location.search.substring(1); //Gets the part after '?'
data = query.split("="); //Separates the var from the data
if (typeof data[0] == 'undefined') {
return false; // It means there isn't variable in the url and no message has to be shown
}else{
if(data[0] != variable){
return false; // It means there isn't the var you are looking for.
}else{
return data[1]; //The function returns the data and we can display a message
}
}
}
In this method we have that data[0] is the var name and data[1] is the var data. You should implement the method like this:
if(GetVars("error") == "email"){
//display message 'email error'
}else if(GetVars("error") == "phone"){
//dislpay message 'phone error'
}else{
// Display message 'Success!' or nothing
}
Finally, for displaying the message I would recommend creating a div with HTML and CSS and animate it to appear and disappear with jQuery. Or just displaying an alert alert("Email Error");
Just create a <div> before or after your form and put IF SUBMIT condition on it.
Like,
<?php
if(isset($_POST['submit']))
{ ?>
<div>
<!-- Your HTML message -->
</div>
<?php } ?>
<form>
</form>

Implement spam-block into contact form 7

I am currently looking into adding a bit of code into both the front end and back end of my form, but I am having trouble figuring out how to do so.
This is the front end code
<li id="user"> <label for="username">Username</label> <input type="text" name="username"> </li>
I will display none that and use it as a honeypot for spam bots.
However, the next bit of code I need to implement is:
<?php if( !isset($_POST['name'])) { die("No Direct Access"); } // Make sure the form has actually been submitted
$name = $_POST['name'];
$email = $_POST['email'];
$spam = $_POST['username']; // This is our Honeypot field if($spam) { // If the Honeypot field has been filled in die("No spamming allowed bitch!"); }
else { // Process the form like normal } ?>
Now the point being is $name and $email are dynamic fields in contact form 7. What could I do to make those avail in contact form 7 as var for this script?
Thanks in advance!
Inside of /contact-form-7/includes/classes.php you can add your code and mark it as spam if you want.
Line 432 under function spam() add lines that follow something similar to this:
if (isset($_POST['username'])) {
$spam = true;
}

Trying To Create A Javascript Alert Window That Doesn't Reload The Page When OK Is Clicked

I have a PHP form that I've set up with a POST method. When all the fields aren't filled out I have a Javascript alert box that pops up and states 'Please fill out all fields!' When I click 'OK' on the alert window it reloads the form behind it clearing all the data that was entered. Is there a function that can keep the alert box's OK button from reloading the entire page? Here's my code:
<?php
if (isset($_POST['brandname']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['website'])){
$brandname = $_POST['brandname'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$website = $_POST['website'];
if(!empty($brandname) && !empty($firstname) && !empty($lastname) && !empty($email)){
$to = 'matt#miller-media.com';
$subject = 'Submission Form';
$body = $firstname;
$headers = 'From: '.$email;
if (#mail($to, $subject, $body, $headers)){
}
}else{
echo '<script type="text/javascript">
window.alert("Please fill out all fields!")
</script>';
}
}
?>
You are alerting your user after posting response ... in this case I would re-post the whole form again with its values set to $_POST or variables that were set using it, for example :
<input type='text' name='brandname' value='<?php echo $_POST['brandname'];?>' />
or :
<input type='text' name='brandname' value='<?php echo $brandname; ?>' />
and so on
But in this case I recommend using client-side validation on the form (Using javascript)
Yeah i assume you need something like this:
<script type="text/javascript">
function do_some_validation(form) {
// Check fields
if (! /* Contition 1 */ ) return false;
if (! /* Contition 2 */ ) return false;
if (! /* Contition 3 */ ) return false;
form.submit();
}
</script>
<form onsubmit="do_some_validation(this) return false;" action="script.php" method="post">
// Fields
</form>
This will only submit the form once all JavaScript conditions in do_some_validation are met... Please note this is not advised over and above PHP validation, this should be used purely for comfort for the user not having to submit the page when there's something Javascript can validate against
For any further PHP validation messages, you can either pass variables into GET or SESSION, eg.
<?php
session_start();
if (count($_POST)) {
if (!/* Condition 1 */) $_SESSION['error'] = "Message";
if (!isset($_SESSION['error'])) {
// Proceed
} else header("Location: script.php");
}
?>
On the page:
<?php if (isset($_SESSION['errir'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
} ?>
Since your code sample is PHP-code, it seems that you are posting the form and validate it server-side, and then you show an alert if any field is empty? In that case, the page has already reloaded, before the alertbox is shown. You are mixing server-side and client-side code.
If you want to show an alert box if the user hasn't filled in all the fields (without reloading the page), you will have to do the validation with JavaScript. You should still keep your PHP-validation as well though!
If you use jQuery for instance, you could do something like this:
$("#your-form-id").submit(function(){
// Check all your fields here
if ($("#input-field-1").val() === "" || $("#input-field-2").val() === "")
{
alert("Please fill out all fields");
return false;
}
});
It can of course be done without jQuery as well. In that case you can use the onsubmit attribute of the form tag to call a JavaScript function when the form is posted, and within that function you do the validation of the form, show an alert box if any field is empty, and then return false from the function to prevent the form from being posted to the server.

Categories