How to add value to the Mysql table using ajax - javascript

I have written a code to insert the values into the database table using ajax. If u see the image below ,the values are appeared in the text boxes and when pressed add areas button, these values must be added to the table.
image:
From the image, the values of X,Y,W and H are gathered and when the add areas button is clicked, it should insert the values of x,y,w and h in the table.
index.php:
<table>
<tr>
<div class="actions">
<input type="button" id="btnView" value="Display areas" class="actionOn" />
<input type="button" id="btnReset" value="Reset" class="actionOn" />
<input type="button" id="btn_add" value="add areas" class="actionOn" />
</div>
<br>
<div id="output" class='output'> </div>
</table>
<p>X:<input type= "text" id="x" name ="x" value="-">
<p>Y:<input type= "text" id="y" name ="y" value="-">
<p>W:<input type= "text" id="w" name ="w" value="-">
<p>H:<input type= "text" id="h" name ="h" value="-">
<script>
var selectionExists;
function areaToString (area) {
document.getElementById('x').value = area.x;
document.getElementById('y').value = area.y;
document.getElementById('w').value = area.width;
document.getElementById('h').value = area.height;
return (typeof area.id === "undefined" ? "" : (area.id + ": ")) + area.x + ':' + area.y + ' ' + area.width + 'x' + area.height + '<br />'
}
$('#btn_add').click(function(){
var x_value= document.getElementById('x').value;
var y_value= document.getElementById('y').value;
var w_value= document.getElementById('w').value;
var h_value= document.getElementById('h').value;
$.ajax({
type:'POST',
url: 'server.php',
data:{
'x_value': x_value,
'y_value': y_value,
'w_value': w_value,
'h_value': h_value
},
success: function(data){
alert("x:" + x_value +"y:" +y_value+"w:" +w_value+"h:" +h_value);
}
});
});
function output (text) {
$('#output').html(text);
}
// Log the quantity of selections
function debugQtyAreas (event, id, areas) {
console.log(areas.length + " areas", arguments);
};
// Display areas coordinates in a div
function displayAreas (areas) {
var text = "";
$.each(areas, function (id, area) {
text += areaToString(area);
});
output(text);
};
</script>
Server.php:
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'project_focus');
if(isset($_POST['x_value'])){
$x= $_POST['x_value'];
$valid="SELECT * FROM sample";
$validdb=mysqli_query($db, $valid);
while (mysqli_fetch_array($validdb)){
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);
}
}
?>
The database table name is sample and its fields are id, x_value, y_value , w, h.
The server.php is the file where i tried to use the mysql query to insert the values into the table. but when i run the code, the output is not achieved. The insert values did not work. I think i made some mistake with the query i think. but i couldnt figure it out. Can someone help me fix this problem.

Did you try to remove the while clause?
You shouldn't need to first query the database in order to do the insert. Just executing the connect and insert commands should work.
Be sure that the other columns in the table are not required, and are set as DEFAULT NULL, so that the query doesn't error on other columns not being set in your insert.
$add_x= "INSERT INTO sample (x_value) VALUES ($x)";
mysqli_query($db, $add_x);

