Php Ajax and html5 form integration of contact form - php

I am having experience in PHP and HTML but not much familiar with Ajax. Can anyone help me out here to integrate my contact form, please check my code below what modification can be required in PHP and ajax code. If I remove ajax its working fine after including ajax form is not getting posted
HTML Code
<div class="col-lg-6">
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
Php code
<?php
require_once 'include/DB_Functions.php';
require 'send-grid/vendor/autoload.php';
$db = new DB_Functions();
if (isset($_POST['contact'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($db->storeform($name,$email,$phone,$subject,$message)) {
$memail = new \SendGrid\Mail\Mail();
$memail->setFrom("info#probig.in", "Probig Consulting");
$memail->setSubject("We have received your message");
$memail->addTo($email);
$raw_html = file_get_contents('email.html');
$getvar= array('%name%');
$repvar= array($name);
$femail=str_replace($getvar, $repvar, $raw_html);
$memail->addContent( "text/html", $femail);
$sendgrid = new \SendGrid('key');
try {
$response = $sendgrid->send($memail);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
$email2 = new \SendGrid\Mail\Mail();
$email2->setFrom("noreply#probig.in", "Probig Consulting");
$email2->setSubject($subject);
$email2->addTo("info#probig.in");
$email2->addContent("text/plain", "Name:".$name."<br><br>Mobile:".$phone."<br><br>Message:".$message);
$sendgrid = new \SendGrid('Key');
try {
$response = $sendgrid->send($email2);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
header("Location:msgsent.html");
}else{
echo "cant send message";
}
}
?>
AJax code:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.php-email-form').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg) {
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(msg);
}
}
});
return false;
});
});

Related

Redirect page after echo [duplicate]

This question already has answers here:
How do I redirect to another webpage?
(58 answers)
How do I make a redirect in PHP?
(34 answers)
Reference - What does this error mean in PHP?
(38 answers)
Page redirect after certain time PHP
(9 answers)
Closed 2 years ago.
I have checked How do I redirect to another webpage? and though they do successfully redirect, they remove the echo 'OK' function I have implemented.
I have a form and would like to redirect back to the home page 5 seconds after the form has been submitted.
However, there needs to be an echo first that says "OK" which links to a jQuery script and shows a green box that says "Your message has been sent (<div class="sent-message">). Thank you!". I would like to display that for 5 seconds, before redirecting back to the home page.
I know you cannot use header("Location: http://www.yourwebsite.com/index.html"); after echo but is there another way to do this?
This is what the form looks like when it is successfully submitted. The green box is what echo 'OK'; does. https://ibb.co/BjZ9v47
contact.php
<?php
// script to send myself an email with the data entered into the form by a user
if($mail->Send()) {
echo 'OK';
// redirect to index.html after 5 seconds
}
?>
form.html
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="captcha">
<div class="g-recaptcha" data-sitekey="my_site_key" data-callback="removeFakeCaptcha"></div>
<input type="checkbox" class="captcha-fake-field" tabindex="-1" required>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" title="Send Message">Send Message</button></div>
</form>
jQuery script:
!(function($) {
"use strict";
$('form.php-email-form').submit(function(e) {
e.preventDefault();
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
if ( $(this).data('recaptcha-site-key') ) {
var recaptcha_site_key = $(this).data('recaptcha-site-key');
grecaptcha.ready(function() {
grecaptcha.execute(recaptcha_site_key, {action: 'php_email_form_submit'}).then(function(token) {
php_email_form_submit(this_form,action,this_form.serialize() + '&recaptcha-response=' + token);
});
});
} else {
php_email_form_submit(this_form,action,this_form.serialize());
}
return true;
});
function php_email_form_submit(this_form, action, data) {
$.ajax({
type: "POST",
url: action,
data: data,
timeout: 40000
}).done( function(msg){
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
if(!msg) {
msg = 'Form submission failed and no error message returned from: ' + action + '<br>';
}
this_form.find('.error-message').slideDown().html(msg);
}
}).fail( function(data){
console.log(data);
var error_msg = "Form submission failed!<br>";
if(data.statusText || data.status) {
error_msg += 'Status:';
if(data.statusText) {
error_msg += ' ' + data.statusText;
}
if(data.status) {
error_msg += ' ' + data.status;
}
error_msg += '<br>';
}
if(data.responseText) {
error_msg += data.responseText;
}
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(error_msg);
});
}
})(jQuery);
You can echo a <meta> refresh with a set URL, although this isn't the best approach.
if (!$mail->Send()) {
echo "Mail sending failed";
}
else {
echo "Mail sent!";
echo "<meta http-equiv='refresh' content='5;URL=/index.html'>";
}
More information about the meta tag here.
In your $.ajax done callback, inside if you can use setTimeout:
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
//redirect to specific url after 5secs
window.setTimeout(function () {
window.location.href = 'https://www.example.com'; //your home url here
}, 5000);
}

