Couldnt get CSRF to work with ajax (CI 2.1) - codeigniter-2

i am trying to get CSRF work with ajax in my CI 2.1 application.
i have searched about this and found few guidlines, but couln't resolve the problem
http://ericlbarnes.com/post/10728867961/codeigniter-csrf-protection-with-ajax
http://www.beheist.com/index.php/en/blog/csrf-protection-in-codeigniter-2-0-a-closer-look
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
i have set two different tokens for two token values in the config
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'token01';
$config['csrf_cookie_name'] = 'token02';
$config['csrf_expire'] = 7200;
Here is my view, i am using form_open
<?php echo form_open("http://localhost/pis/user"); ?>
<div id="inputs">
<?php echo form_input($username);?>
<?php echo form_password($password);?>
</div>
<div id="actions">
<div style="float:left"><?php echo form_submit($submit);?>
<!-- <input type="button" value="Login" id="submit" name="submit" onclick="clicksubmit()" /> -->
</div>
</div>
<?php echo form_close();?>
I am using this javascript to make async call
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(
function(){
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
csrf_token_name: $("input[name=token01]").val()
};
$.ajax({
type: "POST",
url: "http://localhost/pis/user",
data: form_data,
success:
function(data){
$("#debug").html(data.message).css({'background-color' : data.bg_color}).fadeIn('slow');
}
});
return false;
});
});
</script>
When i run this i am getting a "500 Internal Server Error" along with the "An Error Was Encountered, The action you have requested is not allowed" as a response. Firebug shows the POST data parameters correctly.
eg: username=root&password=root&csrf_token_name=31961f17de5fa2df657ab1aba880f718
How ever if i removed the csrf, ajax request runs fine and i get 200 as response
Can anyone help me please?

Even better, you can just let jQuery serialize the form data for you:
var form_data = $(this).serialize();
This way you won't have to worry about inputs being renamed or more fields being added.

Related

Posting form using AJAX

can anyone please help me with sending the below form using Ajax. All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. I have tried so many methods but have not been able to do this. Bill Gates or Steve Wozniak if you guys are reading this, please help
This gives me a console $.Ajax is not a function in the console
<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
}
});
});
</script>
<?php
echo "
<div class='col-sm-3 mt-5'>
<form class='ajax' method='post' action='trolley1.php?action=add&id=$id'>
<div class='products'>
<a>$img</a>
<input type='hidden' name='id' value='$id'/>
<input type='hidden' name='name' value='$product'/>
<input type='hidden' name='price' value='$price'/>
<input type='text' name='quantity' class='form-control' value='1'/>
<input type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
value='Add to Cart'/>
</div>
</form>
You have one syntax error in your JS Code - see correct code
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url: "trolley1.php",
type: "POST",
dataType:"json",
data: form_data
}).done(function(data){
alert("Item added to Cart!");
});
});
});
And you are using jQuery as additional javascript libary. jQuery uses $ to access the methods (e.g. $.ajax) Thats the reason why you get undefined as error.
So you need to load the libary first at the beginning of your page (inside <head>). E.g. directly from their CDN
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then it should work for you

Using ajax to pass text to a db

I am trying to take simple text from a form, pass it to my controller via ajax, and have that send to the data base.
View
<form method="POST">
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="rate" type="submit">
</form>
<script type = "text/javascript">
$(function(){
$("#rate").click(function(){
dataString = $("#email").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/trial/insert_into_db",
data: dataString,
});
});
});
</script>
The controller code and the model code work fine. I am almost sure that it is the ajax code that is not working.
Any information would be greatly appreciated!
Thank you.
One thing missing from your posted code is disabling the default form submission. There still could be other issues.
You don't specify an action so by default the action is the same url as the page.
<form method="POST">
You are doing AJAX but you have not disabled the default behavior with return false or event.preventDefault
$("form").submit(function(event) {
event.preventDefault();
// or
return false;
});
I prefer preventDefault() but the point is you need to prevent the default browser behavior.
Edit: This is how I would submit the form with AJAX.
If you had more than one form button to consider then
$("form").submit(function(e) {
e.preventDefault();
});
$("#rate").click(function(e) {
$.ajax({ ... });
});
But it's (marginally) easier to do it with one handler. I'd also stick the action on the form so the form still submits to the correct url if the javascript failed.
<form id="myform" action="<?php echo base_url();?>index.php/trial/insert_into_db" method="post">
Instead of handling the button click handle the form submission
$("#myform").on("submit", function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type = "post",
url = $(this).attr("action"),
data = formData
})
.done(function(result) {
// do something with the response
});
});

Cross Domain Ajax Issue

