Welcome Guest, Not a member yet? Register   Sign In
ajax post csrf problem 403 error
#6

(This post was last modified: 04-17-2017, 05:53 AM by PaulD. Edit Reason: Added edit to top )

***** EDIT: A public get call to return the current hash is not a great idea. Return the new hash value as part of your original ajax call, not as a separate get. The following answer is just an example to get the idea across ******


So here is one way: (I am not saying this is the only way, the best way, or the most appropriate for your site, but it gets the idea across).

In your view:
Code:
<div id="csrf" data-token="<?php echo $this->security->get_csrf_hash(); ?>"></div>

In your js file
Code:
<script>

$("#atitle").on('input propertychange paste change', changeProperty);

function changeProperty(event) {
    event.preventDefault();
   
    /* collect data */
    var hashValue = $('#csrf').data('token');
    var aTitle = $("#atitle").val();
   
    /* create post data */
    var postData = {
         title: aTitle,
         mycsrf: hashvalue,
    };
    var url = '{$baseurl}Ajax/ar2eng';
   
    /* send post data */
    $.post(url,postData, function(theResponse) {
          /* you should do some validation of theResponse here first */
         $("#aslug").val(theResponse);
         /* refresh tokens on the page */
         refreshTokens();
   });
};

function refreshTokens() {
    var url = /* url to controller to return hash value */;
    $.get(url, function(theResponse) {
          /* you should do some validation of theResponse here too */
         $('#csrf').data('token', theResponse);
    });
}
</script>

In your controller that the refreshTokens function calls something like:

PHP Code:
public function get_tokens() {
 
// check user is logged in first of course
 
.....
 return 
$this->get_csrf_hash();


I have just typed this out so might be some typos in there. Where are you getting your {$base} from? I was assuming this was in a seperate js file loaded into the page with a script tag. If you are using placeholders with a template library loading a view for your js you may want to alter some of the above. If it is in a seperate file I would often do a similar read of the base url if it is going to be used in many sites, or hardcode a global variable in the js.

I have called your csrf token 'mycsrf' and hardcoded the name but you can always read in the token name via another data-token value in the 'csrf' div.

Anyway, I hope this helps and makes some sense.

Paul.

PS Just found this which is another explanation: https://forum.codeigniter.com/thread-612...#pid327081
Reply


Messages In This Thread
ajax post csrf problem 403 error - by arabgenius - 04-16-2017, 02:42 PM
RE: ajax post csrf problem 403 error - by PaulD - 04-17-2017, 02:31 AM
RE: ajax post csrf problem 403 error - by PaulD - 04-17-2017, 03:29 AM
RE: ajax post csrf problem 403 error - by PaulD - 04-17-2017, 05:46 AM



Theme © iAndrew 2016 - Forum software by © MyBB