I’ve got a issue here, i keep getting a error when i try to post something with ajax (POST). I know it is the CSRF that gives me these problems and I’ve been tried back and forth trying to find a solution. However, i hope somebody here can help me out!
This is the error i keep getting (from google chrome inspector),
*Failed to load resource: the server responded with a status of 500 (Internal Server Error)
XHR finished loading: "http://localhost/woho/ajax/images".*
PHP (Controller)
class Ajax extends CI_Controller {
function images() {
echo 'Hello World';
}
}
Javascript
var ID = $(".imageWrap:last").attr("id");
var baseurl = "http://localhost/woho/";
var doScroll = 1;
var cct = $.cookie('csrf_cookie_name');
if (location.href == baseurl) {
$(window).scroll(function(){
if ($(window).scrollTop() > $('body').height() / 2) {
if(doScroll == 1) {
$.post(baseurl + 'ajax/images',{'id' : ID, 'csrf_token_name': cct}, function(data) {
alert(data);
$("#wrapper_content").append(data);
ID++;
});
}
}
});
}
my CCT var from javascript gives me the correct token or "hash" but when the javascript sends the ajax request codeigniter returns an error like,
An Error Was Encountered The action you have requested is
not allowed.
How can i fix this? do i need to validate the CSRF Token or something in my controller?
I'm using Codeigniter 2.0.3
Try (javascript):
var ID = $(".imageWrap:last").attr("id");
var baseurl = "http://localhost/woho/";
var doScroll = 1;
var cct = $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");
if (location.href == baseurl) {
$(window).scroll(function(){
if ($(window).scrollTop() > $('body').height() / 2) {
if(doScroll == 1) {
$.post(baseurl + 'ajax/images',{'id':ID,'<?php echo $this->security->get_csrf_token_name(); ?>': cct}, function(data) {
alert(data);
$("#wrapper_content").append(data);
ID++;
});
}
}
});
}
check value of your $config['csrf_token_name'] in /application/config/config.php as default is setted as csrf_test_name not csrf_token_name.
This decision if you not want to use PHP code in Javascript.
$.ajax({
url: 'some_url',
type: 'POST',
data: {csrf_test_name: $.cookie('csrf_cookie_name')}
});
This code works fine.
If you use the form_open("/some",'id="some_form"') and form_close() , CI create a hidden input that keep the csrf_token_name and it value.
so , in your AJAX request , you can get the form by serialize it and send form !
For example:
<script>
var _form = $("#some_form").serializeArray();
$.ajax({
data: _form,
type: 'post',
url: '<?php echo base_url();?>some',
async: true,
success: function(output){
alert(output);
},
complete: function(output){},
fail: function(err){}
});
</script>
The CSRF always was my problem and by this method, it solved!!
it may be late but i found this perfect solution sort of hack but should work
if (isset($_SERVER["REQUEST_URI"]))
{
if(stripos($_SERVER["REQUEST_URI"],'/mypage') === FALSE)
{
$config['csrf_protection'] = TRUE;
}
else
{
$config['csrf_protection'] = FALSE;
}
}
else
{
$config['csrf_protection'] = TRUE;
}
// in config.php file ci 2.*
found solution from this post
I was facing same problem but now I have fixed this problem.
First of all, I have created csrf_token in header.php for every pages like below code
$csrf = array(
'name' => $this->security->get_csrf_token_name(),
'hash' => $this->security->get_csrf_hash()
);
<script type="text/javascript">
var cct = "<?php echo $csrf ['hash']; ?>";
</script>
After that, when we are sending particular value through ajax then we will have to sent csrf token like below code
$.ajax({
url:"<?php echo APPPATHS.'staff_leave/leaveapproval/getAppliedLeaveDetails'; ?>",
data:{id:id,status:status,'<?php echo $this->security->get_csrf_token_name(); ?>': cct},
method:"post",
dataType:"json",
success:function(response)
{
alert('success');
}
});
I hope this code will help you because this is working for me.
Just follow this code:
$.ajax({
type : 'post',
url : 'Your URL',
data : {
id: id,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
datatype: 'json',
success : function(data){}
});
Related
I am working on a multiple selection using chosen jquery. the values are already stored on an array. But im having problem with the AJAX post to send the values of the array to the controller. I already looked over the internet for solutions, spent so much time on reading articles here but non of it solves my problem. Please help.
Here is my code:
$(document).ready(function(){
var status = [];
var method = $(this).attr('data-method'); // confirm(status);
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
$("#test").chosen().change(function(e, params){
console.clear()
$("#test :selected").each(function(i,selected)
{
status[i] = $.trim($(selected).text());
// status.push($(this).val());
})
console.log(status);
var new_var = JSON.stringify(status);
// $('.statusArray').click(function(e){
$.ajax({
type: "POST",
url: "<?php echo site_url('request/buyer') ?>",
data: { data: new_var }
}).done(function(data) {
console.log(data);
alert( "Data Send:");
}).fail(function() {
alert( "Data Not Send" );
});
e.preventDefault();
enter code here
// });
}); });
I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard
Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>
Here is the view code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<!-- Load JQuery UI -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$( function() {
$("#input").autocomplete({
source: function(req, add){
$.ajax({
url: '<?php echo base_url(); ?>test/ac2',
dataType: 'json',
type: 'POST',
//data: req,
data: 'input='+req,
success: function(data){
if(data.response =='true'){
add(data.message);
}
}
});
},
minLength: 2,
select: function(event, ui){
$(this).end().val(ui.item.value);
}
});
});
</script>
</head>
<?php
echo form_open();
echo form_input('input', '', 'id="input"');
echo form_close();
?>
</html>
and the controller code:
class Test extends CI_Controller {
function index()
{
$this->load->view('vw/test_vw');
}
public function ac2()
{
//$search = $this->input->post('term');
$search = $this->input->post('input');
$data['response'] = 'false';
$this->db->select('*');
$this->db->from('loc_exercise');
$this->db->like('locations', $search);
$locations = $this->db->get()->result();
if (count($locations) > 0) {
$data['message'] = array();
foreach ($locations as $location) {
$data['message'][] = array( 'label' => $location->locations,
'item' => $location->locations,
'value' => $location->locations );
}
$data['response'] = 'true';
}
echo json_encode($data);
}
When I type anything in into the input box I get this on the console:
POST http://my.example.com/test/ac2 500 (Internal Server Error)
and on CI error logs there seems to be no issues (log_threshold is 1, /logs is chmod 777).
BTW I have my config.php with query_strings TRUE and allow_get_array TRUE.
Any ideas how to fix this issue?
This is almost certainly a CSRF token issue.
See this in the CI forums and this blog post
Nothing in your question suggests that you need to turn query_strings on or allow_get_array
Try this
comment out this line
$search = $this->input->post('term');
then add $search to your function as the first argument
public function ac2($search)
Then just try to hit the URL with a browser
http://yourdomain.com/index.php/test/ac2/<insert your search string here>
Now that we know your url is good
change your controller back.
try this...
data: 'term='+req, //<-- change to this
seems you are missing sendig the csrf token with the POST data, try:
$("#input").autocomplete({
source: function(req, add){
var cct = $("input[name=ci_csrf_token]").val(); // <---
$.ajax({
url: '<?php echo base_url(); ?>test/ac2',
dataType: 'json',
type: 'POST',
//data: req,
data: 'input='+req,
'ci_csrf_token': cct, // <---
success: function(data){
if(data.response =='true'){
add(data.message);
}
}
});
},
minLength: 2,
select: function(event, ui){
$(this).end().val(ui.item.value);
}
});
});
you can also find the token like:
csrf_test_name:$("input[name=csrf_test_name]").val(),
that token is generated in the view when using the form helper and opening it like:
<?php echo form_open();?>
sources:
* http://codeigniter.com/forums/viewthread/176318/
** own headache
Check your PHP code without the AJAX. Your error suggests that your PHP is the one that is causing the error.
One more thing it is quite better to see if you have results before you call ->result()
I am using jquery's AJAX in my project. Today, I used it somewhere else with all same themethods but it doesn't work.
Is there something wrong with my script?
HTML:
<a class='btn edit_receipe_btn' id='myreceipe-52'>Edit</a>
JQuery:
(Click function works. When I put alert(instance) after var instance line, it works)
$(document).ready(function(){
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
}
});
});
});
PHP:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
It appears the problem is in the PHP. What am I doing wrong?
Is that the entire PHP page? if so, you should echo instead of return
As Jasper De Bruijn notified me, the problem was in my php script. I should use echo instead of return:
Wrong usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
Correct usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
echo $instance;
}
Two things, output the error and check to make sure instance is not undefined.
Output the error like this:
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
},
error: function(response, status, error)
{
alert(response.responseText);
alert(status);
alert(error);
}
});
});
I think you have formed this POST like a get, not sure why. Try doing this in JS:
var dataString =
{
"process" : "userReceipeEdit",
"instance" : instance
};