1

Problem: Working on a save product information page here I wanted to upload images using Codeigniter and Javascript. Other text boxes and select box data save function working fine. Tried following code but it shows error: You did not select a file to upload.

Please help me to solve this error and upload an image file.

Code:

View: addProduct.php

    <div class="tz-2 tz-2-admin">
    <div class="tz-2-com tz-2-main">
        <h4>Add New Product</h4>
    <div class="split-row">
    <div class="col-md-12">
    <div class="box-inn-sp ad-inn-page">
    <div class="tab-inn ad-tab-inn">
    <div class="hom-cre-acc-left hom-cre-acc-right">
    <div class="">

    <form class="">
    <span id="statusBar"></span>
    <div class="row">
        <div class="input-field col s12">
            <input id="prod_id" type="text" class="validate" disabled>
            <label id="lblProdId" for="prod_id">Product ID</label>
        </div>
    </div>

    <div class="row">
    <div class="input-field col s12">
        <input id="prod_name" type="text" class="validate">
        <label for="prod_name">Product Name</label>
    </div>
    </div>

    <div class="row">
    <div class="input-field col s12">
    <input id="prod_short_name" type="text" class="validate">
    <label for="prod_short_name">Short Name</label>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <select id="prod_cat" class="validate">
            <option value="">-- Select Category --</option>
            <?php foreach($categories as $Category):?>
            <option value="<?php echo $Category->Cat_ID;?>"><?php echo $Category->Cat_Name;?></option>
            <?php endforeach;?>
        </select>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12" >
        <select id="prod_brand" class="validate">
            <option value="">-- Select Brand--</option>
            <?php foreach($brands as $brand):?>
            <option value="<?php echo $brand->Brand_ID;?>"><?php echo $brand->Brand_Name;?></option>
            <?php endforeach;?>
        </select>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <input id="prod_mrp" type="text" class="validate">
        <label for="prod_mrp">MRP</label>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <input id="prod_p_price" type="text" class="validate">
        <label for="prod_p_price">Purchase Price</label>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <input id="prod_s_price" type="text" class="validate">
        <label for="prod_s_price">Min. Selling Price</label>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <select id="prod_uom" class="validate">
            <option>-- Seletct Unit of Measure --</option>
            <option value="Kilos">Kilos</option>
            <option value="Liters">Liters</option>
            <option value="Meters">Meters</option>
        </select>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <input id="prod_size" type="text" class="validate">
        <label for="prod_size">Size</label>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <input id="prod_per_unit" type="text" class="validate">
        <label for="prod_per_unit">Products per unit</label>
    </div>
    </div>

    <div class="row">
    <div class="input-field col s12">
        <input id="prod_SGST" type="text" class="validate">
        <label for="prod_SGST">SGST</label>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <input id="prod_CGST" type="text" class="validate">
        <label for="prod_CGST">CGST</label>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <input id="prod_IGST" type="text" class="validate">
        <label for="prod_IGST">IGST</label>
    </div>
    </div>

    <div class="row">
    <div class="input-field col s12">
        <select id="prod_GST_inc" class="validate">
            <option value=""selected>Is Inclusive GST</option>
            <option value="Yes">Yes</option>
            <option value="No">No</option>
        </select>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <select id="prod_status" class="validate">
            <option>-- Select Status </option>
            <option value="Enabled">Enabled</option>
            <option value="Enabled">Disabled</option>
        </select>
    </div>
    </div>
    <div class="row">
    <div class="input-field col s12">
        <textarea id="prod_description" class="materialize-textarea validate"></textarea>
        <label for="prod_description">Descriptions</label>
    </div>
    </div>
    <div class="row tz-file-upload">
    <div class="file-field input-field">
    <div class="tz-up-btn"> <span>File</span>
        <input type="file" id="prod_image" > </div>
        <div class="file-path-wrapper db-v2-pg-inp">
            <input class="file-path validate" id="prod_image" type="text">
            <label for="prod_image" style="padding-left:12%;" >Product Image</label>
        </div>
    </div>
    </div>
    <div class="row">
        <div class="input-field col s12" id="btnSaveProd"> <a class="waves-effect waves-light btn-large full-btn" href="#!" onclick="ajax_addProduct();">Save Product</a> </div>
    </div>
    </form>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>


    <script>

    function ajax_addProduct(){

    event.preventDefault();

    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "<?php echo base_url();?>products/save";
    var prod_name = document.getElementById("prod_name").value;
    var prod_short_name = document.getElementById("prod_short_name").value;
    var prod_cat = document.getElementById("prod_cat").value;
    var prod_brand = document.getElementById("prod_brand").value;
    var prod_mrp = document.getElementById("prod_mrp").value;
    var prod_p_price = document.getElementById("prod_p_price").value;
    var prod_s_price = document.getElementById("prod_s_price").value;
    var prod_uom = document.getElementById("prod_uom").value;
    var prod_size = document.getElementById("prod_size").value;
    var prod_per_unit = document.getElementById("prod_per_unit").value;
    var prod_SGST = document.getElementById("prod_SGST").value;
    var prod_CGST = document.getElementById("prod_CGST").value;
    var prod_IGST = document.getElementById("prod_IGST").value;
    var prod_GST_inc = document.getElementById("prod_GST_inc").value;
    var prod_status = document.getElementById("prod_status").value;
    var prod_description = document.getElementById("prod_description").value;
    var prod_image = document.getElementById("prod_image").files[0].name;

    var vars = "prod_name="+prod_name+"&prod_short_name="+prod_short_name+"&prod_cat="+prod_cat+"&prod_brand="+prod_brand+"&prod_mrp="+prod_mrp+"&prod_p_price="+prod_p_price+"&prod_s_price="+prod_s_price+"&prod_uom="+prod_uom+"&prod_size="+prod_size+"&prod_per_unit="+prod_per_unit+"&prod_SGST="+prod_SGST+"&prod_CGST="+prod_CGST+"&prod_IGST="+prod_IGST+"&prod_GST_inc="+prod_GST_inc+"&prod_status="+prod_status+"&prod_description="+prod_description+"&prod_image="+prod_image;
        hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
        hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;

    if (return_data > 0) {
        document.getElementById("statusBar").className = "";
        document.getElementById("statusBar").innerHTML = "<p class='alert alert-success' style='font-size:16px; padding-top:2%; text-align:center;'>  <strong>Success...!</strong> New category added.</p>";

    //var elem = document.getElementById("btnSaveProd");
    //elem.parentNode.removeChild(elem);

        var elem = document.getElementById("lblProdId");
        elem.parentNode.removeChild(elem);

        document.getElementById("prod_id").value = return_data;
    }
    else{
        document.getElementById("statusBar").className = "";
        document.getElementById("statusBar").innerHTML = return_data;
    }

    }
    else {
        document.getElementById("statusBar").innerHTML = return_data;
    }
    }

    if (prod_name != "" && prod_short_name != "") {
        hr.send(vars);
        document.getElementById("statusBar").className = "alert alert-info";
        document.getElementById("statusBar").innerHTML = "processing...";
    }
    else if(prod_name == ""){
        document.getElementById("prod_name").className = "validate invalid";
        var elmnt = document.getElementById("statusBar");
        elmnt.scrollIntoView();
    }
    else if(prod_short_name == ""){
        document.getElementById("prod_short_name").className = "validate invalid";
        var elmnt = document.getElementById("prod_name");
        elmnt.scrollIntoView();
    }

    }
    </script>

