Upload PDF using AJAX - javascript

I'm trying to upload a PDF document using AJAX, but it keeps on failing with an unknown error. What am I doing wrong?
HTML File:
<form id="document">
<p>
Title<br>
<input type="text" name="name" size="30">
</p>
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input id="submit-button" type="button" value="Send">
</div>
</form>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#submit-button').click(function() {
$.ajax({
type: "POST",
dataType: "JSON",
url: "upload_document.php",
data: $("#document").serialize(),
success : function(data){
alert(data.message);
}, error : function(data) {
alert(data.message);
}
});
});
});
</script>
PHP File (upload_document.php)
<?php
header("Access-Control-Allow-Origin: *");
try {
$id = "[RANDOM_GENERATED_GUID]";
$targetDir = "../../../../modules/sites/documents/";
if (!is_dir($targetDir)) {
if (!mkdir($targetDir, 0777, true)) {
throw new Exception("Unable to upload your document. We were unable to create the required directories");
}
}
$targetFile = $targetDir . $id . ".pdf";
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
if (file_exists($targetFile)) {
throw new Exception("Unable to upload your document. The file already exists");
}
if ($_FILES["datafile"]["size"] > 2000000) {
throw new Exception("Unable to upload your document. The file is to large (Maximum of 2MB)");
}
if ($fileType != "pdf") {
throw new Exception("Unable to upload your document. Only PDF documents can be uploaded");
}
if (!move_uploaded_file($_FILES["datafile"]["tmp_name"], $targetFile)) {
//Keeps failing here with error code 0
throw new Exception("Unable to upload your document. There was an error uploading the file");
}
echo json_encode(array(
"error" => false,
"message" => "Your document was successfully uploaded"
));
} catch (Exception $ex) {
echo json_encode(array(
"error" => true,
"message" => $ex->getMessage()
));
}
I also checked on the server, and the directory is being created successfully. Thanks for the help!
Edit
This exact same PHP script works if I set the action on the form, and use a submit button. The only reason I want to use AJAX, is to display a modal dialog after receiving a response

When you start using AJAX POST, the posted parameter should be looked for in $_POST instead of $_FILES.
This is because $_FILES is a cache for files uploaded through multipart post. Since you have serialized it and sent using AJAX, PHP parses the JSON and put everything inside $_POST
Look here for an example

Related

upload image from multiple form with ajax and php

in PHP page with multiple form tag to register user information.
using ajax to collect data and post to register PHP page now i want to upload image to server folder but i failed.
my html code:
<label for="upimage" class="btn btn-sm btn-primary mb-75 mr-75">Upload Image</label>
<input type="file" id="upimage" hidden accept="image/*" name="image"/>
Javascript Code:
let data1 = document.getElementById('data1').value,
data2 = document.getElementById('data1').value,
data3 = document.getElementById('data1').value,
upimage = document.getElementById('upimage').value;
$.ajax({
url:"././newregister.php",
method:"POST",
data:{action:'newregister', data1:data1, data2:data2,
data3:data3, upimage:upimage},
success:function(data){
alert(data);
}
});
newregister php code:
$uploads_dir = './uploads';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
echo "Sucsess";
}
else
{
echo "Error" . $_FILES["file"]["error"] ;
}
ERR: Undefined index: file in .... on line ....
Given by POST method uploads
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
Your current solution lacks enctype, that's why your file is not getting uploaded to the server and therefore isn't in the superglobal variable $_FILES.
As ferikeem already said. Wrap your data in a FormData Object and send it that way.
See: https://stackoverflow.com/a/5976031/10887013
JavaScript
let fd = new FormData();
fd.append("you_file_key_here", $("#upimage")[0].files[0]);
fd.append("data1", $("#data1")[0].value);
fd.append("data2", $("#data2")[0].value);
fd.append("data3", $("#data3")[0].value);
$.ajax({
url: "././newregister.php",
method: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
alert(data);
}
});
$_FILES["file"], here is your problem.
In $_FILES array key "file" doesn't exists. As I see you need to change $_FILES["file"] with $_FILES["upimage"].

