Image not getting posted with ajax(without submitting the form) - javascript

My form is -
<form id="fileupload" method="post" enctype="multipart/form-data">
<input type="file" id="headerimage" spellcheck="true" class="typography" name="headerimage">
</form>
My ajax code is -
var fileData = new FormData($('#fileupload'));
fileData.append('imagefile', $('#headerimage')[0].files);
$.ajax({
type : 'post',
data : fileData,
url : 'UploadImage.php',
dataType: 'json',
processData: false,
success : function(data)
{
alert("done");
},
});
Php code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
var_dump($_REQUEST);
if (!empty($_FILES)) {
var_dump($_FILES);
}
Please Help. On the php page i am not getting file data.

HTML CODE:
<form id="fileupload" method="post" enctype="multipart/form-data">
<input name="userImage" id="uploadForm" type="file" class="inputFile" />
</form>
AJAX :
<script type="text/javascript">
$(document).ready(function (e){
$("#fileupload").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "UploadImage.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
});
</script>

Use this javascript
$(document).on("submit", "#fileupload", function(event)
{
event.preventDefault();
$.ajax({
url: 'UploadImage.php',
type: 'POST',
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data, status)
{
}
});
});

Try this...
//Image will upload without submit form
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
</div>
</form>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('change',(function(e) {
e.preventDefault();
$.ajax({
url: "UploadImage.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
{
}
});
}));
});
</script>
UploadImage.php
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>

JS code -
var form = document.getElementById('fileupload');
var fileInput = document.getElementById('headerimage');
var file = fileInput.files[0];
var formData = new FormData();
var filename = '';
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
filaname = xhr.responseText;
}
}
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
PHP code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
if (!empty($_FILES)) {
$file = $_FILES;
if ($file['file']['error'] == 0) {
$name = explode('.', $file['file']['name']);
$newName = "header.".$name[count($name)-1];
if (move_uploaded_file($file['file']['tmp_name'], "../assets/Themes/Default/".$newName)) {
echo $newName;
exit;
}
} else {
echo "";
exit;
}
} else {
echo "";
exit;
}

Related

How to upload and move file onclick button jquery using codeigniter?

With this code I want to insert and move a file into a folder but when I choose a file and upload it shows me an error in my console:
Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
How can I solve this problem? Please help me. Thank You
<input type="file" id="multiFiles" name="files" />
<button id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
$("#upload_file_multiple").click(function(event) {
event.preventDefault();
var form_data = new FormData($("#multiFiles"));
var id = "<?php echo $this->uri->segment(3) ?>";
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
processData: false,
contentType: false,
success: function(response) {
$('#afx_khjk').html(response);
},
error: function(response) {
$('#afx_khjk').html(response);
}
});
});
public function UploadFile($id)
{
if (isset($_FILES['files']) && !empty($_FILES['files']))
{
$rename = 'file_no-'.time().$_FILES["files"]["name"];
move_uploaded_file($_FILES["files"]["tmp_name"], 'uploads/syllabus/' . $rename);
$data = array(
'pdf'=>$rename,
'subjectID'=>$id,
'unique_id'=>time()
);
$this->db->insert('sylabus_pdf',$data);
$insert_id = $this->db->insert_id();
echo 'File successfully uploaded : uploads/syllabus/' . $rename . ' ';
$this->commondata($id);
}
else
{
echo 'Please choose at least one file';
}
}
The error is because the FormData constructor expects an FormElement object, not a jQuery object containing an input.
To fix this create the FormData object with the empty constructor and use append() to add your file:
var input = document.querySelector('#multiFiles');
var form_data = new FormData();
for (var i = 0; i < input.files.length; i++) {
form_data.append('files[]', input.files[i]);
}
Alternatively you can make this more simple by providing the form to the constructor. That way the data in all form controls will be included for you automatically.
var form_data = new FormData($('#yourForm')[0]);
HTML
<form id="frm_upload_file">
<input type="file" id="multiFiles" name="files" />
<button type="submit" id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
</form>
Ajax
$("#frm_upload_file").submit(function (event) {
event.preventDefault();
var id = "<?php echo $this->uri->segment(3) ?>";
var form_data = new FormData(this);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function (response) {
$('#afx_khjk').html(response);
},
error: function (response) {
$('#afx_khjk').html(response);
}
});
});

How to upload image using php , ajax on onchange event