Controller: Products.php

public function save()
  {

    $data['Prod_Name'] = $this->input->post('prod_name', TRUE);
    $data['Prod_Short_Name'] = $this->input->post('prod_short_name', TRUE);
    $data['Cat_ID'] = $this->input->post('prod_cat', TRUE);
    $data['Brand_ID'] = $this->input->post('prod_brand', TRUE);
    $data['Prod_MRP'] = $this->input->post('prod_mrp', TRUE);
    $data['Prod_P_Price'] = $this->input->post('prod_p_price', TRUE);
    $data['Prod_S_Price'] = $this->input->post('prod_s_price', TRUE);
    $data['Prod_UOM'] = $this->input->post('prod_uom', TRUE);
    $data['Prod_Size'] = $this->input->post('prod_size', TRUE);
    $data['Prod_Per_Unit'] = $this->input->post('prod_per_unit', TRUE);
    $data['Prod_SGST'] = $this->input->post('prod_SGST', TRUE);
    $data['Prod_CGST'] = $this->input->post('prod_CGST', TRUE);
    $data['Prod_IGST'] = $this->input->post('prod_IGST', TRUE);
    $data['Prod_GST_Inclusive'] = $this->input->post('prod_GST_inc', TRUE);
    $data['Prod_Status'] = $this->input->post('prod_status', TRUE);
    $data['Prod_Description'] = $this->input->post('prod_description', TRUE);
    $data['Prod_Image'] = $this->input->post('prod_image', TRUE);

    $this->do_upload();

    if ($pid = $this->Products_Model->saveProduct($data))
    {
      echo $pid;
    }
    else
    {
      echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong> Unable to add category.</p>";
    }

  }

  public function do_upload()
  {
      $config['upload_path']          = base_url(). "uploads/";
      $config['allowed_types']        = 'gif|jpg|png';
      $config['max_size']             = 100;
      $config['max_width']            = 1024;
      $config['max_height']           = 768;

      $this->load->library('upload', $config);

      if ( ! $this->upload->do_upload('Prod_Image'))
      {
              $error = array('error' => $this->upload->display_errors());

              echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong>".$error['error'].".</p>";
      }
      else
      {
              $data = array('upload_data' => $this->upload->data());

              echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong>".$data['upload_data'].".</p>";
      }
  }

Please help me to upload and save filename to the database.

NOTE: Don't want to use Jquery. Please suggest an answer with traditional Javascript.

8
  • Does this answer your question? You did not select a file to upload. PHP Code Igniter Commented Nov 8, 2019 at 12:47
  • @Vickel No, I'm not using form action. Just calling a Javascript function to save data. That is working fine but an image is not uploading. Commented Nov 8, 2019 at 14:04
  • You should add in your Products.php the upload library $this->load->library('upload'); Then you can attach anything from your files input with $_FILES Commented Nov 8, 2019 at 14:19
  • @FernandoUrban Sir, I have added upload library to autoload.php in the config folder. Commented Nov 8, 2019 at 14:29
  • Ok, so, what's the output result of do var_dump($_FILES) after $this->load->library('upload'); line ? Commented Nov 8, 2019 at 15:15

1 Answer 1

1

To submit the form with image and other data, use the below code

<?php echo form_open_multipart('', 'id="your_form_id"'); ?>
<?php echo form_close(); ?>

And script

$("#your_form_id").submit(function(e) {
e.preventDefault(); 
var form = $(this); 
$.ajax({
    type: "POST",
    url: "<?php echo base_url();?>products/save",
    data: new FormData(this),
    dataType: 'json',
    contentType: false,
    cache: false,
    processData:false, 
    beforeSend: function(){
       // your code here
    }, 
    success: function(json)
    {
       // your code here
    }
    });
}); 

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried enctype="multipart/form-data" in javascript it is also not working.
Sir, thanks for helping. but don't want to use jquery. Just Pure Javascript. I have tried this but it is also not working for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.