CodeIgniter POST variables - codeigniter

Anyone know why:
class Booking extends Controller {
function booking()
{
parent::Controller();
}
function send_instant_to_paypal()
{
print_r($_POST);
echo '<hr />';
print_r($this->input->post());
echo '<hr />';
$id_booking = $this->input->post('id_booking');
$title = $this->input->post('basket_description');
$cost = ($this->input->post('fee_per_min') * $this->input->post('amount'));
echo $id_booking;
echo $title
echo $cost
}
}
Will echo post variables in CI for $_POST
but NOT for $this->input->post();?
I've got
$this->input->post() in use and working on a search page elsewhere in the site... but on this page, it's not working..
here's my form...
<form id="add_funds" action="' . site_url('booking/send_instant_to_paypal') . '" method="post">
<input type="text" name="amount" id="amount" value="" />
<input type="hidden" name="id_booking" id="id_booking" value="0" />
<input type="hidden" name="basket_description" id="basket_description" value="Adding Credit" />
<input type="hidden" name="fee_per_min" id="fee_per_min" value="' . $fee_per_min . '" />
<input type="submit" value="Add to basket" />
</form>
It's mental ;-p
Anyone spot anything obviously stupid I'm missing?

You most likely have XSS or CSRF enabled and it will prohibit (guessing here) Paypal to get those details back to you.
This is typical of CodeIgniter, and there are some work arounds like excluding CSRF for certain controllers (via config or hook).
If you give some more details on where the POST is coming from I can answer a bit clearly.
edit
could be that you are calling $this->input->post() incorrectly? I know that CI2.1 added support for $this->input->post() to return the full array, but until this point you had to explicitly define the post variable you wanted ala:
$user = $this->input->post('username');

I resolved the issue with excluding CSRF protection for that particular method
you can add this code in application/config/config.php
if(stripos($_SERVER["REQUEST_URI"],'/Booking/send_instant_to_paypal') === FALSE)
{
$config['csrf_protection'] = TRUE;
}
else
{
$config['csrf_protection'] = FALSE;
}

The only thing I can think of right now is that you maybe did not load the form helper, but I'm not sure if it's being used for that.
you can do this in the /config/autoload.php
I for example have this:
$autoload['helper'] = array('url', 'form', 'html', 'site_helper', 'upload_helper');
you can also load it in your function itself as follow:
function send_instant_to_paypal()
{
$this->load->helper('form');
print_r($_POST);
echo '<hr />';
print_r($this->input->post());
echo '<hr />';
$id_booking = $this->input->post('id_booking');
$title = $this->input->post('basket_description');
$cost = ($this->input->post('fee_per_min') * $this->input->post('amount'));
echo $id_booking;
echo $title
echo $cost
}

Related

Input type submit won't trigger when it's clicked

I have trouble with my code, I want to create an upload button to upload my .xlsx file, but it won't trigger even when I try to click it.
My view.php :
<form action="<?php echo base_url("index.php/fin/cost_control/workingcanvas/import"); ?>" method="post" id="import_form" enctype="multipart/form-data">
<p><label>Pilih File Excel</label>
<input type="file" name="file" id="file" required accept=".xls, .xlsx" /></p>
<br />
<input type="submit" id="import" name="import" value="Import" class="btn btn-info" />
</form>
My controller:
public function import(){
include APPPATH.'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader->load('excel/'.$this->filename.'.xlsx');
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true ,true);
$numrow = 1;
foreach($sheet as $row){
if($numrow > 1){
array_push($data, array(
'nis'=>$row['A'],
'nama'=>$row['B'],
'jenis_kelamin'=>$row['C'],
'alamat'=>$row['D'],
));
}
$numrow++;
}
$this->SiswaModel->insert_multiple($data);
redirect("Siswa");
}
and my model:
public function insert_multiple($data){
$this->db->insert_batch('siswa', $data);
}
I've tried with adding some part on autoload such as
$autoload['helper'] = array('url','form','file');
Any suggestions or advice? Thanks.
first load form helper in autoload file of codeigniter or load manually
$autoload['helper'] = array('url'); // autoload
$this->load->helper->('form'); // manually loading form helper
you better use this
$attributes = array('enctype' => 'multipart/form-data');
echo form_open('index.php/fin/cost_control/workingcanvas/import', $attributes);
<your upload form code>
<?php echo form_close(); ?>
instead of tags
more info: https://codeigniter.com/user_guide/helpers/form_helper.html

