Welcome Guest, Not a member yet? Register   Sign In
How to upload image in codeigniter 4
#1

Pls. help;
//view
<?=form_open_multipart( '', 'class="user_form" id="user_form"' ) ?>
<div class="form-group">
            <label for="avatar"> Avatar </label>
            <input class="form-control" type="file" name="avatar" id="avatar" />
        </div>

<button type="button" class="btn  btn-primary" onclick="add_user( '<?=$id?>')">Save changes</button>
<?=form_close();?>

<script>
function add_user( id = '') {
        var user_data    = $( '.user_form' ).find( 'input, select, button' );
        var form_data    = user_data.serialize();
        var form_data    = form_data + '&<?php echo csrf_token(); ?>:<?php echo csrf_hash(); ?>&id=' + id;
       
        $.ajax({
            type        : 'POST',
            url        : '<?=site_url( 'public/home/add_user' );?>',
            data        : form_data,
            async      : false,
            dataType    : 'json',
            success    : function( msg ) { }

})
}
</script>

//controller

function add_user() {
     $avatar = $this->request->getFile( 'avatar' );
      $avatar->move( WRITEPATH. 'uploads' );
}

result

i did not get any file upload.and it show Array()

pls help me
Reply
#2

I think this is messed up:
url : '<?=site_url( 'public/home/add_user' );?>',

doc root is 'public'. url should be '/home/add_user' where Home is the controller class. You don't need the site_url() function.

remove the second var:
var form_data = user_data.serialize();
form_data = form_data + '&<?php echo csrf_token(); ?>:<?php echo csrf_hash(); ?>&id=' + id;
make use of the error property of the ajax call to make it easier to see what's going on.
(why use ajax?)
Simpler is always better
Reply
#3

Read this:

Ajax Form Submit examples using jQuery
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4

(11-05-2019, 05:56 PM)donpwinston Wrote: I think this is messed up:
url        : '<?=site_url( 'public/home/add_user' );?>',

doc root is 'public'. url should be '/home/add_user' where Home is the controller class. You don't need the site_url() function.

remove the second var:
var form_data    = user_data.serialize();
      form_data    = form_data + '&<?php echo csrf_token(); ?>:<?php echo csrf_hash(); ?>&id=' + id;
make use of the error property of the ajax call to make it easier to see what's going on.
(why use ajax?)



Thank you .it worked
Reply
#5

(11-05-2019, 06:01 PM)InsiteFX Wrote: Read this:

Ajax Form Submit examples using jQuery
Thanks man this helped me lot
Reply




Theme © iAndrew 2016 - Forum software by © MyBB