I have two files
1) index.php(picks data from the code editor and submits for processing via Jquery Ajax to exec.php)
2) exec.php (currently just transfer the data it recieved via index.php using jsonp)
Code of index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function test() {
var code = document.getElementById('code').value;
var code_data = "code=" + code;
alert(code_data);
$.ajax({
type: "POST",
crossDomain: true,
url: "http://code1.guru99.com/exec.php",
data: code_data,
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
alert("End of Test");
}
</script>
<form name="myform" id="myform" method="POST" class="code-box">
<textarea name="code" id="code"><?
$code='<?php
"Hello";
?>';
echo $code;
?>
</textarea> <!-- for add html tag in text area nad print the code-->
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" id="submit" onClick="test();"><!--<img id="ajax-loader" name="ajax-loader" src="/img/ajax-loader.gif" class="hidden" style="vertical-align:middle" />-->
</form>
<div name="label" id="label"> </div>
<div name="out" id="out"> </div>
Code of exec.php
<?php
$code=$_POST['code'];
$fp=fopen("file.txt","w"); // Storing the data into a file just to know that data is passed
fwrite($fp,$code);
fclose($fp);
header('Content-Type: application/jsonp');
echo $_GET['callback']."(".json_encode($code).");"
?>
The problem is data just does not pass into exec.php. I am not sure why...
The code is live at http://code.guru99.com/php/
Please help...
You cannot use AJAX to do this. Instead consider posting from a hidden Iframe using a regular FORM and setting the action to the URL you desire. You can still submit the form using JavaScript.
You can also listen to the onload event on the iframe to detect when your post has completed.
Alternately, you can use a server-side proxy.
The code syntax is correct.
May the problem could be with your server

Load PHP array into html as select options

I am having trouble working the finishing touches out with this. I am still fairly new to ajax and json, but here's what i have so far. I am trying to take an array(s) from a php file and load them into a select dropdown (#input) via ajax/json. I think i'm pretty close, but i'm not sure where i'm messing up. Please help
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="../_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function() {
if ($("#numbers").val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = <?php echo json_encode($array); ?>;
for (i=0;i<numbers.length;i++){
$('#input').append("<select>" + numbers[i] +
"</select>");
}
},
});
}
});
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
</div>
<div id="content">
<div class="main">
<div id="formwrapper">
<select id="numbers">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="input"></select>
</div>
</div>
</div>
</div>
</body>
</html>
And here is my PHP (login.php)
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>
In your script, you aren't doing anything with the data that is returned from the AJAX call. I suspect that is because you don't understand how AJAX works. I'll try to explain it without going into super deep detail.
When you make an AJAX call to a URL, you are making an HTTP request, just like when you type http://www.google.com into your web browser. In response, the server at the other end of that URL sends you an HTTP response with some data.
In the case of your AJAX, you are requesting the response of login.php, which, I will assume, is the PHP you added to your question above. In the success function, you get a result. That result is everything that was output by login.php.
So,
$(document).ready(function() {
$("#numbers").change(function(e) {
if ($(this).val() == "2") {
$.ajax({
type: 'POST',
url: 'login.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
var numbers = result; //result is equal to your array from the php. You don't put PHP here.
$('#input option').remove(); //Remove any existing options.
for (i=0;i<numbers.length;i++){
$('#input').append("<option>" + numbers[i] + "</option>");
}
}
});
}
});
});
If login.php is NOT the PHP you added above, then I'm not going to be able to help you until you tell me what file that is from.
Also, notice that we wrapped the AJAX call into a change event on the #numbers select box. That way, when the select box's value changes, it will call this AJAX, and select the numbers.
Thanks for the assist tymeJV.

Beginner in AJAX help needed with POST

I have the following script:
<script>
/* attach a submit handler to the form */
$("#Submitter<? echo $count; ?>").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/*clear result div*/
$("#result").html('');
/* get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "<? echo Configure::read('Burl') . $cat['sub_cat_url']; ?>",
type: "post",
data: values,
success: function(){
$("#prod_add").show();
$("#prod_add").delay(2500).animate({opacity: 0},5000);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
});
</script>
which works, the form is posted. But how do I get access to the post variables on the same page without refreshing? Are they stored in an JavaScript array or something?
this is my form:
<form method="post" id="Submitter<? echo $count; ?>">
<input type="hidden" name="CartAdd" value="1">
<input type="hidden" name="Productcode" value="<? echo $row['Titel']; ?>">
<input type="hidden" name="Description" value="<? echo $row['Omschrijving']; ?>">
<input type="hidden" name="Tumbnail" value="<? echo $row['Afbeelding']; ?>">
<input type="SUBMIT" value="Order Now" class="order_button">
I still don't understand whats the question is, but i will give it a try:
But how do I get access to the post variables on the same page without refreshing?
There is no concept like POST variables client side so i guess you mean the value of the form fields you post to the server?
Just access them by id/name:
var valueOfTumbnail = $('input[name="Tumbnail"]).val();
If you want to access the whole data which gets posted use form.serialize() like in your method:
var serializedData = $("form").serialize();
But i don't think that this is what you want.
EDIT:
Try to execute the code when the document was loaded and processed by the browser:
$(document).ready(function() {
// here your code...
});

Resources