Upload an image by using jquery and ajax - php

I'm trying to upload a photo by using ajax.
My input:
<input type="file" name="defaultPhoto">
A part of my jQuery code.
var form = #insertCredentials
var defaultPhoto = $('#' + form + ' ' + '[name = "defaultPhoto"]').prop('files');
I'm sending defaultPhoto through an ajax call to my php alongside with other form inputs.
The console gives back this error below:
TypeError: 'slice' called on an object that does not implement interface Blob.

I have implemented the AJAX way of file uploading using Dropzone JS.
It will really make your life simple
Check the Dropzone.js Website
All you need to do is instantiate the dropzonejs object and set the options
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
accept: function(file, done) {
if (file.name == "image.jpg") {
done("Naha, you don't.");
}
else { done(); }
}
};

you can't send file via ajax
try to use hidden iframe in form target with normal submit
<form name="" action="/your_iframe_action_url" taget="hidden_iframe_name">
<input type="file" />
<input type="submit" />
</form>
<iframe name="hidden_iframe_name" style="width:0; height:0" />
In your_iframe_action_url you can call javascript parent functions to execute event success or failure... that simulate underground upload

you can use document.getElementById('whatever').files;
to get the file
and then use
formdata
to send the files via ajax.
here is the example
you can also use File reader to show file on loaded
here is the example for filereader

Related

Upload image using jquery

I have a working php code to upload image in the database. Is it Possible to transform it to jquery? If so, what do I need to do? I am new to jquery btw. Thanks
This code works just fine. But I need to do it in jquery.
<form action = 'upload.php' method = 'post' enctype="multipart/form-data">
<input type="file" name="image" > <br>
<input type= 'submit' value = 'Add' id = 'Add' name = 'Add'>
</form>
<?php
if(isset($_FILES['image']))
{
$target_Path = "images/";
$target_Path = $target_Path.basename($_FILES['image']['name'] );
move_uploaded_file( $_FILES['image']['tmp_name'], $target_Path );
$name = $_FILES['image']['name'];
}
if(isset($_POST['Add']))
{
if($_POST["Add"] == "Add")
{
$add = "Insert Into img(path) Values('$name')";
$up = mysql_query($add);
$status = "Upload success!";
print '<script type="text/javascript">';
print 'alert(" '.$status.' ")';
print '</script>';
}
}
<form action='upload.php' method='post' enctype="multipart/form-data" id="formupload">
<input type="file" name="image"/> <br>
<input type='submit' value='Add' id='Add' name='Add/>
</form>
You need to first setup a callback for the submit event of the form.
$("#formupload").on("submit", upload_image);
JQuery selectors work a lot like CSS; $("#formupload") selects the element whose id is formupload.
on is used to register a handler for an event.
Here, we are setting up a handler(the upload_image function) for the submit event of the element whose id is formupload.
Make an AJAX call to the php script.
function upload_image(event){
event = event || window.event;
// Prevent the default form action i.e. loading of a new page
if(event.preventDefault){ // W3C Variant
event.preventDefault();
}
else{ // IE < 9
event.returnValue = false;
}
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData($('#formupload')[0]),
success : function(data){
// Show success message
},
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false
});
}
You can prevent the default action of form submission, which is to load the POST response, which is what the first few lines of the function is doing.
An AJAX call is made using $.ajax which is the jQuery utility for performing an AJAX call.
The url property is to be filled by that of your PHP script.
Since it is a file upload, specify the HTTP method as POST.
The data property is the payload of the POST request, which is the content of the file you are trying to upload.
You can specify the success callback using the success property, which is the function that will be called on completion of the file upload.
You can make an ajax call instead to submit a form. You can use something like this as well:
https://blueimp.github.io/jQuery-File-Upload/
Although, you still need to have your php code in order to store the file in your server

Instant upload on selected