I am uploading an image on onchange event using jquery ajax and php , the code is working but , but it is not uploading the image , showing undefined index photo on other page
index.php
<form id="reg" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="photo" id="photo" onchange="myfunction(this.form);" >
<span id="photoid"></span>
</div>
</form>
<script>
function myfunction(theForm) {
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'regimg.php',
data: formData,
success: function (data) {
$('#photoid').html(data);
},
cache: false,
contentType: false,
processData: false
})
}
</script>
regimg.php
<?php
include 'db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$photo = $_FILES['photo']['name'];
$query = mysqli_query($conn,"INSERT INTO img(image) VALUES('$photo')");
if ($query AND move_uploaded_file($_FILES['photo']['tmp_name'], 'image/'.$photo))
{
echo 'Data has been added';
}
else
{
echo 'data could not be added';
}
}
?>
When I click on the file then there one error showing, undefined index photo.
Please help me out in this problem
this in your function is the window, not the form element. Change the FormData line to :
var formData = new FormData(theForm);

JavaScript formdata multiple upload

I need to upload multiple files to a server using an ajax call.
Here is the code, every-time I am using it I am getting an upload error. The post is not working in the html side.
Below is the code I have used in html and php.
HTML
<input name="fileToUploadName" id="fileinput0" type='file' />
<input name="fileToUploadName" id="fileinput1" type='file' />
<input name="fileToUploadName" id="fileinput2" type='file' />
JS
function upload(){
var formdata = new FormData();
var image0 = $('#fileinput0')[0].files[0];
if(image0)
formdata.append('fileToUpload[]',image0);
var image1 = $('#fileinput1')[0].files[0];
if(image1)
formdata.append('fileToUpload[]',image1);
var image2 = $('#fileinput2')[0].files[0];
if(image2)
formdata.append('fileToUpload[]',image2);
$.ajax({
url: 'server.php',
type: 'POST',
data: formdata,
async: true,
dataType: "text",
success: function (data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
var p =0;
alert("Error uploading data");
},
cache: false,
contentType: false,
processData: false
});
}
server.php
if(isset($_POST['submit']))
{
$uploaddir = 'uploads/';
foreach ($_FILES['fileToUpload']['error'] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES['fileToUpload']['tmp_name'][$key];
$name = $_FILES['fileToUpload']['name'][$key];
$uploadfile = $uploaddir . basename($name);
if (move_uploaded_file($tmp_name, $uploadfile))
{
echo "Success: File ".$name." uploaded.<br/>";
}
else
{
echo "Error: File ".$name." cannot be uploaded.<br/>";
}
}
}
}
But every time I am getting an upload error.
Your problem is here, in your JavaScript file:
url: 'serever.php';
This should be
url: 'server.php';
This is, however, a simple typographical error.

Uploading files with Dropzone JS into child folder

I have a form in which I have a field for name and dropzone. So if I go with simple one like to upload files in main upload folder then it is working but I want to upload files in child folder like I am getting folder name through <input type="text" name="name" /> and on upload file should go to new generated folder.
HTML:
<input type="text" name="name" class="form-control fl_name" />
<div class="dropzone"></div>
JS:
// CREATE FOLDER FOR FILE UPLOADS
$('.name-alert').hide();
$('.fl_name').on('change', function() {
var fl_name = 'name='+ $(this).val();
var fl_url = $(this).closest('form').attr('action');
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
if (result == '0') {
$('.name-alert').slideDown();
setTimeout(function() {
$('.name-alert').slideUp();
}, 2000);
}
}
});
});
// CREATE DROPZONE ENVIORMENT
var myDropzone = new Dropzone('div.dropzone', {
url: "http://localhost/build/assets/php/customer-query.php",
addRemoveLinks: true,
init: function() {
this.on('success', function( file, resp ){
var fl_name = 'name='+ $('.fl_name').val();
var fl_url = 'http://localhost/build/assets/php/customer-query.php';
$.ajax({
type: 'POST',
url: fl_url,
data: fl_name,
cache: false,
success: function(result){
console.log(result);
}
});
});
},
});
PHP:
// Create Folder On Input Field Change
$fname = $_POST['name'];
if (!file_exists('../uploads/'.$fname.'/')) {
mkdir('../uploads/'.$fname.'/', 0777, true);
} else {
echo '0';
}
// Upload Files
$fl_name = $_POST['name'];
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../uploads/'.$fl_name.'/';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) .$ds. $storeFolder .$ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
in my code files are still uploading in main folder instead of new folders.
Thanks
Your "data" in the ajax call doesn't look like a json object. Try changing it to:
$.ajax({
type: 'POST',
url: fl_url,
data: {'name':fl_name},
dataType: "json",
cache: false,
success: function(result){
console.log(result);
}
});
See Passing data with jquery ajax if you need a further example on passing data with json via ajax
You may also be missing the following in your php file to read the json input:
$inputJSON = file_get_contents("php://input");
$result = json_decode($inputJSON,TRUE);
in which case you need to change
$fname = $_POST['name'];
to
$fname = $result['name'];

"You did not select a file to upload. " get this error while uploading image using ajax

I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.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,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document

Categories