Here's a different approach. Simple function in Auth.php that returns the csrf token name and hash in JSON format. Then, in our javascript, make two ajax calls, the first to grab the csrf creds and insert them into hidden form fields, the second to handle our actual form submit.
// place function in Auth.php controller
public function get_csrf()
{
$csrf['csrf_name'] = $this->security->get_csrf_token_name();
$csrf['csrf_token'] = $this->security->get_csrf_hash();
echo json_encode($csrf);
}
// myFunction()
<script type="text/javascript">
function myFunction() {
// first ajax call to grab the csrf name and token
// from our get_csrf() function in Auth.php
$.ajax({
type: "GET",
dataType: 'json',
url: "https://<your_domain>.com/auth/get_csrf", //replace with your domain
success: function (data) {
// assign csrf name and token to variables
csrf_name = data.csrf_name;
csrf_token = data.csrf_token;
// assign field1 and field2 field values to variables
var form_field1 = document.getElementById('field1').value;
var form_field2 = document.getElementById('field2').value;
// insert csrf creds into form
$('#csrftoken').attr('name', csrf_name);
$('#csrftoken').val(csrf_token);
// second ajax call -- this is our form handler
$.ajax({
type: "POST",
url: "https://<your_domain>.com/<your_controller>/<your_function>", //replace with your domain/controller/function
data: {
// ES6 computed property keys are great...
[csrf_name] : csrf_token,
"field1" : form_field1,
"field2" : form_field2
},
success: function(data) {
// handle the return from your form submit
if (data == "ok") {
console.log("Success!");
$("#infoMessage").html("<p>Success</p>").fadeIn(300);
} else {
console.log("Oops!");
$("#infoMessage").html("<p>Oops!</p>");
}
}
});
}
});
}
</script>
// html
<div id="infoMessage"></div>
<form method="post" accept-charset="utf-8">
<input type="hidden" id="csrftoken" name="" value="" />
<label for="field1">Field 1:</label> <br />
<input type="text" name="field1" id="field1" />
<label for="field2">Field 2:</label> <br />
<input type="text" name="field2" id="field2" />
<input type="button" name="submit" value="SUBMIT" onclick="myFunction()" />
</form>