Viewed   233 times

I want to upload image on the server on change event of jQuery but using codeigniter csrf I am able to upload image only one time. How can I upload images using ajax for multiple requests.Please keep in mind when I set this

config['csrf_protection'] = FALSE;

then I am able to send multiple request jQuery onchange event but when csrf_protection is going to be false then I think there is no advantage of csrf. so the question is how can I send multiple requests using ajax while csrf_protection is enable. My jquery code is following

$("#avatar").change(function(){
    var link = $("#avatar").val();     
    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',"id":"hello","link":link},            
        success : function(data)
        {   
            alert(data);
        }  
    });
});

 Answers

3

In my opinion you should try to recreate your csrf token each request

Try this code example...

For the js funcion

var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>',
    csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
("#avatar").change(function(){
    var link = $("#avatar").val();

    var dataJson = { [csrfName]: csrfHash, id: "hello", link: link };

    $.ajax({
        url : "<?php echo base_url('main/test'); ?>",
        type: 'post',
        data: dataJson,            
        success : function(data)
        {   
            csrfName = data.csrfName;
            csrfHash = data.csrfHash;
            alert(data.message);
        }  
    });
});

and for the controller

public function test() { 
    $config['upload_path'] = './uploads/'; 
    $config['allowed_types'] = 'gif|jpg|png'; 
    $config['max_size'] = 500; 
    $config['max_width'] = 260; 
    $config['max_height'] = 260; 

    $reponse = array(
                'csrfName' => $this->security->get_csrf_token_name(),
                'csrfHash' => $this->security->get_csrf_hash()
                )

    $this->load->library('upload', $config); 
    if (!$this->upload->do_upload('link')) { 
        $reponse['message'] = "error"; 
    } 
    else { 
        $data = array('upload_data' => $this->upload->data()); 
        $image_name = $data['upload_data']['file_name']; 
        $reponse['message'] = $image_name; 
    } 

    echo json_encode($reponse);
}

Let me know and good luck

Note: When someone ask you for posting more data to the question, don't post it as a comment or answer, it's better to edit the question itself and adding the stuff

Friday, September 2, 2022
2

you are doing it wrong.

try this

    <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />

the value must be what codeigniter calculates for the csrf token.

or use form helper and codeigniter will add this hidden field automatically.

Thursday, December 8, 2022
 
4

Try this -> In your test.php file, give the action attribute as

action="<?php echo site_url();?>/static_data/test_add"

Then, in your practice.js file:

$('#test_form').submit(function() {
var tdata= $("#test_form").serializeArray();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = tdata;

Now, for testing, in your success function in practice.js, just write the following:

success: function(response) {
         console.log(response);
}

Here, the response you get is what your controller returns to you, now to test that, just type echo "hello"; or anything, just echo out something. (This is because you said teach me :) )

Now to see if this is working, open deveoper tools (if you are in google chrome), go to the console tab and then from bottom, select log, if everything is fine, it will return your echoed message written in your controller.

Also, to see if the form is submitted correctly, select the network tab, when you hit the submit button, the network tab will show you if the data has been submitted correctly or not.

Try this, if doesn't work, leave a comment.

Tuesday, October 18, 2022
3

Add the CSRF token to your data option before posting:

 $.ajax({
    type: "POST",
    url: $this.attr("action"),
    data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',/*....your data....*/},
    beforeSend: function() {
        mensaje.html('<p><img src="public/frontend/img/miniloader.gif"><span><small> Iniciando..</small></span></p>');
    }
})

The CSRF token needs to be sent with each request so it should be specified by the data. The echo statement does this. You can add this separately and serialize, but I've shown what you are missing.

Saturday, October 1, 2022
 
ericl
 
3

i think your problem may be in ajax code since you are using formData object . try append the message variable with it

$('#submit').on('click', function(){

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);
  fd.append('message ',$('#message').val());

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: fd,  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});
Saturday, November 12, 2022
 
malina
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :