how to deal with images in Codeigniter [duplicate] - php

This question already has answers here:
Ajax Upload image
(6 answers)
Closed 8 months ago.
In Codeigniter by using ajax i am adding record to (products) and everything is working fine so i decided to add (image) field , and for some reason it's no longer adding any record to database
and i add input type=file to my form
<input type="file" name="image">
and i add this to my controller
$image = $this->input->post('image');
$data = array('title'=>$title,'description'=>$description,'price'=>$price,'quantity'=>$quantity,'image'=>$image);
but when i remove $image = $this->input->post('image'); it gets to work again
just in case this is my ajax code
var postData = $(this).serialize();
$.ajax({
type:'post',
url: baseURL+"admin/Products/add_product",
data:postData,
dataType:'json',
success:function(data){
}
});
any ideas how to solve it?

Hope this will help you :
Your ajax should be like this :
var formdata = new FormData();
$.ajax({
type: 'POST',
url: baseURL+"admin/Products/add_product",
data: formdata,
cache: false,
contentType: false,
processData: false,
success: function(response)
{
alert(response);
}
});
In controller accessing image using $_FILES super variable
public function add_product()
{
print_r($_FILES);
print_r($this->input->post());
exit;
}
Note : make sure URL path is correct , see ur network tab to see the output
For more : https://www.formget.com/ajax-image-upload-php/

May Be You can use instead of baseURL
var formdata = new FormData();
$.ajax({
type: 'POST',
url: <?=base_url()?>+"admin/Products/add_product",
data: formdata,
cache: false,
contentType: false,
processData: false,
success: function(response)
{
alert(response);
}
});

Related

PHP Ajax Post File and Text Same Time

I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});

Uploading image and data using ajax and php

