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'];
Related
Php code to validate and send form data to an email address
My php wont validate my ajax post call method and have my formdata sent to an email address on submit button click. I am probably missing out some codes and Here is a sample of what my code looks like.
Any answers?
<body>
<div class="tab_content active_tab" id="name">
<form method="post" class="import_form">
<input type="hidden" id="doc_type" name="doc_type" value="" required>
<textarea name="name" placeholder="Name" required></textarea>
<input type="hidden" name="importer1" value="1">
<button type="submit">SEND</button>
</form>
</div>
<div class="tab_content" id="account_type">
<form method="post" class="import_form">
<input type="hidden" id="doc_type" name="doc_type" value="" required>
<textarea name="account_type" placeholder="ACCOUNT TYPE" required></textarea>
<input type="hidden" name="date" placeholder="Date" required>
<input type="hidden" name="importer2" value="1">
<button type="submit">SEND</button>
</form>
</div>
</div>
</div>
<script src="assets/js/jquery.min.html"></script>
<script src="assets/bootstrap/js/bootstrap.min.html"></script>
</body>
<script>
var root_link = "index.html";
forms = document.getElementsByClassName('import_form');
for(let i = 0;i < forms.length; i++){
forms[i].addEventListener('submit',function(e){
e.preventDefault();
data = new FormData(this);
request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//alert(this.responseText);
if(this.responseText == true){
location = 'image.html';
}
}
};
}
function open_tap(tab){
var tabs = document.getElementsByClassName('tab_content');
var tabs_key = document.getElementsByClassName('import_tab');
for(let i = 0; i < tabs.length; i++){
tabs[i].style.display = 'none';
}
for(let i = 0; i < tabs_key.length; i++){
tabs_key[i].style.borderBottom = 'none';
}
document.getElementById(tab).style.display = 'block';
document.getElementsByClassName(tab)[0].style.borderBottom = '1px solid #fff';
}
</script>
<script>
$("#loader").hide();
function loading(t){
$("#loader").show();
setTimeout(function(){
$("#loader").hide();
},t);
}
$('#name').submit(function(e){
e.preventDefault();
var a = $('#name_val').val(),
b = $('#doc_type').val();
$.ajax({
method:"POST",
url:"set.php",
data:{name:a,doc_type:b,importer1:true},
beforeSend:function(){
loading(2500);
},
success:function(r){
loading(5000);
// alert(r);
location = 'image-2.html';
}
});
});
$('#accountype_form').submit(function(e){
e.preventDefault();
var a = $('#accountype_val').val(),
b = $('#doc_type').val(), c = $('#date').val();
$.ajax({
method:"POST",
url:"set.php",
data:{accounttype_val:a,doc_type:b,date:c,importer2:true},
beforeSend:function(){
loading(2500);
},
success:function(r){
loading(5000);
location = 'image-2.html';
}
});
});
</script>
<?php
if(isset($_POST['submit'])){
$to = "anything#domain.com";
$name = $_POST['name'];
$acounttype = $_POST['accounttype'];
$errorMSG = "";
if (empty($_POST["name"])) {
$errorMSG = "location:'image2_html'";
} else {
$name = $_POST["name"];
}
if (empty($_POST["accounttype"])) {
$errorMSG .= "location:'image2_html'";
} else {
$accounttype = $_POST["accounttype"];
}
?>
I want to validate the minlength and maxlength of textarea before submitting, can anyone tell me details?
<form id="contact-je" action="<?php echo JURI::current(); ?>" method="post">
<div class="input">
<label id="je_hide_message" for="message"><?php echo JText::_("$message"); ?></label>
<textarea name="je_message" id="message" class="requiredField" rows="4"
placeholder="<?php echo $message; ?>"><?php if (isset($_POST['je_message'])) {
if (function_exists('stripslashes')) {
echo stripslashes($_POST['je_message']);
} else {
echo $_POST['je_message'];
}
} ?></textarea>
<?php if (!isset($_SESSION)) {
if ($messageError != '') { ?><span
class="error"><?php echo $messageError; ?></span><?php }
} ?>
</div>
<div class="input">
<button name="submit" type="submit"
class="je_button"><?php echo JText::_("$submit") ?></button>
<input type="hidden" name="submitted" id="submitted" value="true"/>
</div>
</form>
<?php } ?>
</div>
If you are allowed to use the browser feature, you can just set minlength and maxlength attributes of <textarea>.
<form>
<textarea minlength="5" maxlength="10"></textarea>
<input type="submit">
</form>
I add following codes, but if enter more than 300characters, the form will still be submitted. I don't want to submit if the characters is over 300
// Validate error
$('form#contact-je').submit(function () {
$('form#contact-je .error').remove();
var hasError = false;
$('.requiredField').each(function () {
if ($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Pls enter ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You\'ve entered an invalid ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
}
}
});
//Limit message characters
$('#message').keyup(function() {
if ($(this).val().length > 300){
$(this).parent().append('<span class="error">ffffff</span>');
$(this).addClass('invalid');
hasError = true;
}
});
if (!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('form#contact-je').slideUp("fast", function () {
$(this).before('<span class="success"><strong>Thank you!</strong> We have received your email.<br />We will get back to you in 12 hours.<br />-- Pneuflex China</span>');
});
});
}
return false;
});
I'm trying to create a form that has a drag and drop image with it. I did a tutorial for the drag and drop and now I'm trying to
put it together with a form.
The problem I'm having is that I'm not able to get the filename, so that I can insert it into the database.
I've tried doing this
if(isset($_POST['add_product']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
but I get a blank array
Array ( [0] => ) 1
and when I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
I get the name of my image, but if I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
}
if(isset($_POST['add_product']))
{
echo print_r($filename);
die();
}
I get a blank array as well
Array ( [0] => ) 1
Here I was hoping that I could grab the $filename and pass it on to the if(isset($_POST['add_product]))
Here is my form
<form action="" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="content">content</label>
<textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
</div>
<input type="file" name="files[]" id="standard-upload-files" multiple>
<input type="submit" value="Upload files" id="standard-upload">
<div class="wrapper">
<div class="upload-console">
<h2 class="upload-console-header">
Upload
</h2>
<div class="upload-console-body">
<div class="upload-console-drop" id="drop-zone">
just drag and drop files here
</div>
<div class="bar">
<div class="bar-fill" id="bar-fill">
<div class="bar-fill-text" id="bar-fill-text"></div>
</div>
</div>
<div class="hidden" id="uploads-finished">
<h3>Process files</h3>
<div class="upload-console-upload">
filename.jpg
<span>Success</span>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product">Save</button>
</div>
</form>
Here is the js files that I got from the tutorial that I did.
main.js
(function(){
"use strict";
var dropZone = document.getElementById('drop-zone');
var barFill = document.getElementById('bar-fill');
var barFillText = document.getElementById('bar-fill-text');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files){
// console.log(files);
app.uploader({
files: files,
progressBar: barFill,
progressText: barFillText,
processor: 'index.php',
finished: function(data){
// console.log(data);
var x;
var uploadedElement;
var uploadedAnchor;
var uploadedStatus;
var currFile;
for(x = 0; x < data.length; x = x + 1)
{
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'upload-console-upload';
uploadedAnchor = document.createElement('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded)
{
uploadedAnchor.href = 'uploads/'+currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function(){
console.log('there was an error');
}
});
};
//drop functionality
dropZone.ondrop = function(e){
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function(){
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function(){
this.className = 'upload-console-drop';
return false;
};
}());
upload.js
var app = app || {};
(function(o){
"use strict";
//private methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4)
{
if(this.status === 200)
{
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function')
{
o.options.finished(uploaded);
}
}else{
if(typeof o.options.error === 'function')
{
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(e){
var percent;
if(e.lengthComputable === true)
{
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1)
{
data.append('files[]', source[i]);
}
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined)
{
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined)
{
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(options.files !== undefined)
{
ajax(getFormData(o.options.files));
// getFormData(o.options.files);
}
}
}(app));
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>
On the contact page, I do have a form that will allow users to send e-mails to the company. To control each field, I had a script to the form and some css effects.
This is working perfectly.
Here is a DEMO (Sadly, it can't work on jsfidle)
However, I didn't find any solution to send an e-mail with javascript (impossible). But what do I have to do to keep my javascript functionalities and send this e-mail?
Note: After sending the e-mail,the user has to stay on the same page.
HTML
<form onSubmit="return formValidation();" id="contactForm" name="contactForm" action="index.php">
<ul>
<label for="name">Name <span id="required">*</span></label>
<li><input name="name" id="name" type="text"/></li>
</ul>
<ul>
<label for="telephone">Telephone <span id="required">*</span></label>
<li><input name="telephone" id="telephone" type="text"/></li>
</ul>
<ul>
<label for="email">Email <span id="required">*</span></label>
<li><input name="email" id="email" type="text"></li>
</ul>
<ul>
<label for="message">Message <span id="required">*</span></label>
<li><textarea name="message" id="message" cols="70" rows="10" ></textarea></li>
</ul>
<ul id="row_submit_button">
<li><input type="submit" value="Submit" id="submit_button"/></li>
</ul>
<ul id="form_incorect_message">
<li>Please, fill in the form correctly.</li>
</ul>
</form>
Javascript
function formValidation()
{
var name = document.contactForm.name; // required
var telephone = document.contactForm.telephone; // required
var email = document.contactForm.email; // required
var message = document.contactForm.message; // required
fname_validation(name);
number_validation(telephone);
email_validation(email);
message_validation(message);
if (fname_validation(name)&&number_validation(telephone)&&email_validation(email)&&message_validation(message))
{
document.getElementById('form_incorect_message').style.visibility = 'hidden';
document.getElementById('contactForm').style.visibility = 'hidden';
document.getElementById('send_ok').style.display = 'block';
// sendMail();
}
else
{
}
return false;
};
function fname_validation(name)
{
if((name.value!="")&&(name.value!=" "))
{
var letters = /^[A-Za-z _-]+$/;
if(name.value.match(letters))
{
document.getElementById('name').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('name').style.borderColor = "red";
return false;
}
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('name').style.borderColor = "red";
return false;
}
};
function message_validation(message)
{
if(message!=""&&message!=" ")
{
var letters = /^[A-Za-z0-9 _-]+$/;
if(message.value.match(letters))
{
document.getElementById('message').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('message').style.borderColor = "red";
return false;
}
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('message').style.borderColor = "red";
return false;
}
};
function number_validation(telephone)
{
var numbers = /^[0-9+]+$/;
if(telephone.value.match(numbers))
{
document.getElementById('telephone').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('telephone').style.borderColor = "red";
return false;
}
};
function email_validation(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.match(mailformat))
{
document.getElementById('email').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('email').style.borderColor = "red";
return false;
}
};
function sendMail()
{
// var link = "mailto:my-email#gmail.com"
// + "?cc=xxxxxxx#xXXXXX.co.uk"
// + "&subject=" + escape("This is my subject")
// + "&body=" + escape(document.getElementById('myText').value);
// window.location.href = link;
};
Thanks