multiple file upload using same form but different input fields using jquery php

I have searched for this thing on stack overflow, I was unable to find a relevant answer to my issue. Please have a look at the code I am using to fetch data and throw it to a php file and upload files to the respective folders and store their link to database. But I am not able to store data. It shows "unable to upload data."
Jquery file:
$(document).on('click','#modalMenu', function(){
var pagename = $("#pagename").val();
var page = 'modalMenu';
var menuname = $("#menuname").val();
var nav = $("#nav").val();
var content = CKEDITOR.instances['content'].getData();
var form_data = new FormData();
var file_data = $('#file').get(0).files[0];
var logo = $('#logo').get(0).files[0];
form_data.append('file', file_data);
form_data.append('logo', logo);
form_data.append('pagename', pagename);
form_data.append('menuname', menuname);
form_data.append('content', content);
form_data.append('nav', nav);
form_data.append('page', page);
$.ajax({
url: 'insert.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
method: 'POST',
success: function(data){
alert(data);
location.reload();
}
});
});
form on some page
<form method="post" role="form" enctype="multipart/form-data" action="javascript:;">
<input type="text" class="form-control" placeholder="Page Name" id="pagename" name="pagename" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Nav Name" id="nav" name="nav" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Menu Name" id="menuname" name="menuname" style="max-width:25%; display:inline" />
<input type="file" name="logo" id="logo" title="Menu Logo" class="form-control" style="max-width:20%; display:inline"/>
<input type="text" class="form-control" placeholder="Summery Part.. Please make it crisp" id="content" name="content" style="max-width:30%; display:inline" />
<script>
var editor = CKEDITOR.replace( "content", {
uiColor: "#ffffff",
filebrowserBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html",
filebrowserImageBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Images",
filebrowserFlashBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Flash",
filebrowserUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files",
filebrowserImageUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images",
filebrowserFlashUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash"
});
CKFinder.setupCKEditor( editor, "../" );
</script>
<input type="file" name="file" id="file" class="form-control" style="max-width:25%; display:inline"/>
<input type="submit" id="modalMenu" name="modalMenu" class="btn btn-success" align="right" value="+" />
</form>
insert.php file
$pageName=$_POST['page'];
if($pageName=='modalMenu'){
$pagename=$_POST['pagename'];
$menuname=$_POST['menuname'];
$nav=$_POST['nav'];
$content=$_POST['content'];
$error=$_FILES['file']['error'];
if($error!=0)
{
echo "Error with File data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$fname=$_FILES['file']['name'];
$ftype=$_FILES['file']['type'];
$fsize=$_FILES['file']['size'];
$ftname=$_FILES['file']['tmp_name'];
$target="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target);
if($ans)
{
$error=$_FILES['logo']['error'];
if($error!=0)
{
echo "Error with Image Data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$logo_name=$_FILES['logo']['name'];
$logo_type=$_FILES['logo']['type'];
$logo_size=$_FILES['logo']['size'];
$logo_tname=$_FILES['logo']['tmp_name'];
$target2="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target2);
if($ans)
{
//save info to database
$con=mysql_connect("localhost","root","");
mysql_select_db("rcg_db",$con) or die (mysql_error());
$target=addslashes($target);
$query="INSERT INTO `modalmenu`(`pagename`, `nav`, `menuname`, `menulogo`, `content`, `readmore`) VALUES ('$pagename','$nav','$menuname','$target' ,'$content','$target2');";
$n=mysql_query($query);
if($n==1)
{
echo "File upload successful! Data is added. Please wait while page reloads";
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait..";
}
}
}
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait.";
}
}
}
Thank you in advance. In case I am not using a good way of coding please do recommend and resolve the issue.
From what I understand you want to send the ajax into PHP but PHP cant save it?
Ill give you an example
jQuery
$(#modalMenu).on('click',function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var age = $("#age").val();
$.ajax({
url: 'insert.php', //point to server-side PHP script
dataType: 'json',
type: "POST",
data:{
"fname" : fname,
"lname" : lname,
"age" : age,
"save" : true
},
success: function(yes){
if(yes.success == true){
window.location.reload(true);
}
}
});
});
PHP
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "INSERT INTO beneficiary (fname, lname, age)
VALUES ('$fname','$lname','$age')";
$result = mysql_query($sql);
echo json_encode(array(
"success" => true,
));
refer the below link, i think this is useful for you
http://www.codexworld.com/upload-multiple-images-using-jquery-ajax-php/

