Welcome Guest, Not a member yet? Register   Sign In
uploading and preview image with ajax

hello, im doing a function to upload photo. i would like to use ajax for user to preview the photo before submitting the form. so basically i want the user to click onto preview button where it will use ajax to preview the img to the user by saving the img file in a temp folder.

here is my code for the html:
<form name="frmregister" method="post" action="http://url/codeigniter/upload/do_upload" enctype="multipart/form-data">
<input type="hidden" name="post" value="1" />        
Upload a photo: <input type="file" name="file" id="file" /><input type="submit"  name="preview" value="preview">
<input class="button" type="submit" name="upload" value="upload" />

i found a ajax file on CI forum. it looks like this:
var ajaxPost = function() {
    // Get request object
    function getRequest() {
        if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else if (window.ActiveXObject)
            return new ActiveXObject("Microsoft.XMLHTTP");
            alert('Ajax not supported');
        return null;

    // Basic callback - could add error handler if you wanted
    function handleChange(req, callback) {
        if(req.readyState == 4) {
            if (req.status == 200) {
                if (callback)
            else {
                alert("Ajax request failed.");

    // Create query string from json object
    function handleParams(params) {
        if(!params) {
            return null;
        else {
            var encoded = "";
            for (var field in params) {
                fieldval = params[field];
                encoded += field + '=' + fieldval + '&';
            return encoded;

    // Combine it all in one pretty interface
    return function(uri, callback, data) {
        var request = getRequest();
        request.open('POST', uri, true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.onreadystatechange = function() { handleChange(request, callback) };
        return request;

can someone show me how to go about doing this. tks

did you found the way to do this already?
care to share?

can you share this please..

Notice this line in that code ?
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
File uploading in requires Content-Type to be multipart/form-data.
As far as I know, XMLHttpRequest currently doesn't support multipart/form-data.

But you can still Ajaxify your file uploader by setting target attribute of your uploader form to some hidden iframe. Go to some search engine and search for "Ajax file uploader". You will get lot of examples in PHP.
Once you have understood how it works it will be very easy for you to do it in Code Igniter.

Theme © iAndrew 2016 - Forum software by © MyBB