How to upload files using ajax in Codeigniter? - javascript

I have a grid and in this list of data shown and every row has a edit action.
So when Edit button press a popup will open and in this i want to update data and upload a image regarding this selected row.
Data is successfully updated but image is not save in folder.
In Code What I did :
In ajax, i serialize all data when form submit but upload file post data is not showing so i am doing this -
var mts = $('#userfile').val();
var formdata = $('form[name=data_popup]').serialize()+'&IMG_URI='+mts;
console.log(formdata);
HTML Code:
<form action="#" method="post" enctype="multipart/form-data" name="data_popup">
<input type="file" name="userfile">
</form>
Jquery Code :
function update_cat(){
var mts = $('#userfile').val();
var formdata = $('form[name=data_popup]').serialize()+'&IMG_URI='+mts;
console.log(formdata);
$.ajax({
url: '<?=$this->config->base_url()?>admin_panel/update_data/',
type: 'post',
data: formdata
}).done(function(data) {
console.log(data);
});
}
Codeigniter Model Code:
$this->load->library('upload');
$config['upload_path'] = "./application/assets/images/logo";
$config['allowed_types'] = "gif|jpg|png|jpeg";
$config['file_name'] = date('dmYHis');
$this->upload->initialize($config);
$this->load->library('upload', $config);
$this->upload->do_upload('userfile');
$data_upload_files = $this->upload->data();
$image = $data_upload_files[file_name];

Use FormData for ajax upload
var formdata = new FormData($('form[name="data_popup"]')[0]);

This should work for you.
HTML
<form action="#" method="post" enctype="multipart/form-data" name="data_popup">
<input type="file" name="userfile" id="userfile">
</form>
JavaScript
function update_cat(){
var formData = new FormData();
var mts = $('#userfile').get(0).files[0];
formData.append('userfile', mts);
$.ajax({
url: '<?=$this->config->base_url()?>admin_panel/update_data/',
method: 'post',
data: formdata,
processData: false,
cache: false,
contentType: false
}).done(function(data) {
console.log(data);
});
}
PHP
<?php
$this->load->library('upload');
$config['upload_path'] = "./application/assets/images/logo";
$config['allowed_types'] = "gif|jpg|png|jpeg";
$config['file_name'] = date('dmYHis');
$this->upload->initialize($config);
$this->upload->do_upload('userfile');
$data_upload_files = $this->upload->data();
$image = $data_upload_files['file_name'];
Note: I didn't do much on the PHP part since I don't have a full understanding of what you want to do with the file.
Also ensure you call the javaScript function somehow.

Related

Sending images and text filed formdata ajax to php. images not identified by php

I have input text boxes of type text and one input text box of type file.I want to send these values to php file via ajax when a button is clicked. Everything seems well but for some crazy reason the image if not identified in the php file.
Kindly help, am out of ideas. My code is as below.
=========javascript code when a button if id=Saved is clicked====
$("#saved").on('click',function(){
$("#itemform").submit(function(e){
e.preventDefault();
});
var item_desc =document.getElementById("item_desc").value;
var item_price_type =document.getElementById("item_price_type").value;
var item_regular_price =document.getElementById("item_regular_price").value;
var item_type =document.getElementById("item_type").value;
var item_cat =document.getElementById("item_cat").value;
var taxablee =document.getElementById("taxablee").value;
var item_price_tax =document.getElementById("item_price_tax").value;
var item_offer_price=document.getElementById("item_offer_price").value;
var offer_start =document.getElementById("offer_start").value;
var offer_end =document.getElementById("offer_end").value;
var file =document.getElementById('file').value;
var price_tax="";
var formdata = new FormData();
formdata.append('file',file);
formdata.append('item_desc',item_desc);
formdata.append('item_price_type',item_price_type);
formdata.append('item_regular_price',item_regular_price);
formdata.append('item_type',item_type);
formdata.append('item_cat',item_cat);
formdata.append('taxablee',taxablee);
formdata.append('price_tax',price_tax);
formdata.append('item_offer_price',item_offer_price);
formdata.append('offer_start',offer_start);
formdata.append('offer_end',offer_end);
});
============php file to insert data into database===========
$item_desc =$_POST['item_desc'];
$item_price_type=$_POST['item_price_type'];
$item_regular_price=$_POST['item_regular_price'];
$item_type=$_POST['item_type'];
$item_cat=$_POST['item_cat'];
$taxablee=$_POST['taxablee'];
$price_tax=$_POST['price_tax'];
$item_offer_price=$_POST['item_offer_price'];
$offer_start=$_POST['offer_start'];
$offer_end=$_POST['offer_end'];
$item_image = $_FILES['file']['name'];
$folder = "../menu_images/";
$pics =time().$item_image;
//$sq="// this is my insert statment";
//$sq_insert =$conn->prepare($sq);
//$sq_insert->execute(array(//these are my array values for the insert
statment));
move_uploaded_file($_FILES["file"]["tmp_name"], $folder.$pics);
Why not use just a html form to submit your data, no need to use javascript for that.
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
});

