Send data to php file with javascript on submit - javascript

so basically, when someone clicks the submit input, I want to retrieve values from various inputs and spans using javascript, then send it to php using $post to then send it by email. I have already tried to delete all the javascript code (except the preventdefault and the click function) and replacing it by a alert, and when I click submit, the alert does execute as it should. But now i'm trying to figure out how to make retrieve all this data and send it by email.
I have a live example here, if you want to see what i'm trying to do.
Thanks
<script type="text/javascript">
$("#submit").click(function (e) {
e.preventDefault();
var PrimaryParentName;
var SecondaryParentName;
var PrimaryEmail;
var SecondaryEmail;
var PrimaryPhone;
var SecondaryPhone;
var Address;
var ChildName;
var ChildBirth;
var ChildAllergies;
var ChildSchool;
var ChildLevel;
var UniformSize;
var PreferedPositions;
PrimaryParentName = document.getElementById("first_parent_name")
.value;
if (document.getElementById("second_parent_name").value ==
null || document.getElementById("second_parent_name")
.value == "") {
SecondaryParentName = 'N/A';
} else {
SecondaryParentName = document.getElementById(
"second_parent_name").value;
}
SecondaryEmail = document.getElementById("first_email")
.value;
if (document.getElementById("second_email").value ==
null || document.getElementById("second_email")
.value == "") {
SecondaryEmail = 'N/A';
} else {
SecondaryEmail = document.getElementById(
"second_email").value;
}
PrimaryPhone = document.getElementById("first_phone")
.value;
if (document.getElementById("second_phone").value ==
null || document.getElementById("second_phone")
.value == "") {
SecondaryPhone = 'N/A';
} else {
SecondaryPhone = document.getElementById(
"second_phone").value;
}
Address = document.getElementById("address")
.value;
ChildName = document.getElementById("child_name")
.value;
ChildBirth = document.getElementById("child_date")
.value;
ChildAllergies = document.getElementById("child_allergies")
.value;
ChildSchool = document.getElementById("school")
.value;
ChildLevel = document.getElementById("uniform_size")
.value;
UniformSize = document.getElementById("leveldescription")
.innerHTML;
PreferedPositions = document.getElementById("Goalie")
.value;
alert(PreferedPositions + UniformSize + ChildLevel);
$.post('registration.php', {
PostPrimaryParentName: PrimaryParentName,
PostSecondaryParentName: SecondaryParentName,
PostPrimaryEmail: PrimaryEmail,
PostSecondaryEmail: SecondaryEmail,
PostPrimaryPhone: PrimaryPhone,
PostSecondaryPhone: SecondaryPhone,
PostAddress: Address,
PostChildName: ChildName,
PostChildBirth: ChildBirth,
PostChildAllergies: ChildAllergies,
PostChildSchool: ChildSchool,
PostChildLevel: ChildLevel,
PostUniformSize: UniformSize,
PostPreferedPositions: PreferedPositions
}, function () {});
});
</script>
<?php
$PrimaryParentName=$_POST['PostPrimaryParentName'];
$SecondaryParentName=$_POST['PostSecondaryParentName'];
$PrimaryEmail=$_POST['PostPrimaryEmail'];
$SecondaryEmail=$_POST['PostSecondaryEmail'];
$PrimaryPhone=$_POST['PostPrimaryPhone'];
$SecondaryPhone=$_POST['PostSecondaryPhone'];
$Address=$_POST['PostAddress'];
$ChildName=$_POST['PostChildName'];
$ChildBirth=$_POST['PostChildBirth'];
$ChildAllergies=$_POST['PostChildAllergies'];
$ChildSchool=$_POST['PostChildSchool'];
$ChildLevel=$_POST['PostChildLevel'];
$UniformSize=$_POST['PostUniformSize'];
$PreferedPositions=$_POST['PostPreferedPositions'];
$to='email#gmail.com';
$subject= 'Nouvelle inscription pour le CSEO';
$message="<span style='font-size: 26px'><b>Contact information</b></span>"."Primary parent's name: ".$PrimaryParentName."\n"."Primary parent's email: ".$PrimaryEmail."\n"."Primary parent's phone number: ".$PrimaryPhone."\n\n"."Secondary parent's name: ".$SecondaryParentName."\n"."Secondary parent's email: ".$SecondaryEmail."\n"."Secondary parent's phone number: ".$SecondaryPhone."\n\n"."Address: ".$Address."\n <hr> \n"."<span style='font-size: 26px'><b>Child's information</b></span>"."\n"."Child name: ".$ChildName."\n"."Child's date of birth: ".$ChildBirth."\n"."Allergies: ".$ChildAllergies."\n"."Child's school: ".$ChildSchool."\n"."Child's level of experience: ".$ChildLevel."\n"."Prefered positions: ".$PreferedPositions."\n"."Uniform size: ".$UniformSize;
mail($to, $subject, $message);
?>

