Returning Uploadifive Ajax 'Error/Success' data from Codeigniter Controller

936 views Asked by At

I'm using the Uploadifive upload plug-in. It works as it should. However, I'm having a hard time passing error and success messages from my controller back to my view via the plug-in. I'm logging console and log errors. But can't seem to return any controller errors back to the Uploadifive call to display in my view.

In short, I want to output either an error or success message from my controller (via the $result var) back to my ajax function to embed into my view.

The alert, alert(data.result) outputs "undefined".

JS function:

$('#file-upload').uploadifive({                 
    ...

    'onUpload': function(file) {
        console.log('upload complete!');
    },
    'onUploadComplete' : function(file, data) {
        console.log('The file ' + file.name + ' uploaded successfully.');

        // returned error/success message here
        alert(data.result);

    },
    'onError': function(errorType) {
        console.log(errorType);
    }
});

CI Controller method:

function add_document() {

    // If Ajax request, proceed:
    if(isset($_POST['is_ajax'])) {

        if (!$this->upload->do_upload()) {
            
            // If file upload failed or is invalid, 
            // display error notification
            $result = array('error' => $this->upload->display_errors());
            echo json_encode($result);
        }       
        else {
            
            // If file upload was successful
            $result = 'success!';
            echo $result;

            ...
        }
    }
    // if not, redirect to upload page
    else {
        redirect('upload');
    }

}
1

There are 1 answers

0
Mike Barwick On

I figured out how to get this to work with my controller code. Uploadifive is not well documented, so it's been a shaky ride. But none the less, here's how I got it to function the way I wanted. Hopefully this helps others.

In my controller, I replaced the echo json_encode($result); line with the below. Specifying the array key I want to use (i.e. error) and the outputting of the result as html.

echo html_entity_decode($result['error']);

In my javascript function, all I simply needed to do was output the data... .result was not needed in the alert. Note, I decided to attach the result to some html versus an alert.

// Display Error/Success Messages
$('.status').html(data);