HTML, CSS, and JavaScript should be more like
//<![CDATA[
/* js/external.js */
let get, post, doc, htm, bod, nav, M, I, mobile, S, Q, aC, rC, tC, shuffle, rand; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
shuffle = array=>{
let a = array.slice(), i = a.length, n, h;
while(i){
n = Math.floor(Math.random()*i--); h = a[i]; a[i] = a[n]; a[n] = h;
}
return a;
}
rand = (min, max)=>{
let mn = min, mx = max;
if(mx === undefined){
mx = mn; mn = 0;
}
return mn+Math.floor(Math.random()*(mx-mn+1));
}
// magic below
const x = I('x'), y = I('y'), w = I('w'), h = I('h'), display = I('display');
const reset = I('reset'), add = I('add'), error = I('error');
function valid(){
let xv = x.value, yv = y.value, wv = w.value, hv = h.value;
if(xv === '' || isNaN(xv) || yv === '' || isNaN(yv) || wv === '' || isNaN(wv) || hv === '' || isNaN(hv)){
error.textContent = 'Invalid Number';
return false;
}
error.textContent = ''; return true;
}
x.oninput = y.oninput = w.oninput = h.oninput = ()=>{
valid();
}
display.onclick = ()=>{
const fd = new FormData; fd.append('get_xywh', true);
post('xywh.php', fd, data=>{
output.innerHTML = '';
data.xywh.forEach(o=>{
const sect = M('div'), sx = M('div'), sy = M('div'), sw = M('div');
const sh = M('div');
sx.textContent = 'X: '+o.x; sy.textContent = 'Y: '+o.y;
sw.textContent = 'W: '+o.w; sh.textContent = 'H: '+o.h; sect.appendChild(sx);
sect.appendChild(sy); sect.appendChild(sw); sect.appendChild(sh);
output.appendChild(sect);
});
});
}
reset.onclick = ()=>{
x.value = y.value = 0; w.value = h.value = 1; error.textContent = '';
}
add.onclick = ()=>{
if(valid()){
const fd = new FormData;
fd.append('x', x.value); fd.append('y', x.value); fd.append('w', w.value);
fd.append('h', h.value);
post('xywh.php', fd, json=>{
error.textContent = json.success ? 'Hacker' : 'Content Added';
});
}
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body,.main{
width:100%; height:100%; background:#ccc;
}
.main{
padding:10px;
}
.er{
color:#900;
}
#xywh{
display:flex; flex-wrap:wrap; align-content:top center;
}
#xywh>*{
margin-bottom:7px;
}
#xywh>label{
flex:0 5%; text-align:center; padding-top:3px;
}
input{
padding:3px 5px; border:0;
}
input[type=number]{
border-radius:3px;
}
#xywh>input{
flex:0 95%;
}
.main{
text-align:center;
}
.main>input[type=button]{
background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 14px Tahoma, Geneva, sans-serif; padding:5px 10px; border-radius:5px;
}
#error{
margin-top:5px;
}
#output{
background:#000; color:#0c0; text-align:left; padding:5px 10px; margin:15px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>index.php</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='xywh'>
<label for='x'>X:</label><input id='x' type='number' min='0' value='0' />
<label for='y'>Y:</label><input id='y' type='number' min='0' value='0' />
<label for='w'>W:</label><input id='w' type='number' min='1' value='1' />
<label for='h'>H:</label><input id='h' type='number' min='1' value='1' />
</div>
<input id='display' type='button' value='Display Areas' />
<input id='reset' type='button' value='RESET' />
<input id='add' type='button' value='Add Area' />
<div id='error' class='er'></div>
<div id='output'>No Data Requested</div>
</div>
</body>
</html>
Put your MySQL connect.php in a restricted folder with permission 700.
<?php /* restricted/connect.php */
$db = #new mysqli('host', 'username', 'password', 'database');
?>
Let's say you have the following table made in MySQL like:
`CREATE TABLE xywh(
x INT NOT NULL,
y INT NOT NULL,
w INT NOT NULL,
h INT NOT NULL
)ENGINE=InnoDB;`
Now in a folder with the normal permission 755 (directly in your site root in this case)
<?php /* xywh.php */
if(!isset($_SERVER['HTTPS'])){ // force https or comment out if no https - but why are you making a site with no https?
header('LOCATION:https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); die;
}
$o = new StdClass;
if(isset($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'])){
$x = $_POST['x']; $y = $_POST['y']; $w = $_POST['w']; $h = $_POST['h'];
$r1 = '/^(0|[1-9]+[0-9]*$/'; $r2 = '/^[1-9]+[0-9]*$/';
if(!preg_match($r1, $x) || !preg_match($r1, $y) || !preg_match($r2, $w) || !preg_match($r2, $w)){
$o->hacker = true;
}
else{
require_once 'restricted/connect.php';
$s = $db->prepare('INSERT xywh (x, y, w, h) VALUES (?, ?, ?, ?)');
$s->bind_param('iiii', $x, $y, $w, $h); $s->execute(); $s->close(); $db->close();
$o->success = true;
}
}
elseif($_POST['get_xywh']) && $_POST['get_xywh'] === true){
require_once 'restricted/connect.php'; $a = [];
if($q = $db->query('SELECT x, y, w, h FROM xywh')){
while($r = $q->fetch_object()){
$a[] = $r;
}
$q->close();
}
$o->xywh = $a; $db->close();
}
else{
$o->hacker = true;
}
echo json_encode($o);
?>
Note that this is a very crude and simple example. You should have users that are allowed to input the data. So, you need a login that verifies users first. It's much more work. Also, this example just INSERTs a new row no matter if one exists that is the same... which, is what you would want if there is more than one of the same. If not, you'll have to test for sameness with a WHERE condition, and do an UPDATE if it already exists. Make sure you use prepared statements, unless you are doing very simple queries. Good Luck... this might take a while to understand. It's mostly an AJAX example for you.

Related

JavaScript , AJAX, PHP : trying to get values from $_POST

I am trying to build a way for a user to be able to create an article, if they want, with a button they can add an input for a text, a file input etc.
I want to send this form with JavaScript vanilla (training)
so what I do in my js is that I loop into my different added input then I append them to formData
and send this formData to my controller to treat it and add it to my database.
Problem is that by iterating my input when I append my input into formData I have to add the index
so when I send it and print_r my post
I get like:
text01
text02
text03 etc.
it would be fine if it was only these input that I wanted to send but in my post I have other inputs which are sent the same way so I get like
title01
paragraphe01
title02
paragprahe02
the problem will be when I want to query to add the data to my database I would have to bind all of these to my query, but of course I can't make 50 lines of
bind('text01', $text01)
I don't think it would be a nice way to do it
so I am looking for a way to be able to query all of these data I thought of maybe a way getting only the paragraphs indexes and putting them in an array containing only paragraphs then forEach() everything.
another array for another input etc. but I can't find a way to do it, is it even possible
so here is my code
<?php
include '../flash/Flash.php';
$pageTitle = "création d'article";
$css = "create_article";
include './assets/include/_header.php';
?>
<body>
<?php
include '../view/assets/include/_nav.php';
flash('createB');
?>
<main>
<form action="../controller/Crud_controller.php" method="post" class="form_container" enctype="multipart/form-data">
<input type="hidden" name="type" value="createB" id="type">
<h3 id="status"></h3>
<h5>titre du post</h5>
<input type="text" name="title" id="title">
<h5>Paragraphe</h5>
<textarea name="paragraphe" id="product_desc" cols="30" rows="10"></textarea>
<input type="file" id="img_livre" name="name" accept="image/png, image/jpeg">
<h5>Note 1</h5>
<input type="text" name="note" id="note">
<button type="button" data-prototype="" class="btn btn_primary btn-js">Ajouter un paragraphe ou une image ?</button>
<button type="button" class="btn btn_primary btn-js-ajax">envoyer</button>
</form>
</main>
</body>
<script>
const btnSubmit = document.querySelector('.btn-js-ajax');
btnSubmit.addEventListener('click', uploadFiles);
function uploadFiles() {
let formData = new FormData();
let images = document.getElementsByName('name');
let type = document.getElementById('type').value;
let paragraphe = document.getElementsByName('paragraphe');
let note = document.getElementsByName('note');
let title = document.getElementById('title').value;
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
formData.append('title', title);
formData.append('type',type );
const ajax = new XMLHttpRequest();
fetch("../controller/Crud_controller.php", {method: "POST", body: formData}).then(res => res.text()).then(data => {console.log(data);})
ajax.upload.addEventListener("load", completeHandler, false);
}
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key)]);
console.log(result);
const form = document.querySelector('.form_container');
const addBtn = document.querySelector('.btn-js');
function addInput() {
const paragraphe = document.createElement('textarea');
paragraphe.name = 'paragraphe';
paragraphe.style = "margin-top:100px";
paragraphe.cols = "30";
paragraphe.rows = "10";
const file = document.createElement('input');
file.type = 'file';
file.style = "border: none";
file.name = 'name';
file.accept = "image/png, image/jpeg";
const note = document.createElement('input');
note.type = 'text';
note.name = 'note';
const btnRemove = document.createElement('a');
btnRemove.className = 'btn_primary btn';
btnRemove.innerHTML = 'supprimer';
form.insertBefore(btnRemove, addBtn);
form.insertBefore(note, btnRemove);
form.insertBefore(file, note);
form.insertBefore(paragraphe, file);
}
addBtn.addEventListener('click', addInput);
</script>
</html>
here the controller getting the post ajax element
<?php
include '../model/CrudModel.php';
include '../model/Blog.php';
require_once '../flash/Flash.php';
class Products
{
private $crudModel;
private $crudBlog;
public function __construct()
{
$this->crudModel = new Product;
$this->crudBlog = new Blog;
}
public function blog()
{
$data = $_POST;
echo "<pre>";
print_r($data);
echo "</pre>";
print_r($_FILES);
if (empty($data['title']) || empty($data['paragraphe'])) {
flash('createB', 'remplir au moins le titre et le paragraphe et ajouter une image');
// header('Location: ../view/crud_blog.php');
} else {
forEach($data as $k => $v)
{if ($this->crudBlog->setBlogPost($data)) {
foreach ($_FILES as $file) {
if ($this->crudBlog->setBlogImages($file)) {
flash('createB', "c'est bon");
// header('Location: ../view/create_blog_page.php ');
}
}
}}
}
}
}
$init = new Products;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['type']) {
case 'crud':
$init->produit();
break;
case 'createB':
$init->blog();
break;
default:
echo "je peux pas";
break;
}
}
here is my Model where I have all my queries
<?php
require_once '../dbb/Database.php';
class Blog {
private $con;
private $table_name = "blog_post";
public function __construct()
{
$this->con = new Database;
}
public function setBlogPost($array) {
$query = "INSERT INTO " . $this->table_name . " SET title = :title , paragraphe=:p1 , note = :note1";
$this->con->prepare($query);
$this->con->bind('title' , $array['title']);
$this->con->bind('p1' , $array['paragrape']);
$this->con->bind('note1' , $array['note']);
if($this->con->execute()){
return true;
}return false;
}
public function setBlogImages($file){
$table_name = "blog_image";
$query = "INSERT INTO " . $table_name . " SET name = :img , id = LAST_INSERT_ID()";
$this->con->prepare($query);
$this->con->bind('img',$file['name']);
move_uploaded_file($file['tmp_name'], "../view/assets/uploads/".$file['name']);
if ($this->con->execute()){
return true;
}return false;
}
and this is the response I get in my console.log maybe it will be more clear
thank you
Little edit so i managed to make an array for each of my input
array paragraphe for paragraphes
note for notes etc...
i changed this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note" + i, notes);
}
}
by this
for(i = 0; i <= images.length; i++) {
let uFiles = images[i];
if (uFiles) {
formData.append("name[]" + i, uFiles.files[0]);
}
}
for(let i = 0; i < paragraphe.length; i++) {
let paragraphes = paragraphe[i].value;
if (paragraphes) {
formData.append("paragraphe[]"+i,paragraphes);
}
}
for(let i = 0; i < note.length; i++) {
let notes = note[i].value;
if (notes) {
formData.append("note[]" + i, notes);
}
}
but here's the problem
i can't find a way to foreach multiple array in php to add them to my database
this is the response result i get in my console now
reponse2

How to add conditionals to user input in App Scripts with while loops?

I made a selectBox which had its range of values from a Google Sheet Column. I also want to take an Integer input value from the user and then write this value in a specific cell according to option taken from selectBox. The html link does not show the integer response box. Is it possible to do the above plan in a while loop? Would appreciate any ideas and correction of code
function doGet() {
var ap = SpreadsheetApp.openByUrl("Gsheet URL here");
var ui = SpreadsheetApp.getUi();
var user = ui.prompt("Put down a number");
var result = result.getSelectedButton();
var sheet = ap.getSheetByName("lv");
var values = sheet.getRange("A2:A10").getValues();
var options = values.map(function(row)
{
#To show show the selected option??
var item = options.getSelecteditem();
if (item === A3)
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var a1 = cell.getA3Notation();
var val = cell.getValue();
SpreadsheetApp.getUi().alert("Ur value is "+a1+" value is "+val);
}
{
return '<option value="' + row[0] + '">' + row[0] + '</option>';
});
var html = '<form onSubmit="handleSubmit(this)"> Type of Cuisine' + options.join('') + '</select></form>';
return HtmlService.createHtmlOutput(html);
}
Using an Html Dialog to Control User Inputs
Not sure what you wanted so here's a complete example I whipped up for you.
Code.gs:
function processInput(obj) {
Logger.log(JSON.stringify(obj));
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const [min,max,locs] = sh.getRange('B1:B3').getValues().flat();
Logger.log('min: %s max: %s locs: %s',min,max,locs)
const lA = locs.split(',');
if(obj.int > max) {
obj.msg = "Too High Try Again";
return obj;
} else if (obj.int < min) {
obj.msg = "To Low Try Again";
return obj;
} else if (!~lA.indexOf(obj.loc)) {
obj.msg = "Invalid Location";
return obj;
} else {
sh.getRange(obj.loc).setValue(obj.int);
obj.msg = "Complete";
return obj;
}
}
Following function Launches the dialog:
function launchInputDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),"Enter Input");
}
html:
<!DOCTYPE html>
<html>
<head>
</head>
<style>input {margin: 2px 5px 2px 0;}</style>
<body>
<form>
<input type="text" id="in1" placeholder="Enter an integer" />
<br /><input type="text" id="in2" placeholder="Enter a location" />
<br /><input type="button" value="Process" onClick="processinput();" />
</form>
<div id="msg"></div>
<script>
function processinput() {
document.getElementById("msg").innerHTML = '';
let v1 = parseInt(document.getElementById('in1').value);
let v2 = document.getElementById('in2').value;
let obj = {int:v1,loc:v2,msg:''};
google.script.run
.withSuccessHandler(robj => {
console.log(JSON.stringify(robj))
if(robj.msg == "Complete") {
document.getElementById("msg").innerHTML = `Value: ${robj.int} Location: ${robj.loc} Try Again`;
document.getElementById("in1").value = '';
document.getElementById("in2").value = '';
} else {
document.getElementById("msg").innerHTML = robj.msg;
}
})
.processInput(obj);
}
</script>
</body>
</html>
Short Demo:
This version uses a <select> tag to allow the user to determine where the data will be loaded
GS:
function doPost(e) {
Logger.log(e.postData.contents);
Logger.log(e.postData.type);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
sh.getRange(data.loc).setValue(data.id)
}
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params = { "contentType": "application/json", "payload": JSON.stringify(obj), "muteHttpExceptions": true, "method": "post", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
UrlFetchApp.fetch(url, params);
}
function displayError(msg) {
SpreadsheetApp.getUi().alert(msg);
}
function launchMyDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'My Dialog');
}
function getSelectOptions() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Options');
var rg = sh.getDataRange();
var vA = rg.getValues();
var options = [];
for (var i = 0; i < vA.length; i++) {
options.push(vA[i][0]);
}
return vA;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<input type="text" id="txt1" name="id" placeholder="Enter Numbers only"/>
<select id="sel1" name="loc"></select>
<input type="button" value="submit" onClick="processForm(this.parentNode);" />
</form>
<script>
function processForm(obj) {
console.log(obj.id.value);
if(obj.id.value.match(/[A-Za-z]/)) {
google.script.run.displayError("Invalid Characters Found in id field");
} else {
google.script.run.sendData(obj);
}
}
window.onload = function() {
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
}
function updateSelect(vA) {
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);
}
}
</script>
</body>
</html>
Demo:

how to upload multiple image in php using javascript array

i have an array in java script, that array have file name and file path, now i have to assign that array in php and upload that file which are store in array, what can i do please give me solutions.
This is my javascript
<script type="text/javascript">
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
//console.log(files);
var filePath = $(this).val();
//console.log("fake pathddddddddddd"+filePath);
for (var i = 0; i < filesLength; i++) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = files[i];
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API");
}
});
</script>
dict is my array how can assign that array in php and upload in file,
you can check in console to gat the value
php file
<!DOCTYPE html>
<head>
<style>
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
whenever click the clickMe button you can the file name and file path in console check it and please help me
Sorry for the late return. I am not 100% sure if this is what you wanted. But i did it anyway :). Thanks to #Ben_Lee with his answer I managed to wrap the initiation inside a function.
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
function initiateFiles(file) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = file;
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
//var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
var filePath = $(this).val();
for (var i = 0; i < filesLength; i++) {
initiateFiles(files[i]);
}
console.log(arrImgNPath);
var myJSON = JSON.stringify(arrImgNPath);
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
});
} else {
alert("Your browser doesn't support to File API");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
Here i created a hidden input, which stores the array.
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
And then assigned an action to the form to send the data to another php file.
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
And now it is time to get the data and process:
<?php
$data = json_decode($_POST['myJSON']);
foreach ($data as $key => $value) {
echo " Name : $value->name <hr>";
echo " Path : $value->path <hr>";
echo " ID : $value->ID <hr>";
}
?>
I hope this helps, if you have further questions, don't hesitate to ask.

ERROR Synchronous XMLHttpRequest on the main thread is deprecated

I am attempting to load a graph with options to show data between select dates. When I run it on my webpage, I get an error "Table has no columns." 1, but when i set the IF statement (buildchris) to NOT EQUAL to maincampus, the chart will load. I believe it has something to do with the xmlhttp .send, the variables seem to not be sending over POST (buildingchartchris). Does anyone have a solution to this problem?
buildchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$p = $_POST['purpose'];
if($p == "maincampus")
{
$sm = $_POST['sm'];
$sd = $_POST['sd'];
$sy = $_POST['sy'];
$em = $_POST['em'];
$ed = $_POST['ed'];
$ey = $_POST['ey'];
//$start_date = Date("Y-m-d", mktime(0, 0, 0, $sm, $sd, $sy));
//$end_date = Date("Y-m-d", mktime(0, 0, 0, $em, $ed, $ey));
$start_date= "2014-01-01";
$end_date= "2016-01-01";
$result = $dbc->query('SELECT SUM(actual_hours) as act_hours, Buildings.bld_name, Buildings.bld_location FROM work_orders INNER JOIN Buildings ON work_orders.building = Buildings.bld_no WHERE work_orders.actual_completion_date > "'.$start_date.'" AND work_orders.actual_completion_date < "'.$end_date.'" AND Buildings.bld_location ="0" AND Buildings.bld_name <> "N/A" AND work_orders.actual_completion_date IS NOT NULL GROUP BY Buildings.bld_name');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Building', 'type' => 'string'),
array('label' => 'Hours', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r['bld_name']);
// Values of the each slice
$temp[] = array('v' => (int) $r['act_hours']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
echo $jsonTable;
}
?>
buildingchartchris.php
<?php
session_start(); // Start the session.
// If no session value is present, redirect the user:
// Also validate the HTTP_USER_AGENT!
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] != md5($_SERVER['HTTP_USER_AGENT'])) OR ($_SESSION['admin_level'] < 1) )
{
// Need the functions:
require ('includes/login_functions.inc.php');
redirect_user('index.php');
}
require("includes/mysqli_connect.php");
$page_title = 'Dashboard';
include ('includes/header.html');
?>
<html>
<head>
<title>Dashboard</title>
<link rel="icon" href="images/NKU.png" type="image/png" sizes="16x16">
<link rel="stylesheet" href="includes/as.css" type="text/css" media="screen" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js?libraries=geometry"></script>
<script src="http://maps.google.com/maps/api/js"></script>
<script>
<!--
//hides or shows the table given by nm
function hide_table(nm)
{
// alert(is_fullscreen);
var table_selector = "#table_" + nm;
$(table_selector).toggle();
//table_width = (table_width == 24)? 35:24;
//$("#iframeholder").animate({width: table_width + "%"});
}
// -->
</script> </head>
<div id="content">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Set a callback to run when the Google Visualization API is loaded.
// google.setOnLoadCallback(drawChart);
function drawChart() {
var maincamp_sm, maincamp_sd, maincamp_sy, maincamp_em, maincamp_ed, maincamp_ey;
if( document.getElementById("maincamp_dates_quarter").checked )
{
var maincamp_q = document.getElementById("maincamp_quarter").value;
maincamp_ey = Number(document.getElementById("maincamp_quarter_year").value);
maincamp_sy = maincamp_ey;
if( maincamp_q == 0 )
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
}
else if( maincamp_q == 1)
{
maincamp_sm = 7;
maincamp_sd = 1;
maincamp_em = 9;
maincamp_ed = 30;
}
else if( maincamp_q == 2 )
{
maincamp_sm = 10;
maincamp_sd = 1;
maincamp_em = 12;
maincamp_ed = 31;
}
else if( maincamp_q == 3 )
{
maincamp_sm = 1;
maincamp_sd = 1;
maincamp_em = 3;
maincamp_ed = 31;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
else if( maincamp_q == 4 )
{
maincamp_sm = 4;
maincamp_sd = 1;
maincamp_em = 6;
maincamp_ed = 30;
maincamp_ey = maincamp_ey + 1;
maincamp_sy = maincamp_sy + 1;
}
}
else
{
maincamp_sm = document.getElementById("maincamp_start_month").value;
maincamp_sd = document.getElementById("maincamp_start_day").value;
maincamp_sy = document.getElementById("maincamp_start_year").value;
maincamp_em = document.getElementById("maincamp_end_month").value;
maincamp_ed = document.getElementById("maincamp_end_day").value;
maincamp_ey = document.getElementById("maincamp_end_year").value;
}
if(!( (maincamp_ey < maincamp_sy) || ( (maincamp_em < maincamp_sm) && (maincamp_ey == maincamp_sy) ) || ( (maincamp_ed < maincamp_sd) && (maincamp_em == maincamp_sm) && (maincamp_ey == maincamp_sy) ) ))
{
var xmlhttp;
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()//Function called when there is a change of state for the server
{ //request
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)//when request is complete and no issues
{
//var str = xmlhttp.responseText;
var jsonData = $.ajax({
url: "buildchris.php",
type: "POST",
dataType: "json", // type of data we're expecting from server
async: false // make true to avoid waiting for the request to be complete
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData.responseText);
var options = {
title: 'Labor Hours for Main Campus',
is3D: 'true',
width: 1200,
height: 2000,
chartArea:{width:"40%"},
bar: {groupWidth: "50%"}
};
var maincamp_view = new google.visualization.DataView(data);
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(maincamp_view, options);
}
};
xmlhttp.open("POST","buildchris.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("purpose=maincampus&sm=" + maincamp_sm + "&sd=" + maincamp_sd + "&sy=" + maincamp_sy + "&em=" + maincamp_em + "&ed=" + maincamp_ed + "&ey=" + maincamp_ey);
}
else
{
alert("Your end date cannot be before the start date.");
}
}
google.load('visualization', '1', {'packages':['corechart']});
function cursor_hand(x)
{
x.style.cursor = "pointer";
}
function cursor_default(x)
{
x.style.cursor = "default";
}
function hide_element(nm)
{
var table_selector = "#" + nm;
$(nm).toggle();
}
</script>
<body>
<p onclick = "hide_element(operational_effectiveness_div);" style = "text-decoration: underline; font-size:x-large; font-weight:bold;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Operational Effectiveness Reports</p><br>
<div id = "operational_effectiveness_div" >
<p onclick = "hide_element(maincamp_div);" style = "text-indent: 15px; text-decoration: underline;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Show Total Labor Hours for Main Campus 2015-16</p><br>
<div id = "maincamp_div" style = "display:table;">
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_quarter" name = "maincamp_dates" value = "1" checked> Report by quarter </legend>
<p><select id = "maincamp_quarter">
<option value = 0 selected>All Quarters</option>
<option value = 1>Q1</option>
<option value = 2>Q2</option>
<option value = 3>Q3</option>
<option value = 4>Q4</option>
</select>
<input type = "number" id = "maincamp_quarter_year" min = "2015" value = "2015"></p>
</fieldset><br>
<fieldset style = "width: 800px; margin:auto; margin-left: 200px;"><legend><input type = "radio" id = "maincamp_dates_range" name = "maincamp_dates" value = "2"> Custom date range </legend>
<p>Start date (mm-dd-yyyy): <input type = "number" id = "maincamp_start_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_start_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_start_year" min = "2015" value = "2015"></p>
<p>End date (mm-dd-yyyy): <input type = "number" id = "maincamp_end_month" min = "1" max = "12" value = "1"><input type = "number" id = "maincamp_end_day" min = "1" max = "31" value = "1"><input type = "number" id = "maincamp_end_year" min = "2015" value = "2016"></p>
</fieldset>
<br>
<p onclick = "drawChart()" style = "border: thin solid black; padding: 2px; width: 95px; margin-left: 550px;" onmouseover="cursor_hand(this)" onmouseout="cursor_default(this)">Generate report</p>
<div id="chart_div" style="width: 1000px; text-indent: 50px;"></div>
</div>
</div>
</body>
</html>
<?php
//Release the used resources
mysqli_close($dbc);
include ('includes/footer.html');
?>

Using AJAX to call PHP function on button click

I am creating a file upload script.
What I wanted to do is to upload the file without refreshing the page
Here's my code:
upload.php
<?php
function upload(){
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<input type="file" name="file1[]" id="file1" multiple>
<input type="button" value="Upload File" onclick ="document.write('<?php upload(); ?>'')">
</form>
</body>
</html>
I wanted to do this on AJAX, I already searched for some examples but I want this to be simpler as possible.
By the way, is it possible for this to run without using any plugins or libraries?
I managed to find a solution for this. I separated the php script from the html and add a javascript file. I used ajax to call the PHP file to upload the files.
Here's my code;
index.php
<html>
<head>
<style type="text/css">
.upload{
width:500px;
background:#f0f0f0;
border: 1px solid #ddd;
padding: 20px;
}
.upload fieldset{
border: 0;
padding: 0;
margin-bottom:10px;
}
.uploads a, .uploads span{
display: block;
}
.bar{
width: 100%;
background: #eee;
padding: 3px;
margin-bottom:10px;
box-shadow: inset 0 1px 3px rgba(0,0,0,2);
border-radius: 3px;
box-sizing:border-box;
}
.barfill{
height: 20px;
display: block;
background: #ff6f01;
width:0px;
border-radius: 3px;
transition:width 0.8s ease;
}
.barfilltext{
color:#fff;
padding: 3px;
}
</style>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload Files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files:f,
progressBar:pb,
progressText:pt,
processor: 'upload.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'), anchor, span, x;
if (data.failed.length) {
failed.innerHTML = '<p>The following files failed to upload</p>'
}
uploads.innerText = '' ;
for(x=0; x<data.succeeded.length; x = x+1){
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x=0;x<data.failed.length; x=x+1){
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
</body>
</html>
upload.php
<?php
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() .'.'.$ext;
if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
upload.js
var app = app || {};
(function (obj) {
"use stricts;"
//Private Methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i=0; i<source.length; i = i+1){
data.append('file[]',source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value){
if (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
anyways, thanks for the help guys. those were gladly appreciated.
Thanks!
I think in your case the simplest way is to put it into an iframe. I assume you have all code in one PHP file which is called upload.php. You would get something like this:
<?php
//Check if the action is upload file. If it is start upload
if(isset($_GET['action']) && $_GET['action'] == 'uploadFile')
{
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
exit;
}
//Check if the action is getForm. If it is then display the form. This is to display the form in the iframe
elseif(isset($_GET['action']) && $_GET['action'] == 'getForm')
{
echo '
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php?action=uploadFile">
<input type="file" name="file1[]" id="file1" multiple>
<input type="submit" value="Upload File">
</form>';
exit;
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<!-- IFrame which loads the form !-->
<iframe id="uploadFileFrame" style="width:100%; height:auto; border:0px;" src="upload.php?action=getForm"></frame>
</body>
</html>
Showing uploaded image after successful upload
you just go through with this code I have already given the answer of this type of question

Categories

Resources