Alright I solved it, the problem was with the if in before the $post.
if (document.getElementById("second_phone").value ==
null || document.getElementById("second_phone")
.value == "") {
SecondaryPhone = 'N/A';
} else {
SecondaryPhone = document.getElementById(
"second_phone").value;
}
I don't know what the exact issue was but it works without it and i'm fine without them.

Related

Woocommerce: How to show Product Attribute name and Category name on title

Using the answer provided in this thread (Woocommerce: How to show Product Attribute name on title when in a category page and "filtering" products via '?pa_attribute=' on address bar) I would like to display the category as well as the attribute name. I have a separate JS function that is currently updating the page_title when a filter is applied but that is only loading after ajax has finished. So in this event it would not load till after the filter is applied.
In the event that a user uses the nav to get to the category, currently only the attribute is displaying in the page_title. Looking to also display the category. I believe this would work out of the box if I organized my products in to subcategories but due to how the filtering is being set up I elected not to go this route. I can explain in further detail why I had to take this approach if anyone is interested.
I have left the commented out code in so that you can see the approach I was attempting to take. If this is confusing can edit it out.
add_filter( 'woocommerce_page_title', 'custom_woocommerce_page_title', 15, 2 );
function custom_woocommerce_page_title( $page_title ) {
if ( is_archive() ) {
$exists_attr = false;
foreach ( $_GET as $index => $value ) {
if ( substr( $index, 0, 3 ) === 'pa_' ) {
//$cat_id = wc_category_taxonomy_id_by_name( $index );
$attr_id = wc_attribute_taxonomy_id_by_name( $index );
if ( $attr_id === 0 && $cat_id ) {
continue;
}
if ( ! $exists_attr /* && ! $exists_cat */) {
$exists_attr = true;
//$exists_cat = true;
$page_title .= ' ';
} else {
$page_title .= ' ';
}
//$terms = get_the_terms( $post->ID, 'product_cat' );
$term = get_term_by( 'slug', esc_html( $value ), $index );
$page_title = /*$terms->name . ': ' . */ $term->name;
}
}
}
// Need to add category name after attribute term name.
return $page_title;
}
Also, I have included the JS I am using to apply page_title in the event a filter selection occurs. Ideally it would be great if I could handle it all via a JS file as I am much more familiar with JS and just starting to dive in to php. I am using the WOOF - WooCommerce Products Filter and modifying some of the code to accomplish what I need.
(function() {
var machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
var processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
var optionMachine = machineEl.querySelector("option[selected='selected']");
var optionProcess = processEl.querySelector("option[selected='selected']");
var machineValue = optionMachine.innerHTML;
var processValue = optionProcess.innerHTML;
var result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
if (machineValue != 'Product Machine' && processValue != 'Product Processing') {
result.innerHTML = machineValue + " " + processValue;
}
else if (machineValue != 'Product Machine') {
result.innerHTML = machineValue;
}
else if (processValue != 'Product Processing') {
result.innerHTML = processValue;
}
})()
So was able to get this to work by taking my JS and adding it in as a script within my functions.php. So essentially I was able to eliminate the custom_woocommerce_page_title filter.
Function.php
<?php
add_action('wp_footer', 'onLoadPageTitle');
function onLoadPageTitle() {
?>
<script>
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
</script>
<?php
}
?>
Then the woof woocommerce filter js that updates the title when a new select occurs after the AJAX.
(function() {
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
})()
will probably pare it down by just calling the script function from within the woof js after ajax.