Run PHP function without reloading doesnt work with AJAX

I know this question has been asked a lot, but I can't solve my problem.
I want to run the PHP function without reloading the page. Why does this not work? The php file is indexTest.php.
The page is just scrolling to the top and nothing works.
I am new to AJAX so I really dont know what to do.
HTML:
<script type="text/javascript">
function submitdata()
{
var nameForm=document.getElementById( "nameForm" );
var emailForm=document.getElementById( "emailForm" );
var messageForm=document.getElementById( "messageForm" );
$.ajax({
type: 'post',
url: 'indexTest.php',
data: {
name:nameForm,
email:emailForm,
message:messageForm
},
});
return false;
}
</script>
<form onsubmit="return submitdata()" method="POST" id="contactForm">
<input spellcheck="false" class="first" type="text" name="name" placeholder="name" id="nameForm">
<input spellcheck="false" class="first" type="text" name="email" placeholder="email" id="emailForm">
<textarea rows="8" spellcheck="false" class="last" type="text" name="message" placeholder="message" id="messageForm"></textarea>
<input type="submit" name="submit" value="" id="button">
</form>
PHP:
<?php
if(isset($_POST['submit'])){
$to = "*"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
};
$first_name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = "Email from: " . $from . "\n\n" . $first_name . " wrote the following:" . "\n\n" . $_POST['message'];
$message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
The problem is that you are posting through the form itself, when you actually want to post through AJAX. Essentially, because you are calling your JavaScript function in onsubmit, the JavaScript will get run in addition to the default form submission.
What you need to do is disable default form submission with e.preventDefault();, and then run your JavaScript instead:
$("#contactForm").submit(function(e) {
e.preventDefault();
submitdata();
});
Hope this helps! :)

Codeigniter Radio button form validation?

I want to validate three radio button inputs using codeigniter form validation rule:
HTML Page
<form action="<?php echo base_url('register')" ?> method="POST">
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
i know what to do here
}
else
{
i know what to do here
}
}
How to do form validation in codeigniter for radio button in my case ?
Load library for form validation and other helpers in application/config/autoload.php
$autoload['libraries'] = array('form_validation');
$autoload['helper'] = array('form', 'url');
In your controller
public function register()
{
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "success";
}
else
{
$this->load->view('welcome_message');
}
}
In your view file use below code for printing validation errors
<?php echo validation_errors(); ?>
To show form error use form_error() function and to show all error use <?php echo validation_errors(); ?>
HTML PAGE
<form action="<?php echo base_url('register'); ?>" method="POST">
<?php echo form_error('cars'); ?>
<input type="radio" name="cars" value="BMW">
<input type="radio" name="cars" value="Ferrari">
<input type="radio" name="cars" value="Jaguar">
<input type="submit" name="submitter">
</form>
Controller
public function register(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('cars', 'Cars', 'required');
if($this->form_validation->run() == TRUE)
{
echo "i know what to do here"; //die;
}
else
{
echo "i know what to do here"; //die;
}
$this->load->view('welcome_message'); // your html view page
}
I think you are looking for in_list validation as an addition to required that has been mentioned by the others.
$this->form_validation->set_rules('cars', 'Cars', 'required|in_list[BMW,Ferrari,Jaguar]');
Also, as a self-reminder, since it took me 1 year to know about this.

submit multiple inputs within a forloop in codeigniter

