How realize form success notify using CodeIgniter? - php

I have feedback non-ajax form whitch create on CodeIgniter 2. I wanna to show notify after form successful submit. How do this, correctly?

Basic example, this is over-simplified so it can be understood easily:
Controller
if ($this->form_validation->run()) // Your logic that tells if the submit was OK
{
$data['message'] = 'Thanks.';
}
else
{
$data['message'] = 'There was an error.';
}
$this->load->view('my_view', $data);
View
<?php echo $message; ?>

Related

How to prevent form submission on refreshing the page in Zend framework?

This is my action on my controller
public function invite()
{
if($this->getRequest()->isPost()){
$data_array = $this->getAllParams();
$emailList = explode(",", $data_array['emails']);
$message = $data_array['message'];
$error_emails = array();
if(sizeof($emailList) <= 1){
$this->view->message = '<div class="alert alert-danger"> Please enter more than one email address and please separate emails by a "," (comma)</div>';
}
else{
$x = 0;
foreach($emailList as $singleEmail){
if (!filter_var(trim($singleEmail), FILTER_VALIDATE_EMAIL)) {
$error_emails[] = $singleEmail;
}
else{
//send emails here
$x++;
}
}
if(sizeof($error_emails) > 0){
$email_str = implode(",",$error_emails);
if($x > 0 ){
$this->view->message = '<div class="alert alert-success"> Successfully Sent! </div> ';
}
$this->view->message .= '<br /><div class="alert alert-danger"> Message to this emails were not sent! <b>'.$email_str.'</b> <br /> Please enter valid emails!</div>';
}else{
$this->view->message = '<div class="alert alert-success"> Successfully Sent! </div>';
}
}
$request = $this->getRequest();
$request->setParam('emails', null);
$request->setParam('message', null);
}
}
I tried the solutions i found;
As you can see i tried setParam method to set values to null. Unfortunately, this doesn't work.
also unset array didn't work- not sure if i did it right.
Anyway, i don't want to redirect. Just want to unset. Can someone help me out? I've been trying this for few hours now. Thanks in advance.
This problem is not specific to Zend Framework, There is a pattern called PRG (short for Post Redirect Get) to deal with resubmissions of forms: https://en.wikipedia.org/wiki/Post/Redirect/Get
Zend Framework provides PRG controller plugin http://framework.zend.com/manual/current/en/modules/zend.mvc.plugins.html#post-redirect-get-plugin In short, it stores post data in session and issues redirect, then on subsequent get request it returns that stored post data.
Example code suggests that you handle form on GET request after PRG plugin did redirect:
// Pass in the route/url you want to redirect to after the POST
$prg = $this->prg('/user/register', true);
if ($prg instanceof \Zend\Http\PhpEnvironment\Response) {
// returned a response to redirect us
return $prg;
} elseif ($prg === false) {
// this wasn't a POST request, but there were no params in the flash messenger
// probably this is the first time the form was loaded
return array('form' => $form);
}
// $prg is an array containing the POST params from the previous request
$form->setData($prg);
if($form->isValid()) {
...
But I disagree with that approach and suggest to always handle form on POST and use PRG to show form with filled data and validation messages afterwards (note $form here is an instance of Zend\Form):
if($this->getRequest()->isPost()) {
$form->setData($this->getRequest()->fromPost());
if ($form->isValid()) {
//handle form
// if you don't need to show form again, redirect:
return $this->redirect()->toRoute('some/route');
}
}
// And now do PRG to re-display form with data and validation errors
$prg = $this->prg('/user/register', true);
if ($prg instanceof \Zend\Http\PhpEnvironment\Response) {
// returned a response to redirect us
return $prg;
} elseif ($prg === false) {
// this wasn't a POST request, but there were no params in the flash messenger
// probably this is the first time the form was loaded
return array('form' => $form);
}
// $prg is an array containing the POST params from the previous request
$form->setData($prg);
// make sure form have validation result to display
$form->isValid();
return array('form' => $form);
But since you are not using forms, you will need to validate data manually twice. Once to process and once to display error messages. If you do not want to use Zend\Form component, I would suggest to look at Zend\InputFilter to validate input.
You can use CSRF protection in zend ie use a token while submitting the form

Codeigniter View gives error

I am developing a web application with codeigniter. I have a main screen which loads three views as follows:
1)header 2)main screen 3)footer
the 'main_screen' view loads another view called 'login'
here is the code
<?php
if($logged == null){
$CI = &get_instance();
$CI->load->view('login');
}else{
echo $logged;
$CI = &get_instance();
$CI->load->view('login');
}
?>
the variable $logged is actually a data sent by a controller, when I first time loads the page it gives error 'Undefined, variable', but when i login it doesn't, here is the code.
if($loginSucessfull){
$data['logged'] ='<div class="success">Login Sucessfull</div>';
$this->load->view('header');
//here I am sending data to the 'menu_screen'
$this->load->view('menu_screen',$data);
$this->load->view('footer');
} else {
$data['logged'] = '<div class="alert">Sorry the username or password is incorrect</div>';
$this->load->view('header');
//here again I am sending the data
$this->load->view('menu_screen',$data);
$this->load->view('footer');
}
What I am trying to do is, if the user is sucessfully logged in show the sucessfull message else show the error and the login form as well. please help me how to fix this.
$logged isn't null. You get the error because the variable does not exist.
You have to set $logged to something before the main_screen page loads.
I don't know whether it works or not. Just try:
data = array();
$data['logged'] = 'something that you want to assign';

