0

I am not familiar with this problem I am facing.. I would like to upload image file through ajax & php

so far I have done these: HTML:

<input type="file" name="file" id="file" class="inputfile">
<label for="file">Choose a file</label>

ajax:

jQuery(document).ready(function($) {
var data = {

                business_name: $('#business_name').val(),
                business_country: $('#business-country').val(),
                business_region: $('#business-region').val(),
                business_phone: $('#business_phone').val(),
                //business_image: $('#image-data').val(),
                business_image: $('#file').val(),
                token: $('#token').val()
            }
$.ajax({
                type: "POST",
                data: data,
                url: "index.php?route=account/profile/savetoken=" + data.token,
            success: function(data) {
                $("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your profile has been successfully saved!</div>");
                }
            });    
});

I could get the path name of the image and store it to database.. But I could not upload the image on e specific folder..

I am using MVC model like openCart.. Actually I got the structure of OC, and building a dashboard from it..

Is there any way of using the tools already OC have like:

$this->load->model('tool/image');

otherwise, how could I upload images? serialize the form or something?

please be specific as possible so I could understand!

thanks in advance!

  • 1
    Possible duplicate of [jQuery Ajax File Upload](https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – splash58 Oct 30 '17 at 15:33
  • I believe this is something different.. cause I am talking about opencart... and a different system that I am trying to do.. But, I would appriciate some help of those I am reading in your link.. cause there is too much information.. and you are loosing me.. – Kiriakos Grhgoriadhs Oct 30 '17 at 15:36

2 Answers2

0

ok I solved my issue/error about my own question. I understood a lot actually about how openCart upload images, how ajax and xhr works and so on. Anyway, the code I have used is this:

Inside file profile.tpl:

$('#upload-image').on('click',function(e){
    var formData = new FormData($('#submitProfile')[0]);
    formData.append('route','account/profile');
    $.ajax({
        url: 'index.php?route=tool/upload/logo',
        type: 'post',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function() {
          $("#containerAlertMessages").html("<div class='alert alert-info'><strong>Sending...</strong></div>");
                    $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        complete: function() {
            $("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your logo has been uploaded successfully! Do not forget to save the abovr information by clicking the Save button at the bottom right corner!</div>");
            $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        success: function() {
            //nothing yet
        },
        error: function(xhr, ajaxOptions, thrownError) {
          alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    });

Inside file upload.php:

public function logo() {
        $this->load->language('tool/upload');

        if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
            $filename = html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8');


            $route = $this->request->post['route'];
            if($route == "account/profile") {
                $file = "image/" . $filename;
                move_uploaded_file($this->request->files['file']['tmp_name'], DIR_LOGOS . $file);
            }
        }
    }
  • DIR_LOGOS has been defined inside config.php file, so I could reffer to this variable again in another file if I want it to.
  • Furthermore, I am sending the route variable, in order to know from where the image upload is coming. So, if the uploading is coming from 'account/profile' I am saving the image to '/image' folder if its coming from 'accoun/register' I am saving to '/image/register' or whatever folder I want to (existing one or not), and so on

I hope that helps someone, with same issues!

-1

I use this code

index.php

if (!empty($this->request->files)) {
    foreach ($this->request->files as $key => $file) {
        if (!empty($file['name']) && is_file($file['tmp_name'])) {
            $filename = date('YmdHis') . rand(0,10000) . html_entity_decode($file['name'], ENT_QUOTES, 'UTF-8');
            move_uploaded_file($file['tmp_name'], "image/".$filename);
        }
    }
}

main.js

$('#pForm').on('submit',function (e) {
    e.preventDefault();

    $.post({
        url: 'index.php?route=ajax/index',
        data: new FormData(this),
        cache:false,
        contentType: false,
        processData: false,
        success: function () {
            //To do something
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
    });
})