4

Am trying to upload an image using Ajax to server. I know the code to upload file using Cakephp, but first i just want to make sure that data/file is uploaded to server for sure by printing the formdata. But it seems that only the data i typed in the textbox is posted and not the file i selected. Any help would be appreciated. Linking the code below

HTML

<form id="newcatform" method="post" action="<?php echo($this->Html->url(array('controller'=>'ajaxadmin','action'=>'newcategory'))); ?>" enctype="multipart/form-data">
            <div class="row" style="margin-top:20px;">
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h5>Create Category</h5>
                        </div>
                        <div class="panel-body">
                                <div class="form-group" style="padding:15px 0px;">
                                    <label class="col-lg-3 control-label">Category Name</label>
                                    <div class="col-lg-9">
                                        <input type="text" name="newcatname" id="newcatname" class="form-control input-sm valid">
                                    </div>
                                </div>
                                <div class="form-group" style="padding:15px 0px;">
                                    <label class="col-lg-3 control-label">Category Image</label>
                                    <div class="col-lg-9">
                                        <input type="file" name="newcatimage" id="newcatimage">
                                    </div>
                                </div>
                                <div class="form-group" style="padding:15px 0px;">
                                    <label class="col-lg-3 control-label">&nbsp;</label>
                                    <div class="col-lg-9">
                                        <button type="submit" class="btn btn-primary btn-sm">Create</button>
                                    </div>
                                </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>

JS

$('#newcatform').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData($('#newcatform')[0]);
        //formData.append("type", $("#newcatname").val());
        //formData.append("content", $("#newcatimage").prop('files')[0]);
        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

In Action Controller

if($this->request->is('post')){
            $this->Layout=null;
            $this->autoRender=false;
            $formdata=$this->request->data;
            print_r($formdata);
            exit;
        }

1 Answer 1

3

With this AJAX form submission approach, you will not be able to upload file using ajax.

If you don't like using a third-party plugin like dropzone.js or Jquery file upload, you can use XMLHttpRequest. An example below:

$('#newcatform').on('submit', function(ev){
    ev.preventDefault();

   var forms = document.querySelector('form#newcatform');

   var request = new XMLHttpRequest();

   var formDatas = new FormData(forms);
   request.open('post','yourControllerFunction');
   request.send(formDatas);

   request.onreadystatechange = function() {
    if (request.readyState === 4) {
      if (request.status === 200) {

       //Request was OK show success message

     } else {
                       // Request not OK, show error message

                     }
                   }
             });

In controller, use:

if($this->request->is('post')){
   $data = $this->request->data;
   echo "<pre>",print_r($data),"</pre>";
   //You should be able to see file data in this array
}
Sign up to request clarification or add additional context in comments.

6 Comments

Tried the code you suggested but still there is no file data when printing in controller. This was the o/p in console. Array ( [newcatname] => ASAS )
This works fine with me, and I do upload file without any problem. When you inspect your browser. click on network tab, then submit the form and see if there's any error.
I have edited my code to remove one extra closing " } ". Hopefully it should work fine. And also make sure you add the route of the function that is handling form submission to your route.php
used the same code but am only getting Array ( [newcatname] => awdawd ), file is still missing.. is there a need for setRequestHeader?
Show your full code you are using. Both XMLHttpRequest and controller
|

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.