My code is to fetch questions of users saved in the database by a foreach loop and let the admin answer each question and save the answer of each question after checking of validation rules in the database , Here we go :
Model is :
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result();
}
My view is:
foreach ($questions as $id => $row) :
?>
<?php
echo "<h5>".$row->question;
echo "<br>";
echo "from : ".$row->user_name."</h5>";
echo date('Y-m-d H:i');
echo "<br>";
$q_no='save'.$row->id;
$ans_no='answer'.$row->id;
echo "<h4> Answer:</h4>";
echo form_open('control_panel');
?>
<textarea name='<?php echo 'answer'.$row->id; ?>' value="set_value('<?php echo 'answer'.$row->id; ?>')" class='form-control' rows='3'> </textarea>
<input type='hidden' name='<?php echo $q_no ; ?>' value='<?php echo $q_no; ?>' />
<input type='hidden' name='<?php echo $ans_no ; ?>' value='<?php echo $ans_no ; ?>' />
<?php
echo form_error($ans_no);
echo "
<div class='form-group'>
<div >
<label class='checkbox-inline'>
<input type='checkbox' name='add_faq' value='yes' />
Adding to FAQ page .
</label>
</div>
</div>
<p>";
?>
<input type='submit' name='<?php echo 'save'.$row->id; ?>' value='<?php echo 'save'.$row->id; ?>' class='btn btn-success btn-md'/>
<?php
echo 'answer'.$row->id;
?>
<hr>
<?php endforeach; ?>
and my controller is :
$this->load->model('control_panel');
$data['questions']=$this->control_panel->get_questions();
$data['no_of_questions']=count($data['questions']);
if($this->input->post($q_no))
{
$this->form_validation->set_rules($ans_no,'Answer','required|xss_clean');
if($this->form_validation->run())
{
/* code to insert answer in database */
}
}
of course it did not work with me :
i get errors :
Severity: Notice
Message: Undefined variable: q_no
i do not know how to fix it
I am using codeigniter as i said in the headline.
In your controller on your post() you have a variable called q_no you need to set variable that's why not picking it up.
I do not think name="" in input can have php code I think it has to be text only.
Also would be best to add for each in controller and the call it into view.
Please make sure on controller you do some thing like
$q_no = $this->input->post('q_no');
$ans_no = $this->input->post('ans_no');
Below is how I most likely would do lay out
For each Example On Controller
$this->load->model('control_panel');
$data['no_of_questions'] = $this->db->count_all('my_table');
$data['questions'] = array();
$results = $this->control_panel->get_questions();
foreach ($results as $result) {
$data['questions'][] = array(
'question_id' => $result['question_id'],
'q_no' => $result['q_no'],
'ans_no' => $result['ans_no']
);
}
//Then validation
$this->load->library('form_validation');
$this->form_validation->set_rules('q_no', '', 'required');
$this->form_validation->set_rules('ans_no', '', 'required');
if ($this->input->post('q_no')) { // Would Not Do It This Way
if ($this->form_validation->run() == TRUE) {
// Run Database Insert / Update
// Redirect or load same view
} else {
// Run False
$this->load->view('your view', $data);
}
}
Example On View
<?php foreach ($questions as $question) {?>
<input type="text" name="id" value="<?php echo $question['question_id'];?>"/>
<input type="text" name="q_no" value"<?php echo $question['q_no'];?>"/>
<input type="text"name="a_no" value="<?php echo $question['a_no'];?>"/>
<?php }?>
Model
public function get_questions(){
$this->db->select('id,user_name, question, date');
$this->db->order_by("id", "desc");
$query=$this->db->get('t_questions');
return $query->result_array();
}

CodeIgniter add URI Segments

I have created a login form with CodeIgniter. To test the form, I submit incorrect data, I get the correct information back and the form is redisplayed. If I correct the errors and resubmit the uri segment is appended to the URL.
So I call the app with localhost/myapp, the login form is displayed. On submission the url change to localhost/myapp/controller/authenticate. When submitting again the URL change to localhost/myapp/controller/authenticate/controller/authenticate
What is the problem here?
View
<form action="<?php echo base_url();?>/welcome/authenticate" method="post" id="loginfrm">
<input type="text" name="username" /><?php echo form_error('username', '<div class="error">', '</div>'); ?><br />
<input type="password" name="password" /><?php echo form_error('password', '<div class="error">', '</div>'); ?><br />
<input type="submit" value="Login" />
</form>
controller
public function index()
{
$this->load->view('welcome_message');
}
public function authenticate()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_message');
}
else
{
echo $this->input->post('username') . " -->> " . $this->input->post('password');
}
}
}
Always use redirect in function where forms are processed this prevents the form re-submission in your case if everything works fine and your view is loaded when user tries to refresh the page he will be asked to resubmit the form. Redirect function changes the url in browser address bar so user will no longer be asked for form re-submission.

Resources