how to upload image using ajax in php - php

<div class="control-group">
<label class="control-label" for="inputEmail">Image</label>
<div class="controls">
<input type="file" value="Browse" name="image" id="image" />
<span style="color: #61625F; font-weight: bolder;" class="sixth"></span>
</div>
</div>
ajax code below
$("#reg").click(function() {
$.ajax({
url: "process_service_person_register.php",
type: "post",
data: "image": $("#image").val()},
});
how will i send the image to the "process file"

You have to use the FormData object.
<script>
if ("FormData" in window)
{
var fd = new FormData();
fd.append('file', $('#image')[0].files[0]);
$.ajax({
url: "process_service_person_register.php",
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(result) {
console.log(result);
}
});
}
else
{
console.log('sorry, FormData object is not available.');
}
</script>
Without FormData, you will have to go old school like using the hidden iframe method

Here is my php page when i post through ajaxform
<?php
include('phpfunc.php');
$path = "images/news/";
$utime = time();
$valid_formats = array("jpg", "png", "bmp","jpeg","gif");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = strtolower($_FILES['uploadnews']['name']);
if(strlen($name)){
$extpos = strrpos($name, '.', -1);
$ext = substr($name,$extpos+1);
if(in_array($ext,$valid_formats)){
$actual_image_name = $utime.".".$ext;
$fpath = $path.$actual_image_name;
$tmp = $_FILES['uploadnews']['tmp_name'];
if(move_uploaded_file($tmp, '../'.$fpath)){
echo $fpath;
}else{
echo "failed";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
exit;
}
?>

There is no way to upload files using AJAX
BUT, you can imitate the behavior of AJAX by using hidden Iframe (other ways exists - but this is the most compatible way for old and new browsers)
for example:
This is your form:
<form target="upload_frame" action="upload_handler.php" method="POST" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="inputEmail">Image</label>
<div class="controls">
<input type="file" value="Browse" name="image" id="image" />
<span style="color: #61625F; font-weight: bolder;" class="sixth"></span>
</div>
</div>
</form>
Now you should have a hidden IFrame inside your page, and name it upload_frame
<iframe name="upload_frame" id="upload_frame" width="1" height="1" frameborder="no" ></iframe>
And in upload_handler.php or whatever file that suppose to handle your upload request you should output something like
<script type="text/javascript">
window.parent.onUploadCallback(callback_data);
</script>
This will call onUploadCallback function set on the original's page JavaScript.
The callback_data parameter better be JSON serialized so you can use it inside the function as a native JavaScript object.
For example:
function onUploadCallback(response){
if(response.success)
alert("File uploaded: "+response.file_path);
} else {
alert("Error while uploading the file: "+response.error_message);
}
}
For making the all thing more generic - you should use "JSONP" like style and pass "callback" parameter to upload_handler.php with the name of the function you want to call. and then add it to the form as hidden field <input type="hidden" name="callback" value="window.parent.onSuccessCallback" />
After all that description - my real suggestion to you is - use an already made jQuery library for the task

Related

Display Two Images on One Click. PHP, AJAX

As I Have 2 Div Boxes. One is Input and the other one is Output Div Box as Shown in the Image Below.:
Now What I am doing is I am uploading the Image using the Help of PHP. And uploading same image on two folders named Input and Output.
What I want is When I Click Submit Button the image from input folder should be shown on Input Box and the Output Folder Image to be shown In Output Folder.
I am able to show the Input folder Image but not able to show the Output folder Image in output Div.
Here is my HTML Code :
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 class="inputImage-text text-center">Input Image</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div id="targetLayer">No Image</div>
<div id="uploadFormLayer">
<input name="fileToUpload" type="file" class="inputFile" /><br />
<input type="submit" value="Submit" class="btnSubmit btn btn-primary" />
</div>
</form>
</div>
<div class="col-md-6">
<h2 class="outputImage-text text-center">Output Image</h2>
<div class="outputDiv">
</div>
</div>
</div>
</div>
Here is my php Script:
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage)
?>
<img class="image-preview" src="<?php echo $targetPath; ?>" class="upload-preview" />
<?php
}
}
}
?>
and Here is the AJAX Code :
<script type="text/javascript">
$(document).ready(function(e) {
$("#uploadForm").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#targetLayer").html(data);
},
error: function() {}
});
}));
});
</script>
Use dataType option to accept the response in JSON format.
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
dataType: "json",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data.input_file);
$(".outputDiv").html(data.output_file);
},
error: function()
{
}
});
}));
});
</script>
Return both input and output files in an array format as follows
<?php
$uploadedFiles = [];
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage);
$uploadedFiles['input_file'] = '<img class="image-preview" src="'.$targetPath.'" class="upload-preview" />';
$uploadedFiles['output_file'] = '<img class="image-preview" src="'.$outputImage.'" class="upload-preview" />';
}
}
}
echo json_encode($uploadedFiles);
?>
Refer to this documentation regarding dataType
Add this with in your script
$(".outputDiv").html(data);
I have changed your php, html and jquery. You need to add jsonarray instead of html because it would be easy to put multiple data in json array and can get it easily in jquery .
In html i have added img tag to display image in output.
In php script, I have removed html and added json array for both the images.
In jquery script, I have replaced all img tag with src.
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 class="inputImage-text text-center">Input Image</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div id="targetLayer">No Image <img src="" id="intput-file-view"/></div>
<div id="uploadFormLayer">
<input name="fileToUpload" type="file" class="inputFile" /><br/>
<input type="submit" value="Submit" class="btnSubmit btn btn-primary" />
</div>
</form>
</div>
<div class="col-md-6">
<h2 class="outputImage-text text-center">Output Image</h2>
<div class="outputDiv">
<img src="" id="output-file-view"/>
</div>
</div>
</div>
</div>
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage);
echo json_encode(array("inputImage"=>$targetPath,"outputPath"=>$outputImage));
exit;
}
echo json_encode(array("inputImage"=>"","outputPath"=>""));
exit;
}
}
?>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
var response=JSON.parse(data);
if(response.inputImage != "" && response.outputPath != ""){
$("#intput-file-view").attr("src",response.inputImage);
$("#output-file-view").attr("src",response.outputPath);
}
},
error: function()
{
}
});
}));
});
</script>

Sending images from form with AJAX

I've been working on a form where you upload an image and a comment. I got it working in PHP, but now I'd like to do it in AJAX. The reason I'd like to do it in AJAX is because the user has to type all of their text again when the upload fails (due to conditions like: fields can't be empty or the aspect ratio of the image is off). However whatever I do, I fail to do it in AJAX.
I've tried to do it in FormData, with $.post and with $.ajax. I've also looked up a lot of guides, and other posts about this, but nothing seems to work for me.
Below you will find the HTML form, the jQuery AJAX call and the PHP code from the PHP page the AJAX call calls.
HTML FORM
<form action="uploadpost.php" id="postForm" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="postImage">Upload image</label>
<input type="file" id="fileToUpload" name="postImage" class="form-control">
</div>
<div class="form-group">
<label for="description">Write a caption</label>
<textarea name="description" id="postMessage" cols="30" rows="5" class="form-control"></textarea>
</div>
<input type="submit" id="postSubmit" value="Create post" name="upload_image" class="btn btn-primary">
</form>
The AJAX call
<script type="text/javascript">
$(document).ready(function(){
$("#postSubmit").on("click", function(e){
var formData = new FormData($("#postForm"));
//var message = $("#postMessage").val();
$.ajax({
url: "ajax/postUpload.php",
type: "POST",
data: formData,
contentType: "multipart/form-data",
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
e.preventDefault();
});
});
The PHP code in ajax/postUpload.php
<?php
include_once("../classes/Post.class.php");
$post = new Post();
var_dump($_FILES);
if(!empty($_POST)){
$file_tmp_name = $_FILES['postImage']['tmp_name'];
$result = $post->createPost($file_tmp_name);
if($result){
$uploadCheck['check'] = "success";
}else{
$uploadCheck['check'] = "error";
}
header('Content-Type: application/json');
echo json_encode($uploadCheck);
}
?>
Output from console.log(data) on ajax call return
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
The problem is that I can't send the image nor the message over to that PHP page, which doesn't allow me to do createPost().
var formData = new FormData($("#postForm"));
The argument to FormData should be a DOM form object, not a jQuery object.
new FormData($("#postForm")[0])
Setting the content type manually:
contentType: "multipart/form-data",
… will fail to set the boundary data in it. Say:
contentType: false,
… so that jQuery won't try to set it at all and the XHR object will generate it from the FormData object.

How to upload the file without submitting the form?

I am trying to upload a file with ajax and php without page refresh and for submit.
my code is able to run and alert the valid message if I just do the preg_match, but when I add the rest of the validation which need to use the $_FILES[$filrec]["tmp_name"], it won't alert me the valid message.
What is wrong here? isn't it possible to upload the file without submitting the form with the following method?
There are bunch of different suggestions and examples with more complicated javascript or jquery methods, but I am trying to simply the ajax and leave the rest for PHP. is that possible with my bellow ajax function ?
Javascript :
var fileselected = $("#browse").val().replace(/C:\\fakepath\\/i, '');
setTimeout(function() {
$.ajax({
type: 'POST',
url: "ajax/extval.php",
data: {fileprs: fileselected},
dataType: 'json',
cache: false,
success: function(resuval) {
// file validation result
if (resuval === "valid"){
alert ("valid")
PHP :
<form id="upload" method="post" class="<?php echo $orvalue."<separator>".$user_id ?>" action="" enctype="multipart/form-data">
<div id="formcontent">
<label class="required" for="unitprice" title="Unit price"><input type="text" id="unitprice" name="unitprice" />Unit price</label>
<label class="required" for="qty" title="How many pcs"><input type="text" id="qty" name="qty" />Quanity</label>
<label class="required" for="express" title="Express within China"><input type="text" id="express" name="express" />Express</label>
<label class="required" for="linkURL" title="Insert a full URL http:\\"><input type="text" id="linkURL" name="linkURL" />Link</label>
<label for="yourdesc" title="Describe your need clearly"><textarea id="yourdesc" name="yourdesc"></textarea>Description<li><font size="-2">You can type 400 letters only, you typed :</li><li id="lettercounter"></li>letters</font></label>
<label for="formsubmit" class="nocontent"><input type="button" id="submitButton" href="#" class="progress-button" value="Add to order" /><strong>Note:</strong> Items marked <img src="../../images/required.jpg" alt="Required marker" width="20" height="20" /> are required fields</label>
</div>
</form>
PHP :
$filrec =mysql_real_escape_string($_POST['fileprs']);
if(preg_match("/\.(gif|png|jpg|JPG|jpeg|bmp|BMP)$/", $filrec))
{
$fileType = exif_imagetype($_FILES[$filrec]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
$allin = "valid";
echo json_encode($allin);
}
Appreciated
You can use the following PHP code to get the file received from Ajax:
$data = split(",",file_get_contents('php://input'));
$img_data = base64_decode($data[1]);
file_put_contents( 'uploads/' . $_SERVER['HTTP_X_FILENAME'],
$img_data );
You can use Following Ajax POST Request this will help you
<script>
$(document.body).on('click','.postDefects',function(){
var form_data = new FormData();
var defect = $(this).closest('tr').find( "input[name='defect_id']" ).val();
var txt_defect=$("#text_defect").val();
var upload_defect = document.getElementById("upload_defect").files[0];
form_data.append("upload_defect",upload_defect);
form_data.append("defect_id",defect_id);
form_data.append("txt_defect",txt_defect);
console.log(form_data);
$.ajax({
url:"postsample_defects.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading..</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
});
});
</script>

$_FILES array is empty

This is the first time I am trying to upload a file and for some reason my $_FILES array is empty. I have checked again and again my HTML and it looks okay to me. When i try to debug the below code in eclipse the $_Files array is empty when i check it. I have checked the php_ini file it has:
file_uploads = On
upload_max_filesize = 2M
The form is in a fancybox modal window.
My HTML looks like this:
<form action="/CiREM/attachments/addAttachmentsModal.php?requestId=120" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="120"/>
<input type='hidden' id='listScreen' name='listScreen' value=""?>
<input type='hidden' name='MAX_FILE_SIZE' value='4000000' /><br/> <strong>Max File size Allowed: </strong>4 Mb <br/><strong>File Formats Allowed: </strong>gif,jpeg,jpg,png<br/><hr/> <div class="control-group">
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
</div>
<div class ="clear"></div>
<input id="addAttachmentsBtn" type="submit" class="btn btn-primary btn-large" value="Add Attachments"/>
</form>
My php is
<form action="<?php echo $_SERVER['PHP_SELF']."?requestId=".$requestId?>" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="<?php echo $requestId;?>"/>
<input type='hidden' id='listScreen' name='listScreen' value="<?php echo $listScreen;?>"?>
<?php
if ($CIREM['MAX_IMG_NUM']>0){
echo "<input type='hidden' name='MAX_FILE_SIZE' value='".$CIREM['MAX_IMG_SIZE']."' />";
echo "<br/> <strong>Max File size Allowed: </strong>".($CIREM['MAX_IMG_SIZE']/1000000)." Mb <br/><strong>File Formats Allowed: </strong>".$CIREM['IMG_TYPES']."<br/><hr/>";?>
<?php for ($i=1;$i<=$CIREM['MAX_IMG_NUM'];$i++){?>
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
<?php }?>
<?php }
else{
echo "<p class='alert alert-info'>Attachment uploading is not allowed</p>";
}
?>
Any help will be greatly appreciated.
Thanks,
Shakira
Without looking through that spaghetti code, first check whether your $_POST is also empty.
If it is, make sure that post_max_size is larger than upload_max_filesize. The two settings have to be congruent.
First of all sorry for the late reply but since sometimes people stumble upon old topics on stackoverflow, I decided to write the way it works for me.
So, to send files via ajax you have to use FormData.
I'll paste a link to a github project I have to submit forms via ajax so you can check the working example and paste here the snippet.
Link: https://github.com/pihh/auto-ajax-form
Code:
$( "form" ).on('submit',function( event ) {
if($(this).attr('ajax')){
event.preventDefault();
var marianaFormUrl = $(this).attr('action');
var marianaFormId = $(this).attr('id');
var marianaFormMethod = $(this).attr('type');
var marianaFormSucess = $(this).attr('success');
var marianaFormComplete = $(this).attr('complete');
var marianaFormBefore = $(this).attr('before');
var marianaFormInputs = $('#' + marianaFormId +' :input');
var marianaEncType = $(this).attr('enctype');
var marianaFormData = {};
// Set enctype
if(marianaEncType === undefined || marianaEncType == ''){
$(this).attr('enctype','multipart/form-data');
}
// Run Ajax Call
$.ajax({
url: marianaFormUrl,
type: marianaFormMethod,
dataType: 'JSON',
data: new FormData( this ),
processData: false,
contentType: false,
cache: false,
success:function(data){
// Run success
if(marianaFormSucess !== undefined && marianaFormSucess !== ''){
var fn = marianaFormSucess;
var func = fn +'( data )';
eval(func);
}
},
complete:function(data){
// Run complete
if(marianaFormComplete !== undefined && marianaFormComplete !== ''){
var fn = marianaFormComplete;
var func = fn +'( data )';
eval(func);
}
}
});
}
});
This is it, using formData it sends the files just fine.

Working with input type file AJAX/PHP

I have got this html/php in my index.php
if (isset($_POST['UploadMSub'])) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)) {
if ($fileP_error===0) {
if ($fileP_size<=2097152) {
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
$_SESSION['fileP']=$fileP;
$_SESSION['fileP_name']=$fileP_name;
$_SESSION['fileP_tmp']=$fileP_tmp;
$_SESSION['fileP_size']=$fileP_size;
$_SESSION['fileP_error']=$fileP_error;
$_SESSION['fileP_extension']=$fileP_extension;
$_SESSION['fileP_new_name']=$fileP_new_name;
}
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
And this ajax
$(".UploadMSub").click(function() {
var text=$(".Text").val();
var file=$("#Nameupload").val();
$.ajax({
type: "GET",
url: '../connect.php',
data: "Text=" + text+"&&file="+file,
success: function(data)
{
alert(data);
}
});
return false;
});
connect.php
if (isset($_GET['Text'])) {
$Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
$file=htmlspecialchars($_GET['file'],ENT_QUOTES);
echo $Text." ".$_SESSION['fileP_new_name'];
}
But when i submit form it returns(alerts)
"Undefine index ''fileP_new_name'"
Is there any other way of getting all information about file in my connect.php?
The problem is,
When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,
Undefine index: fileP_new_name
From your question,
Is there any other way of getting all information about file in my connect.php?
So the solution is as follows. You have to change few things in your code, such as:
Add a name attribute in your <textarea> element, like this:
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:
$(".UploadMSub").click(function(event){
event.preventDefault();
// your code
});
If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.
So your code should be like this:
HTML:
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
jQuery/AJAX:
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('form')[0]);
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data){
alert(data);
}
});
});
And on connect.php, process your form data like this:
<?php
if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
// both file and text input is submitted
$new_post = $_POST['new_post'];
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
// your code
//echo $fileP_new_name;
}
?>

Categories