I need a code that can instant upload an image from the pc to my website after I select it without needet to click submit or to refresh the page. This is the code that I have until now!
<img id="uploadPreviewprofile" style="max-width: 990px; max-height: 320px;text-align:center; position:absolute;" />
<div class="fileUploadprofile btn btn-primary" style="position:absolute; margin-top:298px;">
<form method="post" enctype="multipart/form-data">
<input id="uploadImageprofile" type="file" name="fotoprofile" class="uploadprofile" onchange="PreviewImageprofile();" />
</div>
<script type="text/javascript">
function PreviewImageprofile() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImageprofile").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreviewprofile").src = oFREvent.target.result;
};
};
</script>
</div>
Just ajax it over to your server after you read the file, e.g.:
HTML
<input id="instant" type="file">
JavaScript
// Note: I am using jQuery here, so you need to include the library
$("#instant").on("change", function() {
$.each(this.files, function(index, file) {
// read file data
reader = new FileReader();
reader.onload = function(event) {
// send to server
$.post("upload.php", {name: file.name, image: event.target.result});
}
reader.readAsDataURL(file);
});
});
PHP
<?php
if($_POST["image"]) {
// image is base64 encoded, so let's unparse it
$parts = explode(",", $_POST["image"]);
// check that we have the image
if(isset($parts[1])) {
// save the image
file_put_contents($_POST["name"], base64_decode($parts[1]));
}
}
And that's all the magic..
Quick recap:
1) We select the image via standard file upload tag
2) We capture the change the push the base64 encoded image to the server using an AJAX Post
3) We parse the base64 encoded image (which is in the Data URI scheme) and decode the base64 data part of it. This will give us the binary data from the actual image/file to save to the hard drive using the original name of it.
Now this code doesn't have any checks, etc. But it gives you the core functionality to continue your work.

Php ajax file upload error