javascript functions executing without being called

I have JavaScript function that is supposed to called OnClientClicking but is getting called on page load.
function SaveClientClicking(sender, eventArgs)
{
var FirstName = $find("<% = FN.ClientID %>");
var FNtext = FirstName._value;
var LastName = $find("<% = LN.ClientID %>");
var LNtext = LastName._value;
var Email = $find("<% = email.ClientID %>");
var Emailtext = Email._value;
if (FNtext == "")
{
alert("First Name can't be blank");
eventArgs.set_cancel(true);
}
else if (LNtext == "") {
alert("Last Name can't be blank");
eventArgs.set_cancel(true);
}
else if (Emailtext == "") {
alert("Email address can't be blank");
eventArgs.set_cancel(true);
}
}
And another JavaScript function that is supposed to be called OnClientItemSelected but also is getting called on page load.
function Selecting(sender, eventArgs)
{
var Country = $find("<% = Country.ClientID %>");
var CountryDR = Country.get_selectedItem().get_text();
var State = $find("<% = State.ClientID %>");
if (CountryDR != "United States")
{
State == "Outside of US";
}
}
I am pretty new to JavaScript so any suggestions would be of great help.
Your brackets dont add up i think that might be the problem
You have the ending brackerts in both functions missed, please correct it and check.

Storing the first name and last name of the user in a table

I've created a register and login for my website, and I've created a table to store the users first name and last name, but I want to store more than one user in the table, but every time I update the table, it replaces the first user every time a new user logs in.
Click the link to view the images:
https://imgur.com/a/CFMC8
/*-- REGISTER --*/
function storeUserDetail(){
var fNameInput = document.getElementById("firstNameInput").value;
var lNameInput = document.getElementById("lastNameInput").value;
var uNameInput = document.getElementById("userNameInput").value;
var pWordInput = document.getElementById("passWordInput").value;
if(fNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your First Name.</span>";
}
else if(lNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Last Name.</span>";
}
else if(uNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Username.</span>";
}
else if(pWordInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Password.</span>";
}
else {
var storeDetails = {};
storeDetails.FirstName =
document.getElementById("firstNameInput").value;
storeDetails.LastName =
document.getElementById("lastNameInput").value;
storeDetails.Username =
document.getElementById("userNameInput").value;
storeDetails.Password =
document.getElementById("passWordInput").value;
localStorage[storeDetails.Username] = JSON.stringify(storeDetails);
window.location.replace("http://localhost/login.php");
}
}
/*-- LOGIN -- */
function loginUser(){
var Username = document.getElementById("userNameInput").value;
var Password = document.getElementById("passWordInput").value;
if(Username === ""){
document.getElementById("logMessage").innerHTML = "<span
class='error'>Please enter your Username.</span>";
}
else if(Password === ""){
document.getElementById("logMessage").innerHTML = "<span
class='error'>Please enter your Password.</span>";
}
else {
if(localStorage[Username] === undefined) {
document.getElementById("logMessage").innerHTML = "<span
class='error'>Username Incorrect. Please try again.</span>";
return;
}
else {
var storeDetails = JSON.parse(localStorage[Username]);
if(Password === storeDetails.password) {
localStorage.loggedInUserName = storeDetails.Username;
window.location.replace("http://localhost/game.php");
}
else{
document.getElementById("logMessage").innerHTML = "<span
class='error'>Password Incorrect. Please try again.</span>";
}
}
}
/* TABLE */
function inputUserInfo(){
var storeDetails = JSON.parse(localStorage[localStorage.LoggedInUser]);
var table = document.getElementById("rankTable");
var row = table.insertRow();
var firstNameCell = row.insertCell(0);
var lastNameCell = row.insertCell(1);
firstNameCell.innerHTML = storeDetails.FirstName;
lastNameCell.innerHTML = storeDetails.LastName;
}
You can't create a registration and login system using local storage. Local storage only saves values in the user's own browser, thus 'local.' The server doesn't know about them, other users don't know about them, and they're all cleared a way if the user clears their browser history thoroughly. And there is only one value for each given key -- if you say username = "Sarah" today, and username = "Laura" tomorrow, then Laura overwrites Sarah, because it just doesn't make sense for the user's browser to have two different things both called username.
Local storage isn't suitable for registration and login systems. It's only suitable for caching things for an individual user. For example, you might store in-progress/unsent messages in local storage so the user doesn't lose them on a page refresh.

Decode Json string in javascript

I am trying to decode a json string by using JSON.parse() however, I don't know exactly where to place the code as I'm not that familiar with JSON/Jquery.
This is the JS part:
/* ----------------------------------------------------------- */
/* Contact form
/* ----------------------------------------------------------- */
$('#contact-form').submit(function(){
var $form = $(this),
$error = $form.find('.error-container'),
action = $form.attr('action');
$error.slideUp(750, function() {
$error.hide();
var $name = $form.find('.form-control-name'),
$email = $form.find('.form-control-email'),
$phone = $form.find('.form-control-phone'),
$message = $form.find('.form-control-message');
$.post(action, {
name: $name.val(),
email: $email.val(),
phone: $phone.val(),
message: $message.val()
},
function(data){
$error.html(data);
$error.slideDown('slow');
if (data.match('success') != null) {
$name.val('');
$email.val('');
$phone.val('');
$message.val('');
}
}
);
});
return false;
});
The relevant part of my mailscript:
if($isValid == true) {
$result["submit_message"] = _msg_send_ok;
} else {
$result["submit_message"] = _msg_send_error;
}
if($_POST["name"]=="" || $_POST["name"]==_def_name)
$result["error_name"] = _msg_invalid_data_name;
if($_POST["email"]=="" || $_POST["email"]==_def_email || !preg_match("#^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$#", $_POST["email"]))
$result["error_email"] = _msg_invalid_data_email;
if($_POST["message"]=="" || $_POST["message"]==_def_message)
$result["error_message"] = _msg_invalid_data_message;
$result['isValid'] = $isValid;
echo json_encode($result);
This outputs the following: {"submit_message":"Bedankt voor uw bericht!","isValid":true}
How can I make sure it only shows the submit_message part in the Json string?
If what you want is to display the submit message in $error.html(data) then all you need to do is replace it with $error.html(data.submit_message) as jQuery automatically parses the json from the data variable into a object.

How to update text inside Div?

Iam trying to update Div text based on js variable null or not.
This is the code used for checking var userName is null or not.
If its null i dont want to do anything.But if userName is not null then i need to append ',' to existing text inside div .
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
var div = document.getElementById('title b');
div.innerHTML = div.innerHTML + ',';
}
});
my html of the div
<div id="title" class="box">
<b>Welcome</b>
</div>
For example if userName is not null then i want div text as "Welcome ,"
if userName is null then i want div text as "Welcome"
Since you're using jQuery already...
$(document).ready(function (){
var userName = ""; // this will never get into the following if statement, always else
if (userName == undefined || userName == null) { // use if (!userName) as shorthand.
alert('empty');
} else {
alert('not empty');
var div = $('#title > b');
div.text(div.text() + ',');
}
});
You're using an odd mix of POJS and jQuery here. Here's a purely jQuery solution:
$("document").ready(function (){
var userName = "";
if (userName == undefined || userName == null) {
alert('empty');
} else {
alert('not empty');
$('#title b').append(',');
}
});
It's a little odd that you're declaring userName as an empty string within your function - the first if condition will never execute.
A more jQuery answer, if you are interested:
var userName = "";
//var userName = "User"; // for testing
//var userName; // for testing
//var userName = null; // for testing
$(document).ready(function (){
var greeting = !!userName ? "Welcome, "+ userName + "!" : "Welcome";
$("#title b").html(greeting);
})
jsFiddle

Categories

Resources