Codeigniter form validation: run function is not working

I am working with a from in codeigniter where program control is moving to submit function which I can test by adding the die function. Although set_rules() are successfully checking the entry but the control is not being passed to if($this->form_validation->run()) this function. Its getting out of it and running the die function dead-2 that I have kept to test the program flow.
Below is my controller code
function addPost(){
$this->load->library('form_validation')
if($this->admin_lib->checkMembers()){
if($this->input->post('submit')){
//validate the form
$this->form_validation->set_rules('country','Country','required');
$this->form_validation->set_rules('city','City','required');
$this->form_validation->set_rules('area','Area','required');
$this->form_validation->set_rules('street','Street','required');
$this->form_validation->set_rules('house_no','House number','required|numeric');
if($this->form_validation->run()){
//add to database
die("dead-1");
if($this->members_model->addPost())
{
echo "Successfully made one entry will be validated";
}
else{
echo "Error uploading the datas into database Please contact us about the problem";
}
}
die("Dead -2");
}
$data['content']=$this->load->view('members/addPost','',true);
$this->load->view('members/home',$data);
}
else{
echo "you dont have preveledge to access this page ,<br/> LOgin link rakhnu paryo ";
}
}
Your code will always call die("Dead -2") because it isn't part of an Else block. It's sitting directly below your If statement which means, regardless of what happens with your form validation, it will always die.
Consider changing your code to the following
if($this->form_validation->run())
{
//add to database
die("dead-1");
if($this->members_model->addPost())
{
echo "Successfully made one entry will be validated";
}
else
{
echo "Error uploading the datas into database Please contact us about the problem";
}
}
else
{
die("Dead -2");
}

email contact form - can reach success page manually even if form wasn't submitted - how to stop

Here's my setup for an email contact form:
www.example.com/includes/contact_form.php
www.example.com/includes/contact_submit.php
www.example.com/contact/
/contact/ includes contact_form.php, and the form points to contact_submit.php to run.
When contact_submit.php successfully sends the mail, it does a redirect back to /contact/ but includes a $_GET variable.
header('Location: /contact/index.php?success=yup');
Then in contact_form.php I have:
if (isset($_GET['success'])) { echo 'Your message has been received etc'; exit(); }
Everything works fine. I made it this way so that the form couldn't be F5/refresh resubmitted, and it is successful in that.
However, anyone can access the success page at any time by manually entering the url, even if they don't submit the form. Is there any way around that?
Ofcourse.
Use sessions for that:
class ResponseLog {
private function __construct(){}
public static function hasMessages(){
return (isset($_SESSION['response']['messages']) && !empty($_SESSION['response']['messages'])) ? true : false;
}
public static function setResponse(array $response){
$_SESSION['response'] = $response;
}
public static function getLastResponse(){
$response = isset($_SESSION['response'])) ? $_SESSION['response'] : null;
#unset($_SESSION['response']);
return $response;
}
}
And use it like this:
if(isset($_POST['form'])){
//validation and all to proccess request goes here
if(!$valid){
$response = array('request' => $_POST,'messages' => array('Incorrect email','Please enter forename'),'url' => '/my/form/where/it/happen/');
}
else {
$response = array('messages' => array('Success'),'url' => '/my/form/where/it/happen/');
}
ResponseLog::setResponse($response);
//redirect to contact form
}
In success page or fail:
if(ResponseLog::hasMessages()){
$response = ResponseLog::getLastResponse();
foreach($response['messages'] as $message){
echo $message;
}
}
With this you can store everything user does and can work with data as you need.
I hope this help :)
Warn: I wrote it from mind, so it's untested code and it can be implemented better it's just for view how to work with user session and responses.
PS: But is a lot of ways how to do it, for example see flash messages in some framework and you will be see how it works with sessions etc.
You can use the referrer page if you want, and throw an error or redirect if it is not the form page, but it is not so good. You can also check whether the fields and form name have been posted.
$_SERVER['HTTP_REFERER']

CodeIgniter Controller - pass variable to index()

still very new to CodeIgniter and trying to do the following. I may be doing this wrong, and any direction, greatly appreciated.
I have a function that is called on submit of login form, validate_creds. If successful the form logs in, if not successful I want to set an $error_msg and reload the form. The validate_creds() appears to validate correctly but as you can see on the else statement I want to reload the index() passing the $error_msg displaying the message at the top of the form.
public function index($error_msg = '')
{
//data
$data['login'] = "Logged In";
if($error_msg !== '') {
$data['error_msg'] = $error_msg;
}
//view
$this->load->view('templates/login/login_header',$data);
$this->load->view('login/login_form', $data);
$this->load->view('templates/login/login_footer',$data);
}
public function validate_creds()
{
$this->load->model('user_model');
$query = $this->user_model->validate();
if($query)//if the users creds have been validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('gallery');
}
else
{
$error_msg = "Your username or password is not correct.";
$this->index($error_msg);
}
}
Form Message
<?php if($error_msg != ''): ?>
<div class="alert alert-error">
<?php echo $error_msg; ?>
</div>
<?php endif; ?>
What currently is happening is the $error_msg is displaying all the time.
I hope this is just how it came out with copy pasting because this code is hard to read. check out php codesniffer and as an industry standard, check out some documentation on zend about php code format.
so your logic requires the error message be injected into the index function (which I'm assuming is your action but just not labeled as so), and if it's not injected, it doesn't declare the error message because it's not injected.
i would look at $this->user_model->validate(); to ensure that's properly handling the http request (post).

Categories