-2

I want to upload photo with jquery-ajax in CodeIgniter. First I want to pass file to my controller for just check my AJAX call properly working or not. My code is not posting anything to my controller. I posting my code here, please show me my fault

Here is my code

jQuery and my input of my view is here (profile_view.php)

<script type="text/javascript">
$(document).ready(function() {
    $("#file1").on("change", (function() {
        $("#showimage").fadeIn("slow").html('');
        $("#showimage").fadeIn("slow").html('Plaese Wait...');
        alert('hello');
        $("#frm1").ajaxForm({
            target: '#showimage',
            success: function(response) {
                alert(response);
            },
            error: function(err) {
                alert(err);
            }
        }).submit();
    }));
</script>

My input code is here

<div id="photoframe">
    <form name='frm1' id="frm12" enctype="multipart/form-data" method="post" action="upload_photo">
        <input type="file" name="file1" id="file1" style="visibility:hidden" />
    </form>
    <a style="color:white"><i class="fa fa-edit" id="img1">Edit  Photo</i></a>
    <div id="showimage" name='showimage'>
    </div>
</div>

My controller is Here (upload_photo.php)

class Upload_photo extends CI_Controller {
function __construct() {
    parent::__construct();
    $this - > load - > helper(array('form', 'url'));
}
public
function index() {
    $config['upload_path'] = '/user';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width'] = '1024';
    $config['max_height'] = '768';
    if (isset($_POST['frm1'])) {
        echo 'Image Uploaded';
        echo "post".$_FILE['frm1'];
    } else {
        echo 'Image Upload Failed';
    }
}
}

My output is : Image Upload Failed

halfer
  • 18,701
  • 13
  • 79
  • 158
jems
  • 61
  • 1
  • 12
  • add data in `data: $('form').serialize()` in ajax form submit, if it works.. – i'm PosSible Nov 26 '15 at 05:21
  • you aren't passing the file to the ajax your controler isn't design to save the file and,better start learning about file uploads – madalinivascu Nov 26 '15 at 05:21
  • You have not proper write Ajax call.There is no URL or data set in Ajax call further in HTML form your target is upload_photo.You have not even follow the basics of AJAX. First study how to write ajax call then do some work – rajausman haider Nov 26 '15 at 05:22
  • 4
    Possible duplicate of [How to use FormData for ajax file upload](http://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload) – madalinivascu Nov 26 '15 at 05:23

2 Answers2

0

I think there is problem with your request, You have not passed any data with that request, You can use following data method to pass data with ajax:-

$.ajax({
     url: "post.php",
     data: {
        id: 123
    },
     type: "GET",
     dataType : "json",
     success: function( json ) {
        // Do your code here for success
    },
     error: function( xhr, status, errorThrown ) {
        alert( "Sorry, there was a problem!" );
    },
     complete: function( xhr, status ) {
        alert( "The request is complete!" );
    }
});

And you can not send image file with these AJAX request.

Please change your PHP code also, something like following :-

if (isset($_FILES['frm1'])) {
   // Do your upload code here
}
else
{
    echo 'Image Upload Failed';
}
Harsh Sanghani
  • 1,626
  • 1
  • 10
  • 31
0

This is the ajax call for non processed data (in your case upload images):

var form = $('frm12');

        var formdata = false;

        if (window.FormData){
            formdata = new FormData(form[0]);
        }

        var formAction = form.attr('action');
        $.ajax({
            url: formAction,
            data : formdata ? formdata : form.serialize(),
            cache : false,
            contentType : false,
            processData : false,

            dataType: "json",
            type : 'POST',
            resetForm: true,
        })
        .done(function(data) {
           //returned response
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });

Please note the "processData: false", this is needed to tel ajax to not act as a standard data transfer.

"By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false." from http://api.jquery.com/jquery.ajax/. You can find here explaination about the jquery.ajax settings.

Is worth to mention that if you want to make some checks before sending the data to the server (and I reccoment this) you can also use the "beforeSend: beforeSubmit," setting where "beforeSubmt" is a function that you can implement where you will make all the needed checks (e.g. allowed file type, allowed file size and more...). If something fails than the data will not be uploaded.

Franco
  • 2,242
  • 1
  • 8
  • 18