Image upload via ajax POST without using HTML form

I am trying to send some data via POST method to a PHP file without using form in HTML. This is the code I have. Why doesn't it do anything?
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="hidden" value="<?php echo $row['Gallery_Id']; ?>" name="gid" id="gid">
<input type="hidden" value="User" name="user" id="user">
<button onclick="myFormData()">Upload Image</button>
<script>
$('#fileToUpload').on('change', function() {
var myFormData = new FormData();
var file = document.getElementById('fileToUpload').value;
var gid = document.getElementById('gid').value;
var user = document.getElementById('user').value;
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
});
$.ajax({
url: 'imgupload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
</script>
On imgupload.php I get the POST data like this
$gid = $_POST['gid'];
$user = $_POST['user'];
It worked when I used the HTML form method. What's wrong here?
FormData.append() takes key-value pairs, so this is wrong:
myFormData.append(file,gid,user);
You need something like:
myFormData.append('file', file);
myFormData.append('gid', gid);
myFormData.append('user', user);
Appart from that you need to put this code inside an event handler so that it triggers when you need it to.
For example:
$('#fileToUpload').on('change', function() {
// your javascript code
});
And you should probably also put it inside a document.ready block.

Isset does not work with ajax call

I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.

Save photo from user with AJAX and PHP

I have a problem with saving photos with Ajax and PHP.
This is my form in HTML
<form id="form3">
<input id="photo3" name="photo" class="form-control" type="file" id="fileInput3" />
</form>
And this is my JS
data = $("form#form3").serializeArray();
var file = $("#photo3")[0].files[0];
data.push({name: "photo", value: file});
$.ajax({
url: 'registrace.php',
data: data,
complete: function (response) {
alert(response.responseText);
},
error: function () {}
});
And this is PHP
$output = 'users/'.$namernd.'.jpg';
move_uploaded_file($_GET['photo'],$output);
Everything is copied to my database and works, but photo is not saved to my server.
Ok, i found solution. Just change to this:
var formdata = new FormData();
formdata.append('name', $('#name3'));
formdata.append('password', $('#password3'));
formdata.append('city', $('#city3'));
formdata.append('email', $('#email3'));
formdata.append('file', $('#photo3')[0].files[0]);
And
$namernd = uniqid();
$output = 'users/'.$namernd.'.jpg';
move_uploaded_file($_FILES["file"]["tmp_name"],$output);

How do I add additional POST parameters to ajax file upload?

I'm using ajax file upload javascript and php script to upload an image. It works satisfactorily with $_FILES but I need to send some additional data to the processing script. The form HTML looks like:
<form id="image1" action="" method="post" enctype="multipart/form-data">
<label>image 1?</label>
<p><input type="file" class="saveImage" name="image1" value="<?php echo $something; ?>" id="<?php echo $id; ?>" additional_info="some data" /></p>
<p> <input type="submit" value="Upload" class="submit" /></p>
</form>
I need to be able to pass a variable id and some other data, call it "additional_data" to the php script, then process it in my php script using $additional_data = $_POST['additional_data']. The javascript I'm using is:
<script>
$(document).ready(function (e) {
$("#image1").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var DATA=$(this).val();
var ID=$(this).attr('id');
var ADDL=$(this).attr('additional_data');
var dataString = 'image1='+DATA+'&id='+ID+'&additional_info='+ADDL;
$.ajax({
url: "uploadFile.php",
type: "POST",
// data: new FormData(this),
data: new FormData(this,dataString),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
It doesn't send the dataString, only the FILES array.
I also wanted to do the same thing.
Here's my solution :
The JS part :
var file_data = this.files[0];
file_data.name = idaviz +'.pdf';
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append('extraParam','value231');
console.log(file_data);
console.log('here');
var oReq = new XMLHttpRequest();
oReq.open("POST", "ajax_page.php", true);
oReq.onload = function (oEvent) {
if (oReq.status === 200) {
console.log('upload succes',oReq.responseText);
} else {
console.log("Error " + oReq.status + " occurred when trying to upload your file.<br \/>");
}
};
oReq.send(form_data);
});
The PHP part:
echo $_REQUEST['extraParam']; //this will display "value231"
var_dump($_FILES['file']); //this will display the file object
Hope it helps.
Addition info about extra parameters on formData can be found
here!
I hope I understand you right. Maybe this snippet helps you:
var formData = new FormData();
formData.append("image1", fileInputElement.files[0]);
formData.append("ID", ID);
formData.append("ADDL", ADDL);
And then set this formData variable as data:
type: "POST",
data: formData,
contentType: false,

Categories

Resources