Echo div class after form is submitted

I have a contact form on my website. When a user presses submit with their details filled it, it sends me an email. However, when they click submit, a green box should appear below <div class="sent-message"> yet, when I click submit, it shows a red box and says, "mail sent". Here are the PHP lines in contact.php that are causing this...
Simply, the box should be changed to green and have the text from sent-message instead of this.
if($mail->Send()) {
echo "mail sent";
}
else {
echo "mail sent failed";
}
<div class="form">
<form action="contact.php" method="post" role="form" class="php-email-form">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validate"></div>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" title="Send Message">Send Message</button></div>
</form>
</div>
Here is the jQuery:
!(function($) {
"use strict";
$('form.php-email-form').submit(function(e) {
e.preventDefault();
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validate').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
var this_form = $(this);
var action = $(this).attr('action');
if( ! action ) {
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html('The form action property is not set!');
return false;
}
this_form.find('.sent-message').slideUp();
this_form.find('.error-message').slideUp();
this_form.find('.loading').slideDown();
if ( $(this).data('recaptcha-site-key') ) {
var recaptcha_site_key = $(this).data('recaptcha-site-key');
grecaptcha.ready(function() {
grecaptcha.execute(recaptcha_site_key, {action: 'php_email_form_submit'}).then(function(token) {
php_email_form_submit(this_form,action,this_form.serialize() + '&recaptcha-response=' + token);
});
});
} else {
php_email_form_submit(this_form,action,this_form.serialize());
}
return true;
});
function php_email_form_submit(this_form, action, data) {
$.ajax({
type: "POST",
url: action,
data: data,
timeout: 40000
}).done( function(msg){
if (msg == 'OK') {
this_form.find('.loading').slideUp();
this_form.find('.sent-message').slideDown();
this_form.find("input:not(input[type=submit]), textarea").val('');
} else {
this_form.find('.loading').slideUp();
if(!msg) {
msg = 'Form submission failed and no error message returned from: ' + action + '<br>';
}
this_form.find('.error-message').slideDown().html(msg);
}
}).fail( function(data){
console.log(data);
var error_msg = "Form submission failed!<br>";
if(data.statusText || data.status) {
error_msg += 'Status:';
if(data.statusText) {
error_msg += ' ' + data.statusText;
}
if(data.status) {
error_msg += ' ' + data.status;
}
error_msg += '<br>';
}
if(data.responseText) {
error_msg += data.responseText;
}
this_form.find('.loading').slideUp();
this_form.find('.error-message').slideDown().html(error_msg);
});
}
})(jQuery);
You could do something like this, in contact.php:
$sent = false;
if($mail->Send()) { $sent = true; }
Then in your html you show message:
<?php
if($sent) { ?>
<div class="sent-message">Your message has been sent. Thank you!</div>
<?php } ?>
UPDATE
So your form submission is controlled by jQuery. You can show message by just echo 'OK' instead of "mail sent" in your php script
if($mail->Send()) {
echo "mail sent";
$color = 'green';
}
else {
echo "mail sent failed";
$color = 'red';
}
?>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message" style='background-color:"<?php echo $color;' ?>">Your message has been sent. Thank you!</div>
</div>
Your code must return
if($mail->Send()) {
echo "OK";
}
and if you want differen message, you can change it here:
<div class="sent-message">My new message</div>

Validating forms Ajax PHP

The jQuery/JavaScript/Ajax code is not mine. I'm learning and trying to understand it. The issue that I am having is after the data gets sent to the database the form is suppose to add class="show" to #sendmessage but its adding class="show" to #errormessage even though it was successful and the data was entered into the database. I don't understand why or how to fix it.
contact form index.html
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<div id="errormessage"></div>
<form action="contactform/contactform.php" method="POST" role="form" class="contactForm">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:8" data-msg="Please enter at least 8 chars of subject" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<div class="text-center"><button type="submit">Send Message</button></div>
</form>
</div>
contactform.js
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function() {
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
case 'email':
if (!emailExp.test(i.val())) {
ferror = ierror = true;
}
break;
case 'checked':
if (! i.is(':checked')) {
ferror = ierror = true;
}
break;
case 'regexp':
exp = new RegExp(exp);
if (!exp.test(i.val())) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
f.children('textarea').each(function() { // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if (rule !== undefined) {
var ierror = false; // error flag for current input
var pos = rule.indexOf(':', 0);
if (pos >= 0) {
var exp = rule.substr(pos + 1, rule.length);
rule = rule.substr(0, pos);
} else {
rule = rule.substr(pos + 1, rule.length);
}
switch (rule) {
case 'required':
if (i.val() === '') {
ferror = ierror = true;
}
break;
case 'minlen':
if (i.val().length < parseInt(exp)) {
ferror = ierror = true;
}
break;
}
i.next('.validation').html((ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '')).show('blind');
}
});
if (ferror) return false;
else var str = $(this).serialize();
var action = $(this).attr('action');
if( ! action ) {
action = 'contactform/contactform.php';
}
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
//alert(msg);
if (msg == 'OK') {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
} else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
contactform.php
<?php
//Define access
define('_VALID', 'Yes');
//required files
require_once('../include/config/config.php');
//variables
$contactFormName = '';
$contactFormEmail = '';
$contactFormSubject = '';
$contactFormMessage = '';
$checkStep = 1;
//Add new message
if (isset($_POST['name'])){
//Get values
$contactFormName = $_POST['name'];
$contactFormEmail = $_POST['email'];
$contactFormSubject = $_POST['subject'];
$contactFormMessage = $_POST['message'];
// 1. check name form field
if($checkStep == 1){
if($contactFormName === $_POST['name']){
$contactFormName = filterName($contactFormName);
$checkStep++;
}else{
echo "No its not working";
}
}
// 2. check email field
if($checkStep == 2){
if($contactFormEmail === $_POST['email']){
$contactFormEmail = filterEmail($contactFormEmail);
$checkStep++;
}else{
echo "Uh Oh! Something went wrong with your email please try again!";
}
}
// 3. check subject
if($checkStep == 3){
if($contactFormSubject === $_POST['subject']){
$contactFormSubject = filterSubject($contactFormSubject);
$checkStep++;
}else{
echo "Uh Oh! Whats up with your subject";
}
}
// 4. check message
if($checkStep == 4){
if($contactFormMessage === $_POST['message']){
$contactFormMessage = filterMessage($contactFormMessage);
$checkStep++;
}else{
echo "Uh ho! Please write us a message";
}
}
// 5. insert message
if($checkStep == 5){
$sqlAddMessage = "
INSERT INTO contact_form(
name,
email,
subject,
message
) VALUES(
'$contactFormName',
'$contactFormEmail',
'$contactFormSubject',
'$contactFormMessage'
)
";
$queryAddMessage = $GLOBALS['mysqli']->query($sqlAddMessage);
if($queryAddMessage){
//code goes here
}
}else{
echo "Uh Oh! NO No No. Check step 5";
}
}
?>
The issue is that you're not setting $msg = "OK" anywhere in your function so the AJAX response is always going to the else statement.
contactform.php (in // 5. section)
if($queryAddMessage){
echo "OK";
}
You should echo msg checked by js in php as OK
if($queryAddMessage){
//code goes here
echo 'OK';
}
Just use a jQuery form validation plugin to validate form and its easier than using AJAX for the same.

How can I have an admin controller in Magento and use it in phhtml for uploading file

I'm beginner in PHP and Magento,
I have Plugin which has a admin menu which refers to a page.
What I want to do is adding an admin controller for uploading a file to server from the page.
this is my structure:
MyPlugin/KnownUser/Controller/Adminhtml/Admin/Index.php
<?php
namespace MyPlugin\KnownUser\Controller\Adminhtml\Admin;
require_once( __DIR__ .'../../../../IntegrationInfoProvider.php');
use \DateTime;
class Index extends \Magento\Backend\App\Action
{
/**
* #var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$configProvider = new \MyPlugin\KnownUser\IntegrationInfoProvider();
$configText = $configProvider->getIntegrationInfo(true);
$customerIntegration = json_decode($configText, true);
$resultPage = $this->resultPageFactory->create();
$layout = $resultPage->getLayout();
$block = $layout->getBlock('main_panel');
$block->setAccountId($customerIntegration["AccountId"]);
$block->setVersion($customerIntegration["Version"]);
$block->setPublishDate($customerIntegration["PublishDate"]);
$block->setUploadUrl($this->getUrl('knownuser/admin/process/index'));
$block->setIntegrationConfig( $configText);
return $resultPage;
}
}
MyPlugin\knownuser\view\adminhtml\templates\admin.phtml
<p>
<label style="width:200px">Publisher</label>
<br />
<input readonly type="text" value="<?php echo $this->getAccountId() ?>"> </input>
</p>
<p>
<label style="width:100px">Version</label>
<br />
<input readonly type="text" value="<?php echo $this->getVersion() ?>">
</input>
</p>
<p>
<label style="width:100px">Publish Date</label>
<br />
<input readonly type="text" value="<?php echo $this->getPublishDate() ?
>" > </input>
</p>
<p>
<label style="width:100px">IntegrationdedConfig</label>
</p>
<textarea rows="10" cols="200" readonly>
<?php echo $this->getIntegrationConfig() ?>
</textarea>
<form id='form' method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<script>
const url = '<?php echo $this->getUploadUrl()?>';
alert(url);
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
debugger;
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
</script>
So what I want to do is add a new controller and post my file to server, but I don't know how can I do that.
I tried to add another controller and post my file from JavaScript but it didn't work and just redirect my request.
my controller is like this:
MyPlugin\knownuser\Controller\Adminhtml\Process
<?php
namespace MyPlugin\KnownUser\Controller\Adminhtml\Admin;
class Index extends \Magento\Framework\App\Action\Action
{
public function execute()
{
die('test index');
echo('just for sure it has been ran');
}
}
Finally I found the solution, I just needed to add another controller like this and use it in my html:
<?php
namespace Queueit\KnownUser\Controller\Adminhtml\Admin;
class UploadConfig extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$configProvider = new \Queueit\KnownUser\IntegrationInfoProvider();
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
print_r('{');
$errors = "";
$extensions = ['json'];
$uploads = new \Zend_File_Transfer_Adapter_Http();
$files = $uploads->getFileInfo();
$file_name= '';
$file_tmp ='';
foreach ($files as $file => $fileInfo) {
if ($uploads->isUploaded($file)) {
if ($uploads->isValid($file)) {
if ($uploads->receive($file)) {
$info = $uploads->getFileInfo($file);
$file_name = $info[$file]['name'];
$file_type = $info[$file]['type'];
$file_tmp = $info[$file]['tmp_name'];
$file_ext1 = explode('.', $file_name);
$file_ext2 = end($file_ext1);
$file_ext = strtolower($file_ext2);
if (!in_array($file_ext, $extensions)) {
$errors = 'extension not allowed: ' . $file_name . ' ' . $file_type;
}
}
}
}
break;
}
$strConfig = "";
if ($file_name != "") {
if ($errors == "") {
$strConfig = file_get_contents($file_tmp);
$objectConfig = json_decode($strConfig);
$configProvider->updateIntegrationInfo($objectConfig->integrationInfo, $objectConfig->hash);
print_r("\"stat\" : \"Successful\",");
$configText = $configProvider->getIntegrationInfo(false);
print_r("\"configText\" : " . $configText);
}
} else {
$errors = 'Config file is not found in your request!';
}
if ($errors) {
print_r("\"errors\" : \"");
print_r($errors);
print_r("\"");
}
print_r('}');
}
}
}
<div class="form-group">
<p>
<label style="width:200px">Publisher: </label>
<label id="AccountId"><?php echo $this->getAccountId() ?></label>
</p>
<p>
<label style="width:100px">Version: </label>
<label id="Version"><?php echo $this->getVersion() ?> </label>
</p>
<p>
<label style="width:100px">Publish Date: </label>
<label id="PublishDate" class="form-control"> <?php echo $this->getPublishDate() ?> </label>
</p>
<button id='asdf' class="collapsible">Display JSON Integration Configuration</button>
<div class="content">
<div id="Config">
</div>
</div>
</div>
<hr class="HR_1" />
<div> <span>Select your new Integration Configuration to update the old one:</span></div>
<br />
<div style="overflow: auto">
<form id='form' method="post" enctype="multipart/form-data">
<label class="button" style="float:left">
<input type="file" name="files[]" accept=".json" id="files[]" class="button">
<i class="fa fa-cloud-upload"></i> Select configuration:
</label> <input type='text' id="upload-file-name" class="input-text" style='margin-left: 5px;margin-right: 10px;padding-bottom: 4px;width:400px;float:left'>
<button id="submit-uplode-file" class="button" type="submit" disabled name="submit" style="float:left">
<span id="SPAN_3">Update Configuration</span>
</button>
</form>
</div>
<br />
<div id="announcement"></div>
<script>
require([
'jquery'], function ($) {
var configString = '<?php echo $this->getIntegrationConfig() ?>';
if (configString != '') {
var config = JSON.stringify(JSON.parse(configString), null, '\t');
}
function output(inp) {
var configNode = document.getElementById("Config");
while (configNode.firstChild) {
configNode.removeChild(configNode.firstChild);
}
configNode.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
(function() {
if (config) {
output(syntaxHighlight(config));
}
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
const url = '<?php echo $this->getUploadUrl() ?>';
document.getElementById('files[]').onchange = function(e) {
if (e.target.files.length > 0) {
var filename = e.target.files[0].name;
document.getElementById("upload-file-name").value = filename;
document.getElementById("announcement").innerHTML = '';
document.getElementById("submit-uplode-file").disabled = false;
}
};
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
console.log(files);
jQuery.ajax({
url: url,
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
console.log('Sending');
},
success: function(data) {
console.log(data);
try {
var jsonData = JSON.parse(data);
} catch (e) {
jQuery("#announcement").html("<Span style='color:red'>" + "Some thing went wrong!" + "</Span>").fadeIn();
jQuery("#announcement").html("<Span style='color:red'>" + data + "</Span>").fadeIn();
}
if (jsonData.stat != undefined && jsonData.stat == 'Successful') {
jQuery("#AccountId").text(jsonData.configText.AccountId);
jQuery("#PublishDate").text(jsonData.configText.PublishDate);
jQuery("#Version").text(jsonData.configText.Version);
output(syntaxHighlight(JSON.stringify(jsonData.configText, null, '\t')));
// jQuery("#Config").text(JSON.stringify(jsonData.configText, null, '\t'));
jQuery("#announcement").html("<Span style='color:#4CAF50'>The File is uploaded successfully!</Span>").fadeIn();
document.getElementById("submit-uplode-file").disabled = true;
} else {
if (jsonData.errors != undefined && jsonData.errors != '') {
jQuery("#announcement").html("<Span style='color:red'>" + jsonData.errors + "</Span>").fadeIn();
} else {
jQuery("#announcement").html("<Span style='color:red'>" + "Some thing went wrong!" + "</Span>").fadeIn();
}
}
},
error: function(e) {
console.log(e);
jQuery("#announcement").html("Uploading file is faild!").fadeIn();
}
});
});
})();
});
</script>

Zen Cart Echo Customers email address in my html form

I would like to have a html form added in the create_account_success page. Since zen cart has put the customers email address in the db, so I would like to echo the customers email address in this form, so customers no need to key in again. However I have tried several method still cannot echo the customers_email_address, by any chance any people can help?
<div class="centerColumn" id="createAcctSuccess">
<h1 id="createAcctSuccessHeading"><?php echo HEADING_TITLE; ?></h1>
<div id="createAcctSuccessMainContent" class="content"><?php echo TEXT_ACCOUNT_CREATED; ?></div>
<?php
if(REWARD_POINTS_NEW_ACCOUNT_REWARD!=0 && isset($RewardPoints))
if(REWARD_POINTS_NEW_ACCOUNT_REWARD>0 && GetCustomersRewardPoints($_SESSION['customer_id'])==0)
$RewardPoints->AddRewardPoints($_SESSION['customer_id'],REWARD_POINTS_NEW_ACCOUNT_REWARD);
else
if(REWARD_POINTS_NEW_ACCOUNT_REWARD<0 && GetCustomersPendingPoints($_SESSION['customer_id'])==0)
$RewardPoints->AddPendingPoints($_SESSION['customer_id'],abs(REWARD_POINTS_NEW_ACCOUNT_REWARD));
?>
<fieldset>
<legend><?php echo PRIMARY_ADDRESS_TITLE; ?></legend>
<?php
/**
* Used to loop thru and display address book entries
*/
foreach ($addressArray as $addresses) {
?>
<h3 class="addressBookDefaultName"><?php echo zen_output_string_protected($addresses['firstname'] . ' ' . $addresses['lastname']); ?></h3>
<address><?php echo zen_address_format($addresses['format_id'], $addresses['address'], true, ' ', '<br />'); ?></address>
<div class="buttonRow forward"><?php echo '' . zen_image_button(BUTTON_IMAGE_EDIT_SMALL, BUTTON_EDIT_SMALL_ALT) . ' ' . zen_image_button(BUTTON_IMAGE_DELETE, BUTTON_DELETE_ALT) . ''; ?></div>
<br class="clearBoth">
<?php
}
?>
</fieldset>
<div class="buttonRow forward"><?php echo '' . zen_image_button(BUTTON_IMAGE_CONTINUE, BUTTON_CONTINUE_ALT) . ''; ?></div>
</div>
Form
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="http://c.us7.list-manage.com/subscribe/post?u=8e1a686f2e7899f845cd4208c&id=79af0d8b9f" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
<h2>Subscribe to our mailing list</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address <span class="asterisk">*</span>
</label>
<input type="email" value="<?php echo $customers_email_address;?>" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="FNAME" class="required" id="mce-FNAME">
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name <span class="asterisk">*</span>
</label>
<input type="text" value="" name="LNAME" class="required" id="mce-LNAME">
</div>
<div class="mc-field-group">
<label for="mce-MMERGE4">Where did you hear about us? <span class="asterisk">*</span>
</label>
<input type="text" value="" name="MMERGE4" class="required" id="mce-MMERGE4">
</div>
<div id="mce-responses" class="clear">
<div class="response" id="mce-error-response" style="display:none"></div>
<div class="response" id="mce-success-response" style="display:none"></div>
</div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_8e1a686f2e7899f845cd4208c_79af0d8b9f" value=""></div>
<div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>
<script type="text/javascript">
var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[4]='MMERGE4';ftypes[4]='text';
try {
var jqueryLoaded=jQuery;
jqueryLoaded=true;
} catch(err) {
var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
head.appendChild(script);
if (script.readyState && script.onload!==null){
script.onreadystatechange= function () {
if (this.readyState == 'complete') mce_preload_check();
}
}
}
var err_style = '';
try{
err_style = mc_custom_error_style;
} catch(e){
err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = err_style;
} else {
style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);
var mce_preload_checks = 0;
function mce_preload_check(){
if (mce_preload_checks>40) return;
mce_preload_checks++;
try {
var jqueryLoaded=jQuery;
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
try {
var validatorLoaded=jQuery("#fake-form").validate({});
} catch(err) {
setTimeout('mce_preload_check();', 250);
return;
}
mce_init_form();
}
function mce_init_form(){
jQuery(document).ready( function($) {
var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} };
var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
$("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
options = { url: 'http://candles.us7.list-manage.com/subscribe/post-json?u=8e1a686f2e7899f845cd4208c&id=79af0d8b9f&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
beforeSubmit: function(){
$('#mce_tmp_error_msg').remove();
$('.datefield','#mc_embed_signup').each(
function(){
var txt = 'filled';
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
var bday = false;
if (fields.length == 2){
bday = true;
fields[2] = {'value':1970};//trick birthdays into having years
}
if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
this.value = '';
} else {
if (/\[day\]/.test(fields[0].name)){
this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value;
} else {
this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
}
}
});
});
$('.phonefield-us','#mc_embed_signup').each(
function(){
var fields = new Array();
var i = 0;
$(':text', this).each(
function(){
fields[i] = this;
i++;
});
$(':hidden', this).each(
function(){
if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){
this.value = '';
} else {
this.value = 'filled';
}
});
});
return mce_validator.form();
},
success: mce_success_cb
};
$('#mc-embedded-subscribe-form').ajaxForm(options);
});
}
function mce_success_cb(resp){
$('#mce-success-response').hide();
$('#mce-error-response').hide();
if (resp.result=="success"){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function(){
this.reset();
});
} else {
var index = -1;
var msg;
try {
var parts = resp.msg.split(' - ',2);
if (parts[1]==undefined){
msg = resp.msg;
} else {
i = parseInt(parts[0]);
if (i.toString() == parts[0]){
index = parts[0];
msg = parts[1];
} else {
index = -1;
msg = resp.msg;
}
}
} catch(e){
index = -1;
msg = resp.msg;
}
try{
if (index== -1){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
} else {
err_id = 'mce_tmp_error_msg';
html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
var input_id = '#mc_embed_signup';
var f = $(input_id);
if (ftypes[index]=='address'){
input_id = '#mce-'+fnames[index]+'-addr1';
f = $(input_id).parent().parent().get(0);
} else if (ftypes[index]=='date'){
input_id = '#mce-'+fnames[index]+'-month';
f = $(input_id).parent().parent().get(0);
} else {
input_id = '#mce-'+fnames[index];
f = $().parent(input_id).get(0);
}
if (f){
$(f).append(html);
$(input_id).focus();
} else {
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
} catch(e){
$('#mce-'+resp.result+'-response').show();
$('#mce-'+resp.result+'-response').html(msg);
}
}
}
</script>
<!--End mc_embed_signup-->
Try this:
// Query the database for customers email address by (logged in) customer's ID
$email_results = $db->Execute('SELECT customers_email_address FROM customers WHERE customers_id = ' . $_SESSION['customer_id']);
// The customer's Email Address is now in the PHP variable $email_addr
$email_addr = $email_results->fields['customers_email_address'];

Categories