Codeigniter ajax post csrf The action you have requested is not allowed - php

i have the ajax request for fetching the information if user is still logged in or not let's say checking its session, and also i have enabled the csrf protection also and the GET is working fine in all aspects but the problem is only with POST from ajax, i have also turned off the re-generation of token and also did pass the new token to every ajax request, but still it gives me an error :
The action you have requested is not allowed.
fetching token :
var getToekn = function(){
return $('meta[name=csrf_token]').attr('content');
}
call to userLog every 1 minute:
var userLog = function () {
var formdata = new FormData();
formdata.append('csrf_',getToken);
$.ajax({
url: site_url + 'action=userCheck',
type: 'post',
dataType: 'json',
data:formdata,
processData:false,
success: function (d) {
if (d.login === 'true') {
jQuery('meta[name="csrf_token"]').attr('content', d.csrf);
console.log('loggedin: True');
} else if (d.login === 'false') {
if (jQuery('#js_login_again').legnth) {
popup('js_login_again', 'o');
jQuery('meta[name="csrf_token"]').attr('content', d.csrf);
} else {
$.ajax({
url: site_url + '?pop=loginagain',
type: 'post',
dataType: 'html',
success: function (data) {
var popup = $(data).filter('#js_login_again');
jQuery('body').append(popup);
popup('js_login_again', 'o');
loading('h');
}
});
}
}
}
});
}
i did check if the sent token is correct or not and it is a correct token but the ajax post request still results to an error The action you have requested is not allowed.
The thing is i'm already giving the csrf token to ajax request and the token is being also added to the parameters sent to the url, so it's not the case of token , i'm just lost about why it does so.
also did check the $this->input->post('csrf_'); it's empty.

Related

AJAX call is not working as expected

I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.

Avoid showing login page when session is expired in ajax call

I have a web application developed in codeigniter framework.
My issue is , i have lot of ajax calls in my backend, now on ajax call if session is expired, its showing login page in place where I wanted to load dynamic data.
How can I solve this issue without changing in all my ajax calls?
$.ajax({
url: "<?= base_url("controller/method") ?>",
data: {key1: value1,key2: value2},
type: "POST",
dataType: "HTML"
success: function(){
// here i'm processing the response.
}
});
Ok so there is a easy solution for this,
In server side;
if($_SESSION['loggedin']=='false') //assuming the login check
header('app-stat : loggedout') //send custom header to client
Now in the client side you check the header in ajax call.
The success function is like;
success: function(data, textStatus, request){
if(request.getResponseHeader('app-stat')=='loggedout')
{
//do what ever you want
}
else{
//enjoy
}
},
Ok, and for your already added 500 ajax solution is;
$(document).ajaxSuccess(function() {
//I think now you know what to do
});
In your controller
class Controller_name extends CI_Controller {
public function __construct ()
{
parent::__construct();
$user_id = $this->session->userdata('user_id'); // Session id of user
if(!$user_id || $user_id == '')
{
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{ // Checking if ajax request received or not
echo json_encode(array('status' => FALSE,'msg' => 'You are not logged in'));
die;
}
}
}
}
And in your ajax request
$.ajax({
url: "<?= base_url("controller/method") ?>",
data: {key1: value1,key2: value2},
type: "POST",
dataType: "json"
success: function(resp){
if(resp.status == false)
{
alert(resp.msg);
}
}
});
Note : Here I'm using dataType:'json in ajax request

Redirect user before success callback is received

Here's my code:
$.ajax( {
type: "POST",
url: "/script.php",
data: { "action" : "importData" },
cache: false,
async: true,
success: function() {
window.location.href = "/next-page";
}
} );
When a user lands on this page, ajax will trigger the php script which takes about 15 seconds to complete. Rather than having the user wait for the script to complete and then redirect them, I want to get some type of confirmation that the script has been triggered, then redirect the user without waiting for the entire script to complete. The results of the script isnt used until many minutes later in the workflow.
Is this possible? How to do so?
$.ajax() returns the XMLHttpRequest instance:
var xhr = $.ajax({
type: 'POST',
url: '/script.php',
data: {action: 'importData'},
cache: false,
success: function(){
location = '/next-page';
}
});
/* to test if problem is jQuery remove this line and take comments out
var px = xhr.onreadystatechange;
*/
xhr.onreadystatechange = function(){
//if(px)px();
if(xhr.readyState === 3 && xhr.status === 200){ // look at Properties -> https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
// do stuff here with xhr.readyState less than 4
}
}
Valid XMLHttpRequest.readyState property values can be found here.
Note that if you redirect the user, JavaScript on the current page stops. The page that your user is redirected to may have it's own JavaScript.

Http Post not sending data to another page in angular js

