Welcome Guest, Not a member yet? Register   Sign In
Jquery + file upload problems
#1

[eluser]DanTheMan[/eluser]
Dear all,

I have created a page that uploads a file using CI's file upload library. I only need to upload one file, so the library is perfect.


Today I have been updating parts of my web app to include jquery, which has gone well on the most part. I have however come up with a problem, which from a spot of research shows that it can't be done with jquery because of security issues.

My jquery posts my controller all the fields on the form, which checks for validation. If the validation is correct it uploads file, it not it displays erors. The post method on the jquery posts my form, however not the full path of the file. This means that the file library can not see the submit file and thinks the user has not submit a file.

Has anyone experienced this, is there any work-rounds?

Thanks for your help,
Dan
#2

[eluser]InsiteFX[/eluser]
You can try including this code in your html head section, it will create a variable with the CodeIgniter base_url that you have set in application/config/config.php

Now you can use base_url in js scripts, repalce the $ with s in the script tags.
Code:
<$cript type="text/javascript">
    //&lt;![CDATA[
        var base_url = '&lt;?php echo base_url();?&gt;';
    //]]>
</$cript>

InsiteFX
#3

[eluser]DanTheMan[/eluser]
Hi,

First, thanks for your reply.. That will be very useful to know and will help me alot in further development.

However, I don't see how it helps with my problem. Maybe I did not explain myself well to begin with.

I have a view, which uses javascript to post the user submission. This is so that the page does not need to be reloaded (its in tabs).

I use the following javascript to post this.

Code:
$('#detail_form').submit(function()
    {

    var form_data = {
        ajax:             1,
        name:             $('#name').val(),
        type:             $('#type').val(),
        num_guests:     $('#num_guests').val(),
        userfile:        $('#userfile').val(),
        min_stay:         $('#min_stay').val()
    };
        $.ajax(
        {
            type: 'POST',
            data: form_data,
            url: "&lt;?php echo site_url('accomodation/add_details'); ?&gt;",
            success: function(msg){
            if(msg == 1){
                [removed]('dashboard');
            }else{
                $('#error_messages').html(msg);
            }
                }
        });
        return false;
    });

I then go through general validation. If this validation passes I then move onto the posting of the file (in this case an image). This calls the model where I am doing my file submission.

Code:
if(! $this->upload->do_upload())
            {
                // wooops, there has been a problem
                //$error = $this->upload->display_errors();
                $data['error'] = $this->upload->display_errors();
                $data['status'] = FALSE;
                return $data;
            } else { //do something else... and move onto the manipulation..

The problem is, jquery does not submit the full path of the submission (I believe due to security issues). So even if the user submits a file, it says they have not. I have checked the post and for example, i can see this....

Code:
Parametersapplication/x-www-form-urlencoded
ajax    1
min_stay    1
name    Daniel
num_guests    1
type    whatever
userfile    random b&B capture.jpg
Source
ajax=1&name=Daniel&type=whatever&num_guests=1&userfile=random+b&B+capture.jpg&min_stay=1

I don't know how to make the file upload library in CI understand what is being submit.

Thanks again for your help! ;-)
#4

[eluser]carbona[/eluser]
Hi,

Well the problem is that you cannot upload a file by making a post call.
You can use this jquery plugin for uploading your file :
http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

carbona
#5

[eluser]DanTheMan[/eluser]
Hi,

The problem is, I don't want them to just upload the file. I want it to be part of the form creation process. So I am unsure how I would be able to use a plug-in like this to integrate with my code.

Thanks
#6

[eluser]byde[/eluser]
I had the same problem, a friend told me that you can not upload files usen ajax, I doubt it but i didnt try that way.

So what i did was to submit the form to a popup windows, let me share my code.

