Search code examples
ajaxprototypejscodeigniter-2csrf-protection

codeigniter csrf protection error with ajax


i have a small problem here which i cannot fix,This post goes through but the response returns a “500 internal server error”

who to fix it?

after search in CI forum i found this this link codeigniter-csrf-protection-with-ajax but i cant solve by it.can any one help me?


Solution

  • You should include the csrf key in your AJAX POST request to get the action to work.

    However, you're only GETTING data, so using method:'get' instead of method:'post' should do the trick and make your request work.

    See this question for a wonderful discussion on when to use POST and when to use GET

    If you are, indeed, planning on POSTing data to the server, and it complains about the lack of the CSRF key, there are two ways to add it to the request:

    • use a plugin to allow prototype to extract the data from the csrf cookie that's being set by codeigniter; this might be more elegant, but would add a little more to your total scripts; here's a post with more detail on how to access cookies in prototype http://codeinthehole.com/writing/javascript-cookie-objects-using-prototype-and-json/

    • if you're sending this request from an existing form, it should have a hidden input field containing the key, which you would be able to simply access with something like var csrf = $("input[name=csrf_key]").val(); (This is jQuery syntax, but I'm sure the prototype version isn't too far away). If there isn't a form in that page, just write an echo form_open(); form_close(); somewhere to make sure the hidden field gets printed out by CI.

    Finally, make sure you send that value alongside the POST request, to make sure you're cool guy who doesn't want to hackz0r the server. You should add this parameter to the ajax request in JS:

    parameters: {'csrf_key' : csrf}
    

    Where csrf is the variable in which you fetched the key (from the cookie or from the hidden input). Make sure the names are alright! If you're fetching the cookie, make sure the cookie name coincides with the one set in config/config.php. Same goes for the input token!

    Hope this helps!