Upload Avatar To Server Using AJAX

I have looked into the best way to do this and keep getting conflicting information and advice on the various demonstrations.
My code is as follows...
html
<img src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="avatar-uploader" id="avatar-uploader" style="display: none;" />
javascript
$('input[type=file]').on('change', function(){
$.ajax({
url: "/ajax/upload-new-avatar.ajax.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert("Success");
}
});
});
PHP: /ajax/upload-new-avatar.ajax.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$sourcePath = $_FILES['avatar-uploader']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "".$_FILES['avatar-uploader']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
I'm sure there is something simple that I am missing here and i'm going to feel pretty stupid afterwards but could someone explain to me why the image isn't being uploaded to the server and saved in the AJAX directory for further processing.
What I need it to do is when the user clicks on the "change" hyperlink below the image it opens a file upload dialog (working), once an image has been selected it automatically uploads to the server over an AJAX connection (possibly working, logging shows the PHP file is being triggered), and then the image file needs to be saved in the AJAX directory to be further processed later in the code for it to be uploaded to the avatar service.
Thanks in advance.
Have managed to get it working...
Here is my amended code...
Javascript
$('input[type=file]').on('change', function(event){
files = event.target.files;
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
$("#avatar-status").text("Loading new avatar...");
$("#avatar").css("opacity", "0.4");
$("#avatar").css("filter", "alpha(opacity=40);");
//Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value) {
data.append(key, value);
});
$.ajax({
url: '/ajax/upload-new-avatar.ajax.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
if(typeof data.error === 'undefined') {
//Success so call function to process the form
//submitForm(event, data);
$("#avatar-status").text("Powered by Gravatar");
$("#avatar").css("opacity", "");
$("#avatar").css("filter", "");
} else {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
});
});
PHP
session_start();
require_once("../libraries/logging.lib.php");
new LogEntry("AJAX Upload Started - UploadNewAvatar", Log::DEBUG, "AvatarUpload");
sleep(3);
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = '../tmp/';
foreach($_FILES as $file) {
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name']))) {
$files[] = $uploaddir .$file['name'];
new LogEntry("UploadNewAvatar - Upload Successful", Log::DEBUG, "AvatarUpload");
} else {
$error = true;
new LogEntry("UploadNewAvatar - Errors Occured", Log::ERROR, "AvatarUpload");
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
new LogEntry("UploadNewAvatar - Form was submitted successfully", Log::DEBUG, "AvatarUpload");
}
echo json_encode($data);
HTML
<img id="avatar" src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span id="avatar-status" class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="upfile" id="upfile" style="display: none;" />

Multiple file upload with ajax and php

