403 forbidden in Codeigniter Ajax request even with cookie transfer - php

I am submiting a form with Ajax, I am also sending the cookie, however I still get the 403 forbidden. These are the 2 ways I tried sending the cookie.
Directly setting csrf cookie name and value in Ajax.
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = $('#title').val();
var message = $('#message').val();
console.log(google_name);
var csrf_test_name = $("input[name=csrf_test_name]").val();
console.log(csrf_test_name);
console.log(title);
console.log(message);
$.ajax({
type: "POST",
url: 'http://localhost/hbp/review/submit',
data: {
title,
message,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
Getting the CSRF cookie from the form field
<form id="reviewForm" method="POST">
<div class="control-group">
<div class="controls">
<input type="text" class="form-control"
placeholder="Title" id="title" required
data-validation-required-message="Please enter the review title"/>
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<textarea rows="10" cols="100" class="form-control"
placeholder="Message" id="message" required
data-validation-required-message="Please enter your message" minlength="5"
data-validation-minlength-message="Min 5 characters"
maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div> <!-- For success/fail messages -->
<br>
<div class="g-signin2 btn btn-default pull-right" data-onsuccess="onSignIn"></div>
<br/>
</form>
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = $('#title').val();
var message = $('#message').val();
console.log(google_name);
var csrf_test_name = $("input[name=csrf_test_name]").val();
console.log(csrf_test_name);
console.log(title);
console.log(message);
$.ajax({
type: "POST",
url: 'http://localhost/hbp/review/submit',
data: {
title,
message,
'csrf_test_name ' : 'csrf_test_name ',
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
None of them seem to work, here's the controller if it helps.
public function review($google_name, $google_email, $google_image, $message, $title)
{
$this->load->library('session');
$csrf_token = $this->security->get_csrf_hash();
$data = array(
'csrf_token' => $csrf_token
);
if (!$google_name and $google_email and $google_image and $message and $title) {
$this->load->library('session');
redirect('/', $this->session->set_flashdata('review_form_error', 'Error! All yields are required!')
);
} else {
echo $google_name, $google_email, $google_image, $message, $title;
$this->review_model->set_review($google_name, $google_email, $google_image, $message, $title);
redirect(base_url(), $this->session->set_flashdata('review_success', 'Thank you for providing us with your helpful feedback'));
}
}

try ajax setup
$.ajaxSetup({
data: {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
});

How to troubleshoot CSRF token issues?
open developer console in browser
go to network tab
click on the request being made
go to Cookies tab - compare request and response cookies
You can also var_dump($_POST) on the server side.
Question-specific remarks:
'csrf_test_name ' : 'csrf_test_name ',
should this not be
'csrf_test_name ' : csrf_test_name,
Try with double quotes:
'<?php echo $this->security->get_csrf_token_name(); ?>' : "<?php echo $this->security->get_csrf_hash(); ?>",
EXTRA: how to pass CI variables to JavaScript in a clean way, avoiding PHP/JS clutter?
Create a view file and include it in the bottom of your template:
file name = views/public/ci_config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
?>
<script type="text/javascript">
var CONFIG = {
'base_url': '<?php echo base_url(); ?>',
'csrf_expire': '<?php echo $this->config->item('csrf_expire'); ?>',
'csrf_token_name': "<?php echo $this->security->get_csrf_token_name(); ?>", // needs double quotes!
'csrf_hash': "<?php echo $this->security->get_csrf_hash(); ?>" // needs double quotes!
};
</script>
Load it in a parent template, for example the footer partial, with:
<?php $this->load->view('public/ci_config'); ?>
Easily access this data anywhere in JS files:
var csrf_token_name = CONFIG.csrf_token_name;
var csrf_hash = CONFIG.csrf_hash ;
Or like Aria said:
$.ajaxSetup({
data: {
CONFIG.csrf_token_name : CONFIG.csrf_hash
}
});
Now you don't have to put all your JS code in a PHP file.

Related

Post and display data on the same page using PHP (MVC) AJAX

I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

send csrf_token with a ajax request

I need help to send the token with ajax request. He always say: "invalid".
What Mistake do I make?
world.php:
<form name="theform" id="suchform" method="POST">
<p><input type="text" class="find_person search_btn" placeholder="Person Suchen" tabindex="1"></p>
<p><input type="hidden" class="csrf_token" value="<?= echo $_SESSION['csrf_token']; ?>"></p>
</form>
<div id="output">
</div>
<script>
$('#suchform').on('input', function(event) {
event.preventDefault();
var name = $('#suchform').find('.find_person').val();
var token = $('#suchform').find('.csrf_token').val();
$.ajax({
type: 'POST',
url: 'show_user.php',
data: {find_person:name, csrf_token:token},
success: function(data) {
$('#output').html(data);
}
})
})
</script>
show_user.php
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
echo $_POST['csrf_token'] . '<br>' . $_SESSION['csrf_token']. '<BR>';
exit("invalid");
}
connect.php
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));

jquery/php form in modal window

I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.

Php Js Ajax I need some assistance

I am trying to create a social dating site and I have my problem in the Add as Buddy Button. When you click it, my site should be sending the uid of the sender (from_uid) and the uid of the receiver (to_uid) to the database. It sends out the from_uid successfully but the to_uid always sends 0.
PHP
<div class="member" data-user="<?php echo $member['xmpp_user']; ?>" data-uid="<?php echo $member['uid']; ?>">
<input type="hidden" id="hiddenuid" value="<?php echo $member['uid']; ?>">
<img src="https://s3.amazonaws.com/wheewhew/user/<?php echo $member['uid']; ?>/photos/<?php echo $member['profile_pic']; ?>" />
<div class="member_name"><?php echo $member['firstname']." ".$member['lastname']; ?></div>
<div id="addbutton"><button type="submit" class="add"> Add as Buddy </button></div>
</div>
Javascript
<script type="text/javascript">
var BOSH_SERVICE = 'http://wheewhew.com:5280/http-bind';
var connection = null;
var xmpp_user = "<?php echo $xmpp_user; ?>#wheewhew.com/default";
var xmpp_pass = "<?php echo $xmpp_password; ?>";
var uid = "<?php echo $uid; ?>";
$(document).ready(function () {
$('#btn-logout').click(logout);
$('.add').click(addBuddy);
connectXMPP();
//updateLastSeen();
});
</script>
jabber.js
function addBuddy(){
var xmpp_user = $(this).parent().attr('data-user')+'#wheewhew.com/default';
var to_uid = $(this).parent().attr('data-uid');
$.ajax({
type: "POST",
url: "./ajax/addBuddy",
data: "from_uid="+uid+"&to_uid="+to_uid,
success: function(data) {
var ret = eval('('+data+')');
if(ret.status == 'success'){
connection.send($pres({to:xmpp_user,type:'subscribe'}).tree());
}
}
});
}
Your addBuddy function doesnt have a reference for what $(this) is. Try this out:
$('.add').click(function(){
addBuddy($(this));
});
And then in your function:
function addBuddy($btn){
var xmpp_user = $btn.parent().attr('data-user')+'#wheewhew.com/default';
var to_uid = $btn.parent().attr('data-uid');
// ajaxy stuff
}
That should help. At the very least, we can continue the discussion here rather than in the comments for the OP.

Categories