Friday, September 9, 2022

[FIXED] how to deal with images in Codeigniter

Issue

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?


Solution

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/



Answered By - Pradeep
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.