I want to uplod multiple files through ajax but I can't figure out how I can grab the files in PHP. Can anyone help me? Thank you!
Here is the code:
HTML:
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file" multiple="multiple" name="file"/>
</form>
<div id="info"></div>
<div id="preview"></div>
JavaScript:
$(document).ready(function(){
$("#file").change(function(){
var src=$("#file").val();
if(src!="")
{
formdata= new FormData(); // initialize formdata
var numfiles=this.files.length; // number of files
var i, file, progress, size;
for(i=0;i<numfiles;i++)
{
file = this.files[i];
size = this.files[i].size;
name = this.files[i].name;
if (!!file.type.match(/image.*/)) // Verify image file or not
{
if((Math.round(size))<=(1024*1024)) //Limited size 1 MB
{
var reader = new FileReader(); // initialize filereader
reader.readAsDataURL(file); // read image file to display before upload
$("#preview").show();
$('#preview').html("");
reader.onloadend = function(e){
var image = $('<img>').attr('src',e.target.result);
$(image).appendTo('#preview');
};
formdata.append("file[]", file); // adding file to formdata
console.log(formdata);
if(i==(numfiles-1))
{
$("#info").html("wait a moment to complete upload");
$.ajax({
url: _url + "?module=ProductManagement&action=multiplePhotoUpload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res){
if(res!="0")
$("#info").html("Successfully Uploaded");
else
$("#info").html("Error in upload. Retry");
}
});
}
}
else
{
$("#info").html(name+"Size limit exceeded");
$("#preview").hide();
return;
}
}
else
{
$("#info").html(name+"Not image file");
$("#preview").hide();
return;
}
}
}
else
{
$("#info").html("Select an image file");
$("#preview").hide();
return;
}
return false;
});
});
And in PHP I get $_POST and $_FILES as an empty array;
Only if I do file_get_contents("php://input"); I get something like
-----------------------------89254151319921744961145854436
Content-Disposition: form-data; name="file[]"; filename="dasha.png"
Content-Type: image/png
PNG
���
IHDR��Ò��¾���gǺ¨��� pHYs��������tIMEÞ/§ýZ�� �IDATxÚìw`EÆgv¯¥B-4 ½Ò»tBU©)"¶+*"( E¥J7ôÞ;Ò¤W©¡&puwçûce³WR¸ èóûrw»³ï}fö
But I can't figure out how to proceed from here.
I am using Jquery 1.3.2 maybe this is the problem?
Thank you!
Sorry about the answer, but I can't add a comment yet.
I would recommend not checking the file type in javascript, it is easily bypassed. I prefer to scrutinise the file in PHP before allowing it to be uploaded to a server.
e.g.
This answer taken from another question (uploaded file type check by PHP), gives you an idea:
https://stackoverflow.com/a/6755263/1720515
<?php
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
?>
You can read the documentation on the exif_imagetype() function here.
Could you post your PHP code please? And I will update my answer if I have anything to add.
UPDATE:
NOTE: The 'multiple' attribute (multiple="multiple") cannot be used with an <input type='file' /> field. Multiple <input type='file' /> fields will have to be used in the form, naming each field the same with [] added to the end to make sure that the contents of each field are added to an array, and do not overwrite each other when the form is posted.
e.g.
<form enctype="multipart/form-data" method="POST">
<input type="file" id="file_0" name="img_file[]" />
<input type="file" id="file_1" name="img_file[]" />
<input type="file" id="file_2" name="img_file[]" />
</form>
When the form is submitted, the contents of any <input type='file' /> fields will be added to the PHP $_FILES array. The files can then be referenced using $_FILES['img_file'][*parameter*][*i*], where 'i' is key associated with the file input and 'paramter' is one of a number of parameters associated with each element of the $_FILES array:
e.g.
$_FILES['img_file']['tmp_name'][0] - when the form is submitted a temporary file is created on the server, this element contains the 'tmp_name' that is generated for the file.
$_FILES['img_file']['name'][0] - contains the file name including the file extension.
$_FILES['img_file']['size'][0] - contains the file size.
$_FILES['img_file']['tmp_name'][0] can be used to preview the files before it is permanently uploaded to the server (looking at your code, this is a feature you want to include)
The file must then be moved to its permanent location on the server using PHP's move_uploaded_file() function.
Here is some example code:
<?php
if (!empty($_FILES)) {
foreach ($_FILES['img_file']['tmp_name'] as $file_key => $file_val) {
/*
...perform checks on file here
e.g. Check file size is within your desired limits,
Check file type is an image before proceeding, etc.
*/
$permanent_filename = $_FILES['img_file']['name'][$file_key];
if (#move_uploaded_file($file_val, 'upload_dir/' . $permanent_filename)) {
// Successful upload
} else {
// Catch any errors
}
}
}
?>
Here are some links that may help with your understanding:
http://www.w3schools.com/php/php_file_upload.asp
http://php.net/manual/en/features.file-upload.multiple.php
http://www.sitepoint.com/handle-file-uploads-php/
Plus, some extra reading concerning the theory around securing file upload vulnerabilities:
http://en.wikibooks.org/wiki/Web_Application_Security_Guide/File_upload_vulnerabilities
You can use ajax form upload plugin
That's what i have found couple of days ago and implemented it this way
Ref : LINK
You PHP Code can be like this
uploadimage.php
$response = array();
foreach ($_FILES as $file) {
/* Function for moving file to a location and get it's URL */
$response[] = FileUploader::uploadImage($file);
}
echo json_encode($response);
JS Code
options = {
beforeSend: function()
{
// Do some image loading
},
uploadProgress: function(event, position, total, percentComplete)
{
// Do some upload progresss
},
success: function()
{
// After Success
},
complete: function(response)
{
// Stop Loading
},
error: function()
{
}
};
$("#form").ajaxForm(options);
Now you can call any AJAX and submit your form.
You should consider below code
HTML
<input type="file" name="fileUpload" multiple>
AJAX
first of all you have to get all the files which you choose in "input type file" like this.
var file_data = $('input[type="file"]')[0].files;
var form_data = new FormData();
for(var i=0;i<file_data.length;i++)
{
form_data.append(file_data[i]['name'], file_data[i]);
}
then all your data is in formData object now you can send it to server(php) like this.
$.ajax({
url: 'upload.php', //your php action page name
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (result) {
// code you want to execute on success of ajax request
},
error: function (result) {
//code you want to execute on failure of ajax request
}
});
PHP
<?php
foreach($_FILES as $key=>$value)
{
move_uploaded_file($_FILES[$key]['tmp_name'], 'uploads/' .$_FILES[$key]['name']);
}

$_POST variables not passed by form

I'm hosting a simple contact form on App Engine using PHP, trying to pass $_POST variables from a form to a PHP script that sends the email. As I can read from the logs, the $_POST variables don't seem to get through and I struggle to understand why... hence would appreciate another pair of eyes on this... thank you. Here are the various bits of (simplified) code:
Within index.html at the root:
<form method="post" action="#" id="contactform">
<div>
<label for="email">Enter your email</label>
<input type="text" class="input-field" id="email" name="email" value="">
</div>
<a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Send E-Mail</a>
<div id="success">Your message has been sent successfully!</div>
<div id="error">Unable to send your message, please try later.</div>
</form>
The PHP file, also at the root:
<?php
$send_email_to = "test#test.com";
$email_subject = "Email subject line";
function send_email($email,$email_message)
{
// using AppEngine's mail function here
}
function validate($email,$message)
{
// a simple validation function
}
if(isset($_POST['email'])) {
$email = $_POST['email']; // this doesn't seem to work
}
else
{$email = "email#email.com";} // did this to confirm the $_POST didn't seem to be passed
$return_array = validate($email,$message);
if($return_array['success'] == '1')
{
send_email(,$email,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
And the javascript that controls the error messages:
$('#button-send').click(function(event){
$('#button-send').html('Sending message...');
event.preventDefault();
$('html, body').scrollTo( $('#contact'), 'fast' );
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#contact_form').serialize(),
success: function(html) {
if(html.success == '1')
{
$('#button-send').html('Send message');
$('#success').show();
}
else
{
$('#button-send').html('Send message');
$('#error').show();
}
},
error: function(){
$('#button-send').html('Send message');
$('#error').show();
}
});
And in case this has to do with App Engine, my app.yaml looks like this:
- url: /js
static_dir: js
- url: /send_form_email.php*
script: send_form_email.php
- url: .*
script: index.html
Many thanks again – I've also put the full code on my Google Drive: https://drive.google.com/file/d/0B4yzSrEzbZ5jbk1oc2RWb2xSRWM/edit?usp=sharing
You are trying to serialise #contact_form but you have id="contactform"
The MIME type for JSON is application/json, not text/json.

Categories