1

I am trying to update an image in the my database. I have a modal that is loaded with jquery. When clicking on the save modification button, alla the form data shows up except for the image file, which does not show up in the $_FILES in php. I tried all the indication found on the web (php ini file enables file upload, images size is good). The code works if I use that classic submit method, but I don't want a full screen refresh, I need to do it all in ajax. Here is the html:

        $('#updatePubDevFrm').submit(function (e) {
            e.preventDefault();

 
            var data = $(this).serialize();
            alert(data);
            var url = '/PubDev/updatePubDev';
            $.post(url, data, null, 'json')
                    .done(function (data) {
                        if (data.status === "OK") {


                            $('#updatePubDevModal').removeClass('md-show');

                        } else {
                            alert("update error");
                        }
                    })
                    .fail(function (data) {
                        alert("ajax error");
                    })
                    .always(function () {

                    });



        });
<div class="md-modal md-effect-1" id="updatePubDevModal" >
    <div class="md-content">
        <div class="modal-header">
            <button class="md-close close">&times;</button>
            <h4 class="modal-title">Update Publisher/Developer</h4>
        </div>
        <form id="updatePubDevFrm" class="dz-clickable dropzone" action="/PubDev/updatePubDev" method="post" enctype="multipart/form-data">
           
            <div class="modal-body">
                <div class="row dropzone">
                    <div class="col-lg-5">
                        <div class="form-group">
                            <label for="pubDevName">System Id of Publisher/Developer</label>
                            <input type="text" placeholder="Name of Publisher/Developer" name="pubDevIdDisplay" id="pubDevIdDisplay" class="form-control input-large" disabled="true">
                            <input type="hidden"  name="pubDevId" id="pubDevId" >
                        </div>
                        <div class="form-group">
                            <label for="pubDevName">Name of Publisher/Developer</label>
                            <input type="text" placeholder="Name of Publisher/Developer" name="pubDevName-update" id="pubDevName-update" class="form-control input-large">
                        </div>
                        <div class="form-group">
                            <label for="date-founded">Date Founded</label>
                            <input type="text" placeholder="Date founded" id="date-founded-update" name="date-founded-update" class="form-control date-picker input-large">
                        </div>
                        <div class="form-group">
                            <label>What type of company is this?</label>
                            <div class="checkbox-nice">
                                <input type="checkbox" name="isPub-update" id="isPub-update">
                                <label for="date-founded-update">
                                    This company is a publisher
                                </label>
                            </div>
                            <div class="checkbox-nice">
                                <input type="checkbox" name="isDev-update" id="isDev-update">
                                <label for="isDev-update">
                                    This company is a developer
                                </label>
                            </div>
                        </div>



                    </div>
                    <div class="col-lg-7">
                        <div class="main-box clearfix main-box-frame" >
                            <header class="main-box-header clearfix">
                                <h2>Upload Publisher /Developer Logo</h2>
                            </header>

                            <div class="main-box-body clearfix imgcontainer center">
                                <img id="preview" src="" class="pointable" alt="No Image Available" style="max-height:100%; max-width: 100%; "/>
                                <div class="main-box-body clearfix">
                                    <div id="dropzone" class="drop-zone-frame" >

                                        <input type="file" name="image2" id="image2">


                                    </div>
                                </div>
                            </div>

                        </div>


                    </div>
                </div>

            </div>
            <div class="modal-footer">
                <button type="submit" id="confirmUpdPubdev" class="btn btn-primary">Save Modifications.</button>
            </div>
            
            
        </form>


    </div>
</div>

Here is the php code:

public function updatePubDev() {

    $fields = array();

    $fields[$this->pubdev->get_id_name()] = $this->input->post('pubDevId');
    $fields['name'] = $this->input->post('pubDevName-update');
    if ($this->input->post('date-founded'))
        $fields['date_founded'] = stampa_data_formato_DATE($this->input->post('date-founded-update'), '/');
    if ($this->input->post('isPub-update'))
        $fields['publisher'] = 1;
    else
        $fields['publisher'] = 0;

    if ($this->input->post('isDev-update'))
        $fields['developer'] = 1;
    else
        $fields['developer'] = 0;


    $row_count = $this->pubdev->update($fields,$this->pubdev->get_id_name());

    $file = $_FILES['image2'];

    //$idPubDev = $this->input->post("pubDevName");
    $ds = DIRECTORY_SEPARATOR;
    $path = dirname('../') . $ds . 'application' . $ds . 'assets' . $ds . 'img' . $ds . 'pub_devs' . $ds . 'logos' . $ds;
    //print_r($file);
    $info = new SplFileInfo($file['name']);
    //var_dump($info->getExtension());
    $filename = "logo_id_" . str_pad( $this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . "." . $info->getExtension();
    $result = $this->upload->uploadfile($file, $path, $filename);
    //echo "test";
    if ($result['status'] === "OK") {
        $logo = 'logo_id_' . str_pad($this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . '.' . $info->getExtension();
        $this->pubdev->update(array('logo' => $logo, $this->pubdev->get_id_name() => $this->input->post('pubDevId')), $this->pubdev->get_id_name());
        $result['message'] = "file saved successfully";
        $result['query'] = $this->db->last_query();
    }

    $result['update_rows']= $row_count;
    echo json_encode($result);
}

enter image description here

I tried the .ajax version, but the problem persist, here is the modified jquery:

        $('#updatePubDevFrm').submit(function (e) {
            e.preventDefault();


            var data = $(this).serialize();

            var url = '/PubDev/updatePubDev';

            $.ajax({
                url: url,
                type: "POST",
                data: data,
                processData: false,
                contentType: false
            })

                    .done(function (data) {
                        if (data.status === "OK") {


                            $('#updatePubDevModal').removeClass('md-show');

                        } else {
                            alert("update error!");
                        }
                    })
                    .fail(function (data) {
                        alert("ajax error!");
                    })
                    .always(function () {

                    });



        });

It is not a duplicate question because the answer provide contained different properties necessary to uplaod both image and data inputs. these two properties in the $.ajax call are needed:

 processData: false,
  contentType: false

This way, it solved my problem.

Salvo
  • 541
  • 6
  • 19
  • Can you include `php` at Question? – guest271314 Jul 18 '16 at 00:44
  • I've inserted the php code as well (it's codeigniter) – Salvo Jul 18 '16 at 00:50
  • everything before the "$file = $_FILES['image2'];" instruction works. Everything after it isn't executed at all. This code works in a normal situation without jquery and ajax however. – Salvo Jul 18 '16 at 00:52
  • Try substituting `$.ajax({type:"POST", processData:false, contentType:false})` for `$.post()` – guest271314 Jul 18 '16 at 00:55
  • In order to post files through jQuery you have to set `processData` option to false, `$.post` by itself does not set that, you have to use the second [`$.post()`](http://api.jquery.com/jQuery.post/#jQuery-post-settings) syntax and use a settings object – Patrick Evans Jul 18 '16 at 01:01
  • See http://stackoverflow.com/questions/11399484/posting-file-input-as-filereader-binary-data-through-ajax-post – guest271314 Jul 18 '16 at 01:01
  • Please look at the jquery code again. I'm sorry, but I am working on this all day and I didn't realize that the jquery was the incorrect version. I reloaded the jquery code and took out the print_r command. The problems is still the same however. – Salvo Jul 18 '16 at 01:02
  • I tried what you did but the problems persists – Salvo Jul 18 '16 at 01:18
  • Use `FormData` as `data` instead of `$(this).serialize()`; e.g., `var data = new FormData(); data.append("file", $(":file", this)[0].files[0])`. You can alternatively use `file_get_contents("php://input")` as described at posted Answer – guest271314 Jul 18 '16 at 01:22
  • See http://stackoverflow.com/a/36314992/ – guest271314 Jul 18 '16 at 01:28
  • Thanks! It worked! Please put it as an answer so that I can award you the correct answer. Thanks again. – Salvo Jul 18 '16 at 01:38
  • @Salvo Which approach returned expected result? Using `FormData` or `file_get_contents("php://input")`, or both? – guest271314 Jul 18 '16 at 01:49
  • the first one, using the mdata object and then the $.ajax method setting the two parameters that you said – Salvo Jul 18 '16 at 01:50
  • Possible duplicate of [How can I upload files asynchronously?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – Patrick Evans Jul 18 '16 at 06:05

2 Answers2

1

Use FormData as data instead of $(this).serialize();, set processData and contentType to false

   var data = new FormData();
   data.append("file", $(":file", this)[0].files[0]);
   $.ajax({
     url: "/PubDev/updatePubDev",
     type: "POST",
     data: data,
     processData: false,
     contentType: false
   })
guest271314
  • 1
  • 15
  • 104
  • 177
0

Please try to use file_get_contents('php://input'); to get the upload content.

闫兴茂
  • 16
  • 1
  • 3