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

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);
}
});
});

Related

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.

Need to be able to get the return string from javascript method in yii2

I am working on Yii2 and having a problem with returning the content of the javascript method to be sent when using the Html::a -hyperlink
The javascipt is in order to obtain the selected value of the checkboxes and it is outputting correctly.
<script>
function getNewPermissions() {
var permissions = '';
var rows = $(document).find('.permission');
$.each(rows, function (key, value) {
if($(value).find('input').prop('checked') == true)
permissions += value.id+'$&/';
})
permissions = permissions.substring(0, permissions.lastIndexOf("$&/"));
return permissions;
}
</script>
echo Html::a(Yii::t('app', 'Edit'), ['permissions/edit' ,'id'=> $name], [
'class' => 'btn btn-primary',
'onclick' =>'js:getNewPermissions()',
'data-method' => 'post',
'data' => [
'params' => ['newPerms'=>'js:getNewPermissions()','_csrf' => Yii::$app->request->csrfToken],
],
])
In the yii1 the value was read correctly from the params.
Just cant find any source to help get js in the params directly and the onclick does work.
in my project use another way
<a style="float:left;" class="btn btn-success" onclick="myFunction(this)"
type="<?php echo $value->id; ?>">
</a>
and use js function in end of layout
<script>
function updateSession(e)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
var pid = e.getAttribute('type');
var key = e.getAttribute('title');
var pqty = $("#id_" + key).val()
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/updatecard') ?>',
type: 'Post',
data: {
productid: pid,
key: key,
pqty: pqty,
_csrf: csrfToken
},
success: function (data) {
alert(data);
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcard') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#collapseCart").empty();
$("#collapseCart").append(data);
}
});
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcardpage') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#get_card2").empty();
$("#get_card2").append(data);
}
});
}
});
}
</script>

Ajax upload not working codeigniter

I am using codeigniter 3.1 . I want to post upload data using ajax.
Ajax upload file not working. But when i post the simple form without ajax, it working fine.
I don't know why but no error in console.
HTML
<?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?>
<input type="file" name="userfile" value="">
<input type="submit" value="Submit" />
<?php echo form_close() ?>
JAVASCRIPT
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this)
});
});
CONTROLLERS
public function post()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE
));
$this->upload->do_upload('userfile');
$data = $this->upload->data();
$image_file = $data['file_name'];
}
Another approach to this would be passing to PHP the file encoded in base64:
get the selected file from #userfile field using $('#userfile').prop('files')[0];
transform the contents of that file into a base64 encoded string using FileReader.readAsDataURL(). We're going to call this content; Here's a similar question showing how to do and expanding the answer & possibilities;
send the AJAX passing both the filename and content strings;
now on CI, fetch the POST data;
base64_decode() the content;
fwrite() the result into a file using the filename.
That way also you could avoid POSTing all form fields.
try this..
Post data using FormData() formdata post file also.
To get all your form inputs, including the type="file" you need to use FormData object.
$('#post').on('click', function (e) {
var file_data = $("#userfile").prop("files")[0];
var form_data = new FormData();
form_data.append("userfile", file_data)
$.ajax({
url: window.location.href+'/post',
type: 'POST',
data: form_data,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
For more...https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
One of the issues is that file uploading uses a different mechanism than the other form <input> types. That is why $this->input->post("userfile") isn't getting the job done for you. Other answers have suggested using javascript's FormData and this one does too.
HTML
A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit".... Doing so makes it a lot easier for the javascript to use the FormData object.
FormData documentation
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-2.2.2.js"></script>
<title>Upload Test</title>
</head>
<body>
<?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
<input type="file" name="userfile">
<p>
<input type="submit" value="Upload">
</p>
<?php echo form_close() ?>
<div id="message"></div>
<script>
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
</script>
</body>
</html>
JAVASCRIPT
Use FormData to capture the fields.
Note that instead of handling the button click we handle the submit event.
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
//uncomment the next line to log the returned data in the javascript console
// console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
CONTROLLER
I've added some code that "reports" results to ajax and will display it on the upload page.
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(['form', 'url']);
}
public function index()
{
$this->load->view('upload_v');
}
public function post()
{
$this->load->library("upload");
$this->upload->initialize(array(
"upload_path" => './uploads/',
'allowed_types' => 'gif|jpg|png|doc|txt',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$successful = $this->upload->do_upload('userfile');
if($successful)
{
$data = $this->upload->data();
$image_file = $data['file_name'];
$msg = "<p>File: {$image_file}</p>";
$this->data_models->update($this->data->INFO, array("image" => $image_file));
} else {
$msg = $this->upload->display_errors();
}
echo json_encode(['result' => $successful, 'message' => $msg]);
}
}
This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.
I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.
Controller
public function upload()
{
$this->load->library('upload');
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']))
{
if ($_FILES['myfile']['error'] != 4)
{
// Image file configurations
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->upload->initialize($config);
$this->upload->do_upload('myfile');
}
}
}
View
<form id="myform" action="<?php base_url('controller/method'); ?>" method="post">
<input type="file" name="myfile">
("#myform").submit(function(evt){
evt.preventDefault();
var url = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
},
error: function (error) {
console.log(error);
}
}); // End: $.ajax()
}); // End: submit()
Let me know if any query
you need to submit the form not on click but on submit ... give the form an id and then on submit put ajax
HTML
<?php $attributes = array('id' => 'post'); ?>
<?php echo form_open_multipart(site_url("upload/post",$attributes), ?>
<input type="file" id="userfile" name="userfile" value="">
<button id="post">Submit</button>
<?php echo form_close() ?>
JAVASCRIPT
$('#post').on('submit', function () {
var formData = new FormData();
formData.append("userfile",$("#userfile")[0].files[0]);
$.ajax({
url: window.location.href+'/post',
type: "POST",
data: formData
});
CONTROLLERS
public function post()
{
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$data = $this->upload->data();
$image_file = $data['file_name'];
$this->data_models->update($this->data->INFO, array(
"image" => $image_file
)
);
}

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

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;
}

Categories