javascript - Using AJAX to call PHP function on button click -
i creating file upload script.
what wanted upload file without refreshing page
here's 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'] $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 upload!'; } }else{ $failed[$position] = '[{$file_name}] file large!'; } }else { $failed[$position] = '[{$file_name}] file extension 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 on ajax, searched examples want simpler possible.
by way, possible run without using plugins or libraries?
i managed find solution this. separated php script html , add javascript file. used ajax call php file upload files.
here's 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 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'] $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+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, guys. gladly appreciated. thanks!
Comments
Post a Comment