Code:
[removed]
var win= null;
function NewWindow(mypage,myname,w,h){
  var winl = (screen.width-w)/2;
  var wint = (screen.height-h)/2;
  var settings  ='height='+h+',';
      settings +='width='+w+',';
      settings +='top='+wint+',';
      settings +='left='+winl+',';
      settings +='scrollbars=yes,';
      settings +='resizable=yes';
  win=window.open(mypage,myname,settings);
  if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}
window.addEvent('domready', function() {
    $("uploadForm").addEvent('submit', function (e) {
        e.preventDefault();
        NewWindow('', 'subir_foto', 300, 400);
        this.target = 'subir_foto';
        this.submit();
    });
});
[removed]

          &lt;?php echo form_open_multipart('banners/do_upload', $attr);?&gt;
            <p><label>Imagen a subir &lt;input type="file" name="userfile" size="20" /&gt;&lt;/label></p> ...

banners/do_upload recibes the form data with the image, in the popup window you can use javascrpt to call functions in the openner one or close it

i did this
Code:
[removed][removed]
[removed]
window.addEvent('domready', function() {
//    window.resizeTo($("im").get('width'),$("im").get('height'));
    window.opener.ActualizarImg();
});
[removed]
<img src="&lt;?php echo base_url() ?&gt;&lt;?php echo $img; ?&gt;" width="200px" id="im" />
this last one (""window.opener.ActualizarImg();"") updates a list of images from ajax but in the openner window


As you can see, i did it with mootools, but it is very similar in jquery, actually in this code only changes the selector, i didnt find a jquery example

You can send me a PM so i can help you
#7

[eluser]skunkbad[/eluser]
Ajax uploader in the CI Wiki:

http://codeigniter.com/wiki/Ajax_Uploader/
#8

[eluser]DanTheMan[/eluser]
Hi,

The AJAX uploader seems fine. It will offer the ability for me to upload on the spot and then get the path of the file.

A few notes though;

1) There seems to be no documentation about this, in the download it has a controllers and my controllers, but no discussion if these are examples or if they are required. Has anyone any information on this?

2) I see a problem where if the user uploads the file, it submits the file to the folder. If they then submit my form to add a property (where my file uploader is located) then the returned page will loose the previous uploaded file path... meaning they will have to submit the picture again, clogging up the server.

In my non ajax script, I had the following solution:

1) User loads page with property form.
2) User types in details, including the form
3) User specifies file to upload
4) User submits
4) The controller checks validation of the data, if wrong it retuns an error on the same page
5) The controller checks the file upload, it will then create a thumb, return the filepath for use later... It will display errors in the view if exist.
6) Success, add to the database
#9

[eluser]skunkbad[/eluser]
I'm the one that added the ajax uploader to the wiki. No there isn't any documentation. It's just a simple example, and not meant to be anything more than that. It's a proof of concept; a foundation to start with, so that you can design the true functionality you desire. All of the files in the download are necessary to have that uploader example work. You might set up a test installation of codeigniter, install the files, and see how it works.

You could use javascript to alter a hidden form field so that when you do your upload it contains the path. You could also just add the path to a database, giving the image row an id and what it belongs to. I've actually created something much more complex for my own use, which can sort the images using drag and drop, delete images, etc.

I think if you spend some time playing around with those files, customizing them for your own application, you will create something that meets your needs.
#10

[eluser]DanTheMan[/eluser]
Dear Skunkbad,

I have installed your script and was trying to get it working in a test form. I have just added the files in the download to a test install.

I keep getting the following error when waiting a sucess response back from the file upload, however I can see behind the scenes the fileuploader works and uploads a file.

The error in firebug is the following, on line 627 of the ajaxupload.js;
missing ) in parenthetical
[Break On This Error] </div>{"status":"success","file_name":...n_flattend6.png","raw_name":"Dashboard

This is stopping the upload script from sending response to the view and updating the 'uploading file' page, or displaying in an alert box any errors.

I am using CI V2.

Thanks for your help,
Dan




Theme © iAndrew 2016 - Forum software by © MyBB