I am trying to upload firstname, lastname, description and image path to MySql database. And move uploaded image to specific folder.
Here is my ajax function
formData = new FormData(addPeopleForm);
var file_data = $('input[type="file"]')[0].file;
formData.append("file", file_data);
$.ajax({
type: "POST",
url: "functions.php",
contentType: false,
cache: false,
processData: false,
data: {
function: "savepeople",
data: formData
}, success: function(data){
console.log(data);
getPeople();
}
});
functions.php
if(isset($_POST['function'])){
$f = $_POST['function'];
if($f == "savepeople"){
require_once("config.php");
echo $_POST['firstname'];
.
.
.
you can not send directly image to php file with ajax call, you have to take form enctype="multipart/form-data" while form defination
and replace this code for file upload while ajax call
for appending file in formdata use below code
formData = new FormData(); //your form name
var file_data = $('input[type="file"]')[0].file;
formData.append("file", file_data);
formData.append("function","savepeople"); // new variable for your php condition
$.ajax({
url: "YOUR_FILE_PATH",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
// success operation here
},
and on php side you have to use $_FILES['YOUR_FILE_NAME'] instead of $_POST['YOUR_FILE_NAME'] for accessing a uploaded file on server.
you can try this code
$.ajax({
type:'POST',
url:'functions.php',
data:new FormData($('#my_form')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg)
{
console.log(msg);
}
});
return false;
where #my_form is your form id
var formData = new FormData($(this)[0]);
var action = "savepeople";
$.ajax({
url : 'functions.php',
type : 'POST',
data: {action:action,formData:formData},
contentType: false,
cache: false,
processData:false,
async : false,
, success: function(data){
console.log(data);
getPeople();
}
});
functions.php
if(isset($_POST['action']) && $_POST['action'] == "savepeople"){
//TO DO CODE
}

PHP ajax uploading images

I'm trying to do a file upload through ajax and php. The PHP works fine when called directly, but each time I call it through ajax it is failing. I'm not getting any errors (annoying) it just does not want to upload.
My JQUERY looks like
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
form_data.file = file_data;
console.log(form_data);
var fileType = $(this).parent().find('input[type="hidden"]').val()
console.log(fileType);
$.ajax({
url: '/docs/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
fileType:fileType,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});
and my PHP looks like
$file_upload="true";
$file_up_size=$_FILES['file_up'][size];
print_r($_FILES[file_up]);
if ($_FILES[file_up][size]>250000){$msg=$msg."Your uploaded file size is more than 250KB
so please reduce the file size and then upload.<BR>";
$file_upload="false";}
$file_name=$_FILES[file_up][name];
$add="medicalPaperwork/$file_name"; // the path with the file name where the file will be stored
if($file_upload=="true"){
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
echo "Thank god!";
}else{echo "Fuck you.";}
}else{
echo $msg;
}
What am I doing wrong? I'm going crazy trying to figure this out.
edit: the content of the form_data
You are using FormData incorrectly, use append to set the fields you want to upload
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
var fileType = $(this).parent().find('input[type="hidden"]').val()
form_data.append('file_up', file_data);
form_data.append('fileType', fileType);
console.log(form_data);
console.log(fileType);
$.ajax({
url: '/docs/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(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});

codeigniter file upload using AJAX

hello i have this function using AJAX. i need to retrieve the file's name size type and i will have to save it to my database..
here is my code.
function UploadImage() {
var data = new FormData($('#fileName'));
Jquery.each($('#fileName')[0].files, function(i,file) {
data.append(i,file);
}
$.ajax({
type: 'post',
data: data,
url: 'controller/function',
cache: false,
ContentType: false,
ProcessData: false,
success: function(data) {
alert(data);
}
}
when i will retrieve the data coming from the ajax request through my controller, i cant get the data of the files using _$Files[] it has error saying undefined index.
This may work for you
function UploadImage()
{
var data = new FormData(document.getElementById("fileName"));//remember fileName is your form id.
//You dont need this
/*Jquery.each($('#fileName')[0].files, function(i,file) {
data.append(i,file);
}*/
//you don't need to modify the data. data already contains whole form information.
$.ajax({
type: 'post',
data: data,
url: 'controller/function',//better use full path instead of relative path
cache: false,
ContentType: false,
ProcessData: false,
success: function(data) {
alert(data);
}
}

Can't use the array that php returns [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am getting an array returned from PHP which I json_encode() in php first and I echo that array. I get the array with an AJAX request disabling "Async". I know I shouldn't use that but it was the only way I could find.
It returns me this:
{"id":"38","name":"111111111111111111111111111111111111111111111.jpg"}
And this is my AJAX request:
function uploadFile(file){
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: 'inc/ajax/uploadFile.php', //Server script to process data
type: 'POST',
data: formData,
contentType: false,
processData: false,
async: false,
//Ajax events
success: function(html){
strReturn = html;
}
});
return strReturn;
}
When I do this I get the whole array:
var img = uploadFile(file);
console.log(img);
But when I call "img.name" or img.id" it says undefined.
You're receiving back a JSON string representation of an object. Tell jQuery that you're expecting JSON, so that it parses it into an actual Javascript object for you:
data: formData,
dataType: 'json', // Add this line
You need set dataType to json and you should use a callback you are probably returning strReturn before it is populated.
function uploadFile(file,callback){
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: 'inc/ajax/uploadFile.php', //Server script to process data
type: 'POST',
data: formData,
contentType: false,
processData: false,
dataType: "json",
//Ajax events
success: function(html){
strReturn = html;
callback(strReturn);
}
});
}
uploadFile(file,function(img){
console.log(img.name);
});
Try this:
function uploadFile(file){
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: 'inc/ajax/uploadFile.php', //Server script to process data
type: 'POST',
data: formData,
contentType: false,
dataType: "json",
processData: false,
//Ajax events
success: function(html){
strReturn = html;
return strReturn;
}
});
}
It says undefined because the strReturn is not defined at the moment you return it. The ajax's success method is called with a delay of some milliseconds so you have to return your variable after the ajax is finished.

Categories