Codeigniter CSRF valid for only one time ajax request

前端 未结 9 892
鱼传尺愫
鱼传尺愫 2020-12-03 11:46

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 mul

9条回答
  •  难免孤独
    2020-12-03 11:53

    Please try like my code. its working my application

    your view file

    $token_name = $this->security->get_csrf_token_name();
    $token_hash = $this->security->get_csrf_hash();
    
    
    
    

    after set jquery post method like below

    // Get Keyup 
    jQuery( "#search-text").keyup(function() {
        // Get Data 
        var val       = jQuery("#search-text").val();
        var hashValue = jQuery('#csrf').val();
    
        // Get jquery post for ajax task
        jQuery.post( 
            '',
            {val:val,'security->get_csrf_token_name(); ?>':hashValue}, 
            function(data)
            { 
                // Get return data to decode
                var obj = jQuery.parseJSON(data);
                // Get csrf new hash value
                var new_hash = obj.csrfHash;
                // Set csrf new hash value update
                jQuery('#csrf').val(new_hash);
    
            }
        );        
    
    });
    

    please set your controller like below

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

    above all code recreate your csrf token each request.

提交回复
热议问题