i am trying to upload file using ajax.
form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php">
<div class="feedback-form-inputs col-5">
<div class="input-field">
<select id="type" required>
<option value="quiz">Quiz</option>
<option value="midterm">Midterm</option>
<option value="final">Final</option>
</select>
</div>
<div class="input-field">
<input type="text" id="professor"/>
</div>
<div class="input-field">
<input type="text" id="name"/>
</div>
<div class="input-field">
<input type="file" id="uploaded_file" name="file" accept="" required />
</div>
</div><!-- END feedback-form-inputs -->
<div class="clear"></div>
<input type="submit" value="submit" onclick="submit() />
<div id="upload-status"> </div>
</form>
my function for opening ajax are in the external file.
function addPastTest1(cid){
// form variables
var type = _("type").value;
var professor = _("professor").value;
var name = _("name").value;
var fileSelect = _('uploaded_file');
var status = _('upload-status');
event.preventDefault();
// Update status text.
status.innerHTML = 'Uploading...';
// Get the selected files from the input.
var file = fileSelect.files[0];
var FileName = file.name;
var FileSize = file.size;
var allowed = ["msword", "pdf","pages"];
var found = false;
// check if the extension of the file match the allowed ones
allowed.forEach(function(extension) {
if (file.type.match('application/'+extension)) {
found = true;
}
})
if (FileSize >10204){
status.innerHtml = 'File must be less than 1mb in size';
}
if (found==true){
// Create a new FormData object.
var formData = new FormData();
// Add the file to the request.
formData.append('file', file, FileName);
// Set up the request.
var ajax = ajaxObj("POST", "ajaxResponse.php");
ajax.onreadystatechange = function(){
if (ajaxReturn(ajax)==true){
if (ajax.responseText=='failed'){
status.innerHtml = "failed to upload file";
}
else {
status.innerHtml = 'uploaded';
alert(ajax.responseText);
}
}
}
ajax.send(formData); //ajax.send("f="+formData+"&t="+type+"&p="+professor+"&n="+name+"&cid="+cid+"&fn="+FileName);
}
}
so i am sending formData to the php. but at this point i can not take the file from form data and upload it to the server.
here is my php
// Ajax calls this code to add a past test
if (isset($_FILES['file']){
$file = $_FILES['file'];
$path = 'files/'.$type.'/'.$fileName;
$moveResult = move_uploaded_file($file, $path);
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
$path = 'files/'.$type.'/'.$fileName;
$sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')";
$query = mysqli_query($db_conx,$sql);
if (mysqli_affected_rows($db_conx)>0){
echo "success";
exit();
}
else {
echo "failed sql";
exit();
}
}
?>
Also i want to grab inputs with the file and process them together. Upload file, and insert inputs into database.
The simplest one I can find. :)
jQuery code
$("#form-id").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "file-to-call.php",
type: "POST",
data: new FormData(this),
cache: false,
processData: false,
success: function(data) {
//handle success
}
});
}));
HTML code
<form name='form1' method='post' enctype='multipart/form-data' id='form-id'>
<input type='submit' id='input' value='Upload' />
</form>
Related
I try to upload file then save filename to mysql the method is same as upload & save file to mysql.
But my problem still happen. error message is uploadedfile is undefined.
HTML :
<form id="flowlist">
<div class="form-group">
<label for="idcar" class="control-label">ID CAR</label>
<input type="text" name="idcar" id="idcar" class="text_field form-control" required>
</div>
<div class="form-group">
<label for="upload">Upload Minute Of Meeting</label>
<input type="hidden" name="MAX_FILE_SIZE" value="20000000">
<input id="upload" name="uploadedfile" type="file">
<input type="hidden" id="filenm" name="filenm" required>
<input type="hidden" name="action" value="updateflow">
</div>
</form>
JS Script (cms.js):
dialog = $( "#flow" ).dialog({
buttons: {
"Update Data":function() {
var params=$('#flowlist').serialize();
$.ajax({
type:"post",
url:"doserver.php",
data:params,
cache :false,
async :false,
success : function() {
$('input').val("");
$('textarea').val("");
table.row('.selected').draw(false);
location.reload();
return this;
},
error : function() {
alert("Data failed to input.");
}
PHP code (doserver.php):
case 'updateflow':
/* catch variable parameter */
$idcar = mysqli_real_escape_string($dbc,$_POST['idcar']);
$file= mysqli_real_escape_string($dbc,$_POST['filenm']);
$target_path = "mom/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
/* UPDATE */
$sql ="UPDATE monitor SET Mom = '".$file."'";
$sql.=" WHERE id_car LIKE '".$idcar."'";
$res =mysqli_query($dbc,$sql) or die(_ERROR30.":".mysqli_error($dbc));
}
else { echo "There was an error uploading the file, please try again!"; }
break;
Edit
add enctype="multipart/form-data"
<form id="flowlist" enctype="multipart/form-data">
</form>
Then make some change to ajax function :
"Update Data":function() {
var formData = new FormData(this);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
data:formData,
....
});
I have no error but the idcar wasn't updated and file wasn't uploaded.
if you are using jquery better using $('#flowlist')[0] instead of this. I have solved this using :
"Update Data":function() {
if(window.FormData !== undefined)
{
var formData = new FormData($('#flowlist')[0]);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
mimeType:"multipart/form-data",
data:formData,
...
});
}
}
I am very new to Codeigniter. I m trying to create a form with some text input field along with two image upload field. The image uploading working fine but the text input field value are not coming. Can anyone please check my code and tell me where I am doing wrong Here is my Code:
Front End
<body>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data"">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
</script>
Controller Script is this
public function upload(){
$uploadData = "";
//Get the details
$productName = $_POST['product_name'];
$productCode = $this->input->post('product_code');
$productLink = $this->input->post('product_link');
$uploadData = $productName.','.$productCode.','.$productLink;
// setting cofig for image upload
$config['upload_path'] = 'uploads/profile/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
//$config['max_size'] = '1024'; //1 MB
// Get the profile image
$errorMsg = "";
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
$errorMsg = 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/profile/' . $_FILES['file']['name'])) {
$errorMsg = 'File already exists : uploads/profile/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$errorMsg = $this->upload->display_errors();
} else {
$data = $this->upload->data();
$errorMsg = 'File successfully uploaded : uploads/profile/' . $_FILES['file']['name'];
$uploadData = $uploadData.','.$data['full_path'];
}
}
}
} else {
$errorMsg = 'Please choose a file';
}
//upload product screenshots
$config['upload_path'] = 'uploads/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
$link="";
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
$errorMsg = "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
$errorMsg = 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
$fileOriginalNmame = $_FILES["files"]["name"][$i];
$explodeFile = explode(".",$fileOriginalNmame);
$fileExtenstion = end($explodeFile);
$fileName = md5(md5(uniqid(rand(), true)).$_FILES["files"]["name"][$i]).'.'.$fileExtenstion;
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $fileName);
$link= $link.$fileName.',';
}
}
}
$uploadData =$uploadData .','. $link;
$errorMsg = $uploadData;
} else {
$errorMsg = 'Please choose at least one file';
}
echo $errorMsg;
}
And if anyone can improve my controller code that will be very helpful tnx.
FormData() Method:
As per our definition .FormData() submit a element data in a Key/Value form. The Form element must have a name attribute. One advantage of FormData() is now you can post a files on next page.
Simple Syntax:
var formData = new FormData(form);
Highlight Points:
This method does post files.
This method post complete form using Get & Post method including files.
var formData = new FormData();
formData.append('username', 'joe');
In addition you could add a key/value pair to this using FormData.append.
So your code broke because you need to pass value of input as key/pair format that you missed except for file.
Hope this will help you.
Please find solution describe below.
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
var inputs = $('#product-upload input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
formData.append(name, value);
});
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
Let me know if it not works for you.
I have seen this tutorial and tried Form submit with ajax without refresh
It was working fine when i had the php code in my index.php. But now when i added the js and copied the php code in reply.php . it's not working.
I am not even sure does the php works in same way with ajax or not .
someone please help me to submit this form in database .
index.php
begin snippet: js hide: false console: true babel: false -->
<div id="comment-box">
<div class="form-group">
<form method="post" id="reply" enctype="multipart/form-data" style="width: 85%;" >
<div class="input-group">
<input type="file" name="image2" class="file" id="imgInp"/>
<span class="input-group-btn">
<button class="browse btn btn-primary input-md" type="button" ><i class="glyphicon glyphicon-picture"></i>I</button>
</span>
<input type="text" placeholder="say something" class="form-control" name="comment"/><br/>
<span class="input-group-btn">
<button class="btn btn-info" >submit</button>
</span>
</div>
<div>
<img id="blah" src="/final/images/blank.jpg" style=" width:7%; float:left; " />
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reply').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'reply.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#fcomment-box').fadeOut('slow', function(){
$('#comment-box').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
</div>
and here is php reply.php:
[note: this was working fine when it was in the same index.php. i just copied the whole php code in reply.php]
<?php
// these php variables are from index.php . will this work now like these are included ??
$user =$_SESSION['user_email'];
$get_user = "select * from users where user_email='$user' ";
$run_user = mysqli_query($con,$get_user);
$row = mysqli_fetch_array($run_user);
$user_id2 = $row['id'];
$user_name2 = $row['user_name'];
if( $_POST ){
global $con;
global $user_id2;
$comment = $_POST['comment'];
$post_image2 = $_FILES['image2']['name'];
$image_tmp2 = $_FILES['image2']['tmp_name'];
$fileType = $_FILES["image2"]["type"];
$fileSize = $_FILES["image2"]["size"];
$fileErrorMsg = $_FILES["image2"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $post_image2); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$post_image2 = preg_replace('#[^a-z.0-9]#i', '', $post_image2);
$post_image2 = time().rand().".".$fileExt;
date_default_timezone_set("America/New_York");
$date = date('Y-m-d H:i:s');
if ( $_FILES['image2']['name']=='') {
$insert =" insert into comments (post_id,user_id,comment,author_name,date) values('$post_slug','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
else if($fileSize > 1048576) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 1 Megabytes in size.";
// Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
}
else if (preg_match("/.(gif)$/i", $post_image2) ) {
// This condition is only if you wish to allow uploading of specific file types
$post_image2 = 'resized_'.$post_image2 ;
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
else{
if (!preg_match("/.(gif|jpg|png)$/i", $post_image2) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
// Remove the uploaded file from the PHP temp folder
}
else{
move_uploaded_file($image_tmp2,"images/$post_image2");
// ---------- Include Universal Image Resizing Function --------
include_once("2ak_php_img_lib_1.0.php");
$target_file = "images/$post_image2";
$resized_file = "images/resized_$post_image2";
$wmax = 260;
$hmax = 380;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function -----------
$insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
}
}
?>
$(document).on("submit", "#reply", function(e){
e.preventDefault();
var fd = new FormData();
var file = $("#imgInp")[0];
fd.append("image2", file.files[0]);
fd.append("comment", $(this).find('input[name="comment"]').val());
$.ajax({
url: 'reply.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
}).done(function (data){
$('#fcomment-box').fadeOut('slow', function(){
$('#comment-box').fadeIn('slow').html(data);
});
}).fail(function(){
alert('Ajax Submit Failed ...');
});
});
i have the following html code:
<form class="dropzone" id="msform" enctype="multipart/form-data"> <!-- multistep form -->
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Account Setup</li>
<li>Post an Image</li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Fill in Some General Details</h2>
<h3 class="fs-subtitle">As Simple As This</h3>
<input type="text" name="update" id="title" placeholder="Update Title" />
<textarea name="description" id="description" placeholder="Short Description/Add On"></textarea>
<input type="date" name="expire" id="expire" placeholder="Expire By" value="Expire By" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<h2 class="fs-title">Upload Image</h2>
<h3 class="fs-subtitle">We currently only support images.</h3>
<div class="dropzone-previews dz-message" id="dropzonePreview">
</div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</fieldset>
</form>
</div>
</div>
<script>
Dropzone.options.msform = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "filepostupload.php",
autoProcessQueue: false,
autoDiscover: false,
addRemoveLinks: true,
uploadMultiple: false,
parallelUploads: 5,
maxFiles: 5,
paramName: "file",
previewsContainer: '.dropzone-previews',
clickable:'#dropzonePreview', //used for specifying the previews div
//used this but now i cannot click on previews div to showup the file select dialog box
// The setting up of the dropzone
init: function() {
var myDropzone = this;
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length === 0) {
var update = $('#title').val();
var description = $('#description').val();
var expiry = $('#expire').val();
var groupid = <?php echo $groupid ?>;
var request = $.ajax({
url: "updatesnofile.php",
type: "POST",
data: { update:update, description:description, expiry:expiry, groupid:groupid},
dataType:"text",
success: function(data) {
if (data=="success") {
alert('success');
} else {
alert(data);
}
},
error: function(request, err){
alert(err);
}
});
}else {
myDropzone.processQueue();
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sending", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("success", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
alert(response);
});
this.on("error", function(files, response) {
alert("error");
});
}
}
</script>
And my php script that does the file upload is :
<?php
session_start();
require 'config.php';
//I'm using mysql_ as an example, it should be PDO
$ds = DIRECTORY_SEPARATOR;
$foldername = "updatefiles/";
if (isset($_POST['update']) && isset($_POST['description']) && isset($_POST['expiry']) && isset($_POST['groupid'])){
$title= mysqli_real_escape_string($mysqli,trim($_POST['update']));
$description= mysqli_real_escape_string($mysqli,trim($_POST['description']));
$expire= mysqli_real_escape_string($mysqli,trim($_POST['expiry']));
$groupid= mysqli_real_escape_string($mysqli,trim($_POST['groupid']));
$fileupload = basename($_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath. $fileupload;
move_uploaded_file($tempFile,$targetFile);
$fileupload = mysqli_real_escape_string($mysqli,basename($_FILES['file']['name']));
$fileType = mysqli_real_escape_string($mysqli,$_FILES['file']['type']);
$fileSize = mysqli_real_escape_string($mysqli,$_FILES['file']['size']);
mysqli_query($mysqli,"START TRANSACTION;");
$ins = mysqli_query($mysqli,"INSERT INTO posts (category, description, posttitle, userid, expire, group_id) VALUES ('updates','".$description."', '".$title."','{$_SESSION['userid']}', '".$expire."','".$groupid."' )");
if (!$ins) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with first insert";
return FALSE;
}
$upd = mysqli_query($mysqli,"SET #post_id_in_posts = LAST_INSERT_ID()");
if (!$upd) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with setting postid";
return FALSE;
}
$del = mysqli_query($mysqli, "INSERT INTO files (post_id,f_name, f_type, f_size) VALUES (#post_id_in_posts,'".$fileupload."', '".$fileType."', '".$fileSize."')");
if (!$del) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo "Error with Second Insert!";
return FALSE;
}
// All succeeded
mysqli_query($mysqli,"COMMIT");
echo"success";
return TRUE;
}else {
echo"formwasnotsubmitted";
}
?>
However, it keeps telling me that the form was not submitted (which means the posting of the form by drop zone fails, and therefore the data isn't posted over when there are files, the ajax works though when there are NO files), can anyone find out why? thanks!
I have managed to find the mistake, it is something to do with the way Dropzone sends the 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>
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