I’m currently working on a project with the framework CodeIgniter. I use jQuery 1.7.1 and i want to implement a ajax call with data to add a post message.
The strange thing is that the function works and returns the alert message without the extra data. But the function with the data returns a HTML 500 error (in console from chrome).
The requested page is nothing more then a php script echoing ‘It works!’.
Code that works:
$.post("/ajax/add_post_to_profile",
function(data) {
alert("Data Loaded: " + data);
});
Code that doesn’t work:
$.post("/ajax/add_post_to_profile", { msg: "My test msg!"},
function(data) {
alert("Data Loaded: " + data);
});
UPDATE:
Here the codeigniter controller that handles the requested page:
class PostController extends CI_Controller {
public function __construct(){
parent::__construct();
}
public function addPostToProfile() {
echo 'It works!!!';
}
}
Update 2:
I have tested the function with a new file request placed in the root of the app. And then it works like a charm.
It looks like the CodeIgniter controller is blocking the POST request or something..
Update 3:
I found out that it is the CSRF security of CodeIgniter. It works when I turn it off.
I searched the internet for a solution to keep the CSRF, but the code that I found doesn’t work :(.
<script>
$('#ajax_test').click(function() {
$.post("/ajax/add_post_to_profile", { msg: "My test msg!", csrf_token_name: "<?php echo $this->security->get_csrf_hash(); ?>"},
function(data) {
alert("Data Loaded: " + data);
});
});
</script>
Just a quick update with the vars in place, it works just tried it, thank you very much 😉
Now the function works fine with the CSRF enabled! Thanks for all the help!