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.
Related
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.
I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits
I have problem regarding on appending a sample a href to the div or to the html elements, I have only 3 array response to my ajax, however the results shows duplicate item to the corresponding div. I will share to you guys my sample code that already made,
I have here my backend php:
<?php
require_once('../ConnectionString/require_db.php');
session_start();
//submit function
$status = 'Active';
$posttype_affiliation_page = 'affiliation_page';
$posttype_member_org_page = 'member_org_page';
$affiliation_member_org_content = $db->prepare('SELECT title,link,posttype FROM tblcontent
WHERE status = ? AND posttype = ? OR posttype = ? ORDER BY contentID DESC')
or die($db->error);
$affiliation_member_org_content->bind_param('sss',$status,$posttype_affiliation_page,$posttype_member_org_page);
$affiliation_member_org_content->execute();
$affiliation_member_org_content->bind_result($title,$link,$posttype);
$result = array();
while ($affiliation_member_org_content->fetch()) {
$result[] = array('title'=>$title,'link'=>$link,'posttype'=>$posttype);
header('Content-type: application/json');
}
echo json_encode($result);
?>
my front end:
$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
My Html:
<div class="Affiliation">
<h5>Affiliation</h5>
<p style="font-size:14px;" class="list_affiliation_links">
</p>
</div>
<br>
<div class="Member">
<h5>Member Organizations</h5>
<p style="font-size:14px;" class="list_member_org_links">
</p>
</div>
$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_affiliation_links').html('');
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_member_org_links').html('');
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
You should first clear html content and then set to DOM element. Might be it works for you.
you're appending a second p tag with your HTML that also gets selected in your append later in the code. You should only build the link withing the var data.
Greetings
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.
I want to convert the following client side javascript code to server side PHP in order to protect some code. Below is a sample code of what I would like to have in PHP (and not using echo on each line, as this does not hide anything apart from the opening and closing PHP tags!)
function calc() {
var aa = document.a.lsofa.value * 40.77;
var bb = document.a.ssofa.value * 29.26;
var z90 = "Text here.";
var ctt = aa + bb;
ctt = parseInt(ctt);
tot = ctt;
if (tot < 1) {
var rslt = "Please enter relevant quantities in the form above.";
}
else {
var rslt = "Complete. We would require " + ctt.toString() + z95 + "";
}
document.a.answer.value = rslt
Also the onclick event of the form would need to be changed (I would like to keep the converted code on the same page an just call this function on form submit).
Any help would be appreciated.
You mean something like this:
header('Content-type: application/json');
$aa = $_GET["lsofa"] * 40.77;
$bb = $_GET["ssofa"] * 29.26;
$z90 = "Text here.";
$ctt = aa+bb;
$ctt = intval(ctt);
$tot = $ctt; // not useful
if ($tot<1) {
echo json_encode(array('result' => "Please enter relevant quantities in the form above."));
} else {
echo json_encode(array('result' => "Complete. We would require " . $ctt . $z95));
}
called with
$(function() {
$("#myForm").on("submit",function(e) {
e.preventDefault(); // stop submission
$.get("calc.php",$(this).serialize(),function(data) {
alert(data.result);
});
});
});