I want to upload file using ajax but i dont get data in php $_FILES and I get it in $_REQUEST. How do I do it. Below is my jquery code.Ajax is not working for file uploading so is there any code so that i can merge with existing code for file uploading process.
<script>
jQuery(function($){
jQuery('#btn').click(function(){
var data = {},
ticks = [];
$('.ajax_elements').each(function(_, elem) {
data[this.id] = this.value;
});
$.ajax({
type : 'POST',
url : 'app_process.php',
data : data,
cache : false
}).done(function(result) {
alert(result);
});
});
});
</script>
<form name="frm" enctype="multipart/form-data">
<input type="text" name="bb" class="ajax_elements" id="one"/>
<input type="file" class="ajax_elements" name="passport" id="passport" />
<input type="button" name="bttn" id="btn" />
</form>
here is php file code
<?php
if($_REQUEST['passport']!=''):
$uploaddir = 'images/';
move_uploaded_file($_FILES["file"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport']));
endif;
?>
error message
Notice: Undefined index: file in
G:\xampp\htdocs\data_ajax\app_process.php on line 5
My advice would be to look at the XMLHttpRequest, FormData and File APIs. The Mozilla Developer Network have great documentation on all of these.
This needs testing and tweaking to be more robust in your development environment, but something along the lines of this could get you started...
<script>
$('#btn').click(function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("load", function(e){
// stuff to do when upload is complete
}, false);
xhr.upload.addEventListener("progress", function(e){
// stuff here to handle progress bars, progress percentages etc.
}, false);
xhr.open('POST', 'app_process.php', true);
var formdata = new FormData();
var file = $('#passport').get(0).files[0];
formdata.append('passport', file);
xhr.send(formdata);
});
</script>
And the PHP...
<?php
if (isset($_FILES['passport'])) {
$uploaddir = 'images/';
$upload = move_uploaded_file($_FILES['passport']['tmp_name'], $uploaddir . str_replace(" ","_",$_FILES['passport']['name'])) or exit('Upload failed.');
} else {
exit('File not found');
}
?>
Any additional information you want to send with the file needs to be added to the FormData object. These will appear in the PHP $_POST variable.
formdata.append('field', 'data');
Bear in mind that these APIs are not universally supported in browsers, so best practice is to include all the usual feature detection scripts before the user reaches this point.
You could also bind the upload function to the change event of the file input instead of asking for a button click...
$('#passport').change(function() { ...
Hope that helps.
There is 2 problems :
You need to add the attribute enctype="multipart/form-data" in the form tag if you want to upload files:
replace
<form name="frm">
by
<form name="frm" enctype="multipart/form-data" >
With ajax (and jquery), you cannot send file directly. But I suggest you that jquery form plugin who can help you with that

How to save dynamically XML file from server to a local machine?

Help me please. Where is my mistake ? I have many XML files on the IIS server. After click button link to XML come in JS file. JS send link to PHP file. PHP must show save dialog to save this link. See code:
JS:
function showAl(url)
{
alert(url);
var ajax = getRequest();
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
...
}
}
ajax.open("POST", "/do_query.php", true);
var data = 'info='+url;
ajax.send(data);
}
PHP:
<?php
if (isset($_POST['info']))
{
$info = $_POST['info'];
header('Content-Type: application/xml;');
header('Content-Disposition: attachment; filename=file.xml;');
readfile(str_replace(" ", "%20", $info), false);
}
?>
Thank's in advance !
Three simple ways to download a file:
Good old form
<form id="the-form" action="/do_query.php" method="post">
<input type="hidden" name="info" value="test">
<input type="Submit" value="Download with regular form">
</form>
Submit good old form with JavaScript
<script type="text/javascript">
function download(){
document.getElementById("the-form").submit();
}
</script>
<input type="Submit" value="Download with JavaScript" onclick="download()">
Switch to GET (requires changes to do_query.php):
Download with link
The problem with AJAX is that it runs on current (HTML) page. It can manipulate the page HTML or redirect to another location but it cannot send a custom HTTP response.
You cannot prompt a user to save a file when you are using AJAX, you will need to direct the browser window to the URL of the file to download. This also means you will need to use the GET method instead of the POST method to transfer the file.
Try this:
JS:
function showAl(url)
{
window.location.href = '/do_query.php?info=' + url;
}
PHP:
if (isset($_GET['info']))
{
$info = $_GET['info'];
// ...
This should prompt the user to download the file.

How to show upload image preview using jquery before form submit in a div

I am dealing with a form that contains various form elements with an option to upload multiple images(upto 6 max). Now i am having a div preview on clicking that div i fetch all form fields using jquery (form still not submitted at this time as its a multi form step1, 2 and 3). Now the problem is that i am fetching all form data with this code -
var allFormData = $("#myform").serializeArray();
Using this another code i am able to show rest of the data in div, but image is not coming.
$.each(adtitletoshow, function(i, field){
if( field.name == 'desc'){
$(".add_desc").text(field.value);
}
});
This is the filed created by JS to upload image.
<script type="text/javascript">
var total_images = 1 ;
function add_file_field () {
total_images++ ;
if ( total_images > 6 ) return ;
var str_to_embed = '<input name="fileImage[]" size="40" style="width: 500px;" type="file" onChange="add_file_field()"><br>' ;
$("#image_stack").append ( str_to_embed ) ;
}
</script>
All things going on single page so i need a solution that how can i load images under my preview div. Let me know if thr is some point of ambiguity still persists.
You need to loop through the files array from the multiple input and use the FileReader API on each.
I've set up the HTML like this:
​<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>​​​​​​​​​​​​​​​​​​​​​​
Then the javascript as follows:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
var image = $('<img>').attr('src', e.target.result);
$(image).appendTo('#images');
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#go').click(function() {
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});
I've set up a JSFiddle to demo http://jsfiddle.net/3LB72/
You'll probably want to do more checks on whether the browser the user is using has FileReader and if the files they have chosen are image files.
JSFiddle demo
This is much better, without clicking any button :D
HTML:
<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>
JavaScript:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
$("#images").css({'background-image':'url('+e.target.result+')'});
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#files').live('change', function(){
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});

Categories