I am working on login form in Angular Js.The HTML and validation part is working fine.
The problem is when i send data using HTTP POST method to my servicecall PHP page and want to save it to DB.
I have tried all the way by setting this in JS
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I have tried by setting enctype of form to
enctype="application/x-www-form-urlencoded"
as well.But none of them is working i am not able to get data via $_REQUEST, $_POST, $_GET any of these method.
I have also tried using PHP library function.
$postdata = file_get_contents("php://input");
But it gives some weird string which i can't handle because number of POST data could be hundreds.
So this there any other way to solve the problem.
Code for http request is
var req = {
method: 'POST',
url: 'servicecall.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.loginData.username,
password: $scope.loginData.password,
action : 'checkLogin'
} //First way of sending data
//Second way of sending data which is also not working
//data: "{username:"+$scope.loginData.username+",password:"+$scope.loginData.password+",action:checkLogin}"
}
$http(req).then(function(response){
console.log(response);
}, function(response){
alert("Error "+response);
});
At PHP page i do
print_r($_REQUEST);
print_r($_POST);
But it prints just blank array like array{}
Following the code that I am using for same purpose. Hope that may help you.
var app = angular.module('angularApp', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == "1"){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});

HTTP 422 Error with JSON & jQuery + Human API

I am using the Human API found here: https://docs.humanapi.co/docs/connect-backend
At one point in connecting to the API, I need to send data back to them as JSON. I get a JSON object called sessionTokenObject which contains this:
{
humanId: "1234567890",
clientId: "abcdefg",
sessionToken: "9876zyx",
}
To which I'm supposed to add a clientSecret. Essentially, I'm taking what's in the JSON object, converting it individual variables, passing them through to another page via URL parameters and then reconstructing everything so that I can add the clientSecret like so:
$pop_clientid = $_GET['clientid'];
$pop_humanid = $_GET['humanid'];
$pop_userid = $_GET['userid'];
$pop_sessiontoken = $_GET['clientid'];
$my_sessiontokenobject = '{
humanId: "'.$pop_humanid.'",
clientId: "'.$pop_clientid.'",
sessionToken: "'.$pop_sessiontoken.'",
clientSecret: "thesecretgoeshere"
}'; ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
type: "POST",
url: 'https://user.humanapi.co/v1/connect/tokens',
data: '<?php echo $my_sessiontokenobject; ?>',
success: null,
dataType: 'application/json'
});
});
</script>
If I don't wrap the data value in the .ajax() call in apostrophes, I get a 422 error back from https://user.humanapi.com/v1/connect/tokens
If I do, I get an "Uncaught SyntaxError: Unexpected token ILLEGAL" error.
Can anyone see what's wrong with my code, or perhaps even tell me if trying to recreate a JSON object and then pass it back via .ajax() in the manner I am is just completely incorrect?
Try with this: (Returns a 404 Not found error, but it seems that it is in their side)
connectBtn.addEventListener('click', function(e) {
var opts = {
// grab this from the app settings page
clientId: clientId,
// can be email or any other internal id of the user in your system
clientUserId: clientUserId,
clientSecret: clientSecret,
finish: function(err, sessionTokenObject) {
console.log(sessionTokenObject);
// When user finishes health data connection to your app
// `finish` function will be called.
// `sessionTokenObject` object will have several fields in it.
// You need to pass this `sessionTokenObject` object to your server
// add `CLIENT_SECRET` to it and send `POST` request to the `https://user.humanapi.co/v1/connect/tokens` endpoint.
// In return you will get `accessToken` for that user that can be used to query Human API.
sessionTokenObject.clientSecret = clientSecret;
jQuery(document).ready(function($) {
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
contentType: "application/json",
data: sessionTokenObject,
});
});
// clientId=ceb8b5d029de3977e85faf264156a4e1aacb5377&humanId=f54fa4c56ca2538b480f90ed7b2c6d22
// $.post(url, sessionTokenObject, function(res){
// console.log(res);
// });
},
close: function() {
// do something here when user just closed popup
// `close` callback function is optional
}
}
HumanConnect.open(opts);
});
Human API Code for Testing, this code generates accessToken from Human API Developer Side but its not coming as in response while i execute this code
<script src='https://connect.humanapi.co/connect.js'></script>
<script>
var options = {
clientUserId: encodeURIComponent('email'), //Unique ID of user on your system (we send this back at the end)
clientId: '',
publicToken: '',
finish: function (err, sessionTokenObject) {
/* Called after user finishes connecting their health data */
//POST sessionTokenObject as-is to your server for step 2.
console.log(sessionTokenObject);
sessionTokenObject.clientSecret = 'Client Secret Key';
$.ajax({
type: 'POST',
url: 'https://user.humanapi.co/v1/connect/tokens',
method: 'POST',
data: sessionTokenObject
})
.done(function (data) {
console.log(data);
// show the response
if (data.success) {
alert(data.success);
} else {
alert(data.error);
}
})
.fail(function (data) {
console.log(data);
// just in case posting your form failed
alert("Posting failed.");
});
// Include code here to refresh the page.
},
close: function () {
/* (optional) Called when a user closes the popup
without connecting any data sources */
alert('user clicked on close Button');
},
error: function (err) {
/* (optional) Called if an error occurs when loading
the popup. */
}
}
function openHumanApiModel() {
HumanConnect.open(options);
}
</script>

Categories