Not getting the filename of a drag and drop image in PHP - php

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));

Related

Php code to validate and send form data to email

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"];
}
?>

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>

The PHP don't add the value to an external file

I write this little script of PHP but when I press the button "Add" it don't add the value to the json.json file, can you tell me what is wrong? The objective is take the values introduced by user on the box add.name and add-link and save it to the json.json file. Have I to call the php script on a html line?
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
<?php
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($json, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $jsonString);
?>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" name="addname" id="add-name" placeholder="Name"></input>
<input type="text" name="addlink" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Box/Table Configuration (Sites/edit/delete)
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
var el1 = document.getElementById('edit-name1');
el.value = Checker[item].name;
el1.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
var url1 = el1.value;
if (url) {
Checker[item].url = url1.trim();
Checker[item].name = url.trim();
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
//Close button (Edit bar)
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
I think you are not using your variables in the right way. json_decode should use $jsonContents and file_put_contents should use $json
Since you are using post variables, you might want to check if it is a post first.
Try it like this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($jsonContents, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $json);
}

Repeatation Of Ajax(Jquery method) Submission on a single click And Image Not Passing to server

I'm having issues on submmiting a formdata to my server after a jquery based client side validation. i havebeen working on this since noon, i really need assistance.I had made a jquery slider with my login form, so after each input it slides to the next after validation, so i have two issues basically, one after each submit of a review.. 5 reviews are actually made, and two the image is not processed, i'm not certain it passes to my server because it is not saved on my harddrive.
Here Is My Simple HTml Form
<form action="review.php" method="post" id="makeReview" enctype="multipart/form-data">
<!-- first slide start -->
<div class="makereview firstSlide">
<div id="myslides" >
<input type="text" id="reviewName" name="reviewName" placeholder="Name of Reviewee" pattern="[a-zA-Z0-9'.- ]+" maxlength="25" class="myForm">
<br>
<button class="btn btn-info nextSlideOne" >
<i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
<strong style="color: red;text-align: left;" class="errorOne"></strong>
</div>
</div>
<!-- first slide ends-->
<!-- Second slide start -->
<div class="makereview secondSlide">
<div id="myslides">
<input type="text" id="reviewLink" name="reviewLink" placeholder="https://reviewee.com" pattern="[a-zA-Z/.0-9:]+" class="myForm" style="text-transform: lowercase;">
<br>
<button class="btn btn-info nextSlideTwo" >
<i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
<strong style="color: red;text-align: left;" class="errorTwo"></strong>
</div>
</div>
<!-- Second slide ends-->
<!-- third slide start -->
<div class="makereview thirdSlide">
<div id="myslides">
<input type="file" class="myForm" name="image" id="reviewLogo" style="margin: auto">
<br>
<button class="btn btn-info nextSlideThree" >
<i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
<strong style="color: red;text-align: left;" class="errorThree"></strong>
</div>
</div>
<!-- third slide ends-->
<!-- fourth slide start -->
<div class="makereview fourthSlide">
<div id="myslides" >
<h3>Your Review</h3>
<textarea class="myForm" name="reviewBody" minlength="200" maxlength="500" placeholder="Your review. minimum 200 Characters and maximum 500 Characters" rows="8" id="reviewBody" ></textarea>
<br>
<button class="btn btn-info nextSlideFour">
<i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
<strong style="color: red;text-align: left;" class="errorFour"></strong>
</div>
</div>
<!-- fourth slide ends-->
<div class="makereview fifthSlide">
<div id="myslides" >
<br>
<br>
<br>
<br>
<br>
<br><br>
<button class="btn btn-info btn-large nextSlideFive">
<i class="glyphicon glyphicon-send"></i> Verify And Submit
</button>
<br>
<br>
<h2 style="color:green;text-align: center;font-family: serif;" class="responseSuccess"></h2>
<strong style="color:red;text-align: center;" class="responseError"></strong>
</div>
</div>
</form>
ANd here is my ajax method in jquery(i extracted it from the larger code to aid reading), the larger code is below it
$(nextFive).click(function(){
$(nextFive).fadeOut('linear')
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: 'review.php',
data: formData,
})
.done(function() {
$('.responseSuccess').text('Thank You \n Your Review Have Been Made');
})
})
Here is the larger code(i don't think it's necessary here but for clarity)
<script type="text/javascript">
$(function(){
// get the form
$('.scriptOnlyForm').css('visibility','visible')
var form = $('#makeReview');
// get the buttons
var nextOne = $('.nextSlideOne');
var nextTwo = $('.nextSlideTwo');
var nextThree = $('.nextSlideThree');
var nextFour = $('.nextSlideFour');
var nextFive = $('.nextSlideFive');
//get the input fie;ds
var inputOne = $('#reviewName');
var inputTwo = $('#reviewLink');
var inputThree = $('#reviewLogo');
var inputFour = $('#reviewBody');
//get the divs
var first = $('.firstSlide');
var second = $('.secondSlide');
var third = $('.thirdSlide');
var fourth = $('.fourthSlide');
var fifth = $('.fifthSlide');
// get the error classess
var errorOne = $('.errorOne');
var errorTwo = $('.errorTwo');
var errorThree = $('.errorThree');
var errorFour = $('.errorFour');
// by default slide up all divs except first div
$(second).slideUp('fast');
$(third).slideUp('fast');
$(fourth).slideUp('fast');
$(fifth).hide('fast');
$(nextOne).css('visibility','visible');
$(nextTwo).css('visibility','visible');
$(nextThree).css('visibility','visible');
$(nextFour).css('visibility','visible');
//start the submit fuction
$(form).submit(function(e){
// prevent form from submiting by default
e.preventDefault()
// first slide work========================================================== starts
$(nextOne).click(function(){
if($('#reviewName').val() == ''){
$(errorOne).html('Input The reviewee Name Please');
$(inputOne).css('background','red');
return false;
}
else if($('#reviewName').val() != ''){
$(first).slideUp('slow');
$(second).slideDown('linear');
}
})
//first slide work============================================================ ends
// second slide work========================================================== starts
$pattern_1 = /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;
$pattern_2 = /^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;
$(nextTwo).click(function(){
if($('#reviewLink').val() == ''){
$(errorTwo).html('Input The reviewee Website Url Please');
$(inputTwo).css('background','red');
return false;
}
if(!$pattern_1.test($('#reviewLink').val()) || !$pattern_2.test($('#reviewLink').val())){
$(errorTwo).html('Input A Valid Url Of the reviewee Please');
return false;
}
else if($('#reviewLink').val() != ''){
$(second).slideUp('slow');
$(third).slideDown('linear');
}
})
// second slide work============================================================ ends
// Third slide work========================================================== starts
$(nextThree).click(function(){
if($('#reviewLogo').val() == ''){
$(errorThree).html('Input The reviewee Logo Or badge Please');
$(inputThree).css('background','red');
return false;
}else if($('#reviewLogo').val() != ''){
$(third).slideUp('slow');
$(fourth).slideDown('linear');
}
})
// third slide work============================================================ ends
// fourth slide work========================================================== starts
$(nextFour).click(function(){
if($('#reviewBody').val() == ''){
$(errorFour).html('Write Your Review Please');
$(inputFour).css('background','red');
return false;
}else if($('#reviewBody').val() != ''){
$(fourth).slideUp('slow');
$(fifth).slideDown('linear');
}
})
// fourth slide work============================================================ ends
// verify form================================start
$(nextFive).click(function(){
$(nextFive).fadeOut('linear')
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: 'review.php',
data: formData,
})
.done(function() {
$('.responseSuccess').text('Thank You \n Your Review Have Been Made');
})
})
//verify form ================================== ends
})
})
</script>
Finally here is my php(it works well when i use a regular form with inputs and submit button, so i guess i problem don't lie here)
<?php
require 'header.php';
?>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$reviewBody = review($_POST['reviewBody']);
$reviewName = sanitizeString($_POST['reviewName']);
$reviewLink= sanitizeString($_POST['reviewLink']);
$reviewDate = date('Y-m-d');
if(isset($_SESSION['firstname']) && isset($_SESSION['lastname'])){
$reviewBy=$_SESSION['firstname'].' '. $_SESSION['lastname'];
}else{
$reviewBy= "source-research_user_not_registered_hence_we_give_an_unimaginable_name_that_is_obviously_not_going_to_be_hacked_nor_found_by_anyone";
}
if(empty($reviewBody) || empty($reviewName) || empty($reviewLink)){
die('Input all fields to make a review'); }
else if(
$reviewName && $reviewBody && $reviewLink){
$sql = ("INSERT INTO `reviews` (reviewName, reviewBody ,reviewDate, reviewLink,reviewLike, reviewUnlike, reviewBy ) VALUES ('$reviewName', '$reviewBody' , '$reviewDate','$reviewLink', 0,0, '$reviewBy') ");
$query=mysqli_query($conn,$sql);
if(!$query) {
header('location:makreview.php');
}
if($query){
$my = ("SELECT * FROM reviews where reviewName ='$reviewName' and reviewBody='$reviewBody' ");
$result = mysqli_query($conn, $my);
if(!$result){
$sql = ( "DELETE FROM `reviews` WHERE `reviews`.`reviewName` = '$reviewName' AND `reviewBody` = '$reviewBody'");
$query=mysqli_query($conn,$sql);
header('LOcation:dashboard.php');
}
if($result->num_rows){
$row =$result->fetch_array(MYSQLI_ASSOC);
$reviewId=$row['reviewId'];
}
if(!$result->num_rows){
$sql = ( "DELETE FROM `reviews` WHERE `reviewName` = '$reviewName' AND `reviewBody` = '$reviewBody'");
$query=mysqli_query($conn,$sql);
die('could not process, Go back');
}
}
}
if (isset($_FILES['image']['name']) && isset($reviewId)){
$saveto = "reviews/".$reviewId.".jpg";
$space='[\s]';
$nospace='';
$saveto = preg_replace($space,$nospace,$saveto);
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 900;
$tw = $w;
$th = $h;
}
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array(array(-1, -1, -1),
array(-1, 16, -1), array(-1, -1, -1)), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}
if(!file_exists($saveto) && !isset($reviewId)){
$sql = ( "DELETE FROM `reviews` WHERE `reviews`.`reviewName` = '$reviewName' AND `reviewBody` = '$reviewBody'");
$query=mysqli_query($conn,$sql);
}
header('Location:dashboard.php');
}
?>
To solve your issue,
first you need to note that you cannot submit image with ajax using form serialize. You need to replace
var formData = $(form).serialize();
with
var formData = new FormData(this);
Your form submit ajax code becomes
$(nextFive).click(function(){
$(nextFive).fadeOut('linear')
//var formData = $(form).serialize();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'review.php',
data: formData,
cache:false,
contentType: false,
processData: false,
})
.done(function() {
$('.responseSuccess').text('Thank You \n Your Review Have Been Made');
})
})
In your PHP page "review.php", you can only retrieve your form element with $_POST, the uploaded image can be retrieved with $_FILES. You also need to use PHP's move_uploaded_file to save the file to your desired location from the temporary directory.
Hope this helps. There are several solutions on this online

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