In the settings.php i have some input for the realname,hobby,city and select tag for the languages
The html form is easy and i'm not going to copy it :)
This is the php code for the form
<?php
if(isset($_POST['submit'])){
if($this->edit->process()){
$s = 1;
}
}
if($s){echo '<p id="success">Success</p>';}
?>
This is in the view file and when the form is submit the $this->edit = the model for the updating the user data.
Everything work really good but in head.php there is this code
<?php $lang = $this->lange('global',$this->getUser->language($_SESSION['userID']));?>
With him this get the user current language and after that load the file with lange()
So if the submit is like this,the inputs and select tag are changing with what the user have choicen but the to see the new language they have to refresh the page. This is not good,because the user may be confuced that they did something wrong.
But if the form with method="POST" the page is refreshing and still with the old language
It is going to be quite hard to change all the texts in the DOM model to make the language change without redirect. I doubt it's really your desire.
You ought to make a GET method redirect after processing any POST form. So, instead of printing whatever "success" messages you have to reload the page.
Using session to store the language is not good method, the language have to be set by means of the page address - a subdomain (preferable) or a virtual directory.
Related
I have a page in view that has two parts actually which are accessed through # tags, like login#signin and login#signup. When the page loads for the first time it shows login form without having #signin without a problem.
So signin is not causing a problem as it loads at folder/login. But when I try to put folder/login#signup to load directly signup part it gives an error that there is no view login#signup.php. How to cope with this situation?
$this->load->view('workers/login#signup'); is not working.
When I don't put #signup it loads login form that is weird.
I'll expand more on my initial comments for the cause of this error, and how to fix things.
The cause of the issue
As mentioned throughout the comments, you cannot a view using an anchor point. For example, this does not work:
view('workers/login#signup'); // The #signup should not be here.
The documentation states:
Loading a View
To load a particular view file you will use the following method:
$this->load->view('name');
Where name is the name of your view file.
The name is the file is "name", not "name#signup".
Further down,
The .php file extension does not need to be specified unless you use something other than .php.
This implies, that when you use view('name'), CodeIgniter will, by default, load the file name.php. If you include a #signup in it, then CodeIgniter will not be able to find name#signup.php because that file does not exist.
Correct way to handle things
You mentioned you're using the form validation, so we need to ensure no value is lost during the transition process.
Here's a simplified explanation for how to handle it:
function login() {
// Data to be passed to the view (you may or may not already have this)
// More info: https://codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
$data = array();
// Validation has failed...
$this->form_validation->run() == FALSE ) {
// Set variable to redirect to #signup upon page load
$data['redirect_to_signup'] = true;
}
// Load view with $data which contains values to be passed to the view
$this->load->view('workers/login', $data);
}
In your workers/login view file, we just need to check if the redirect_to_signup value exists. If it does exist, then we can use some simple JavaScript to scroll down the #signup form:
<?php if (isset($redirect_to_signup) && $redirect_to_signup === true): ?>
<script>
var top = document.getElementById('signup').offsetTop;
window.scrollTo(0, top);
</script>
<?php endif; ?>
Because your validation object is still valid, you can use the built-in CodeIgniter functions to preload your form elements with the set_value() helper functions. For example:
<input type="text" name="email" value="<?php echo set_value('email'); ?>">
That hopefully explains how to achieve what you're after:
Validate user submitted form; and
If there are errors, reload the form with validation messages; and
Scroll down to the #signup form on the page.
One alternative is using redirect('login#signup'), but I would not recommend this method. You would need to save your form values and validation errors to the session to show them on the next page. You also run into the issue that the user might click the refresh button and all values would be lost then.
I have a form at the bottom of a long page, if a user fills out the form but it doesn't validate the page is reloaded in the typical codeigniter fashion:
$this->load->view('template',$data);
however because the form is way down at the bottom of the page I need the page to load down there like you do with HTML anchors. Does anyone know how to do this in codeigniter?
I can't use the codeigniter
redirect();
function because it loses the object and the validation errors are gone. Other frameworks I've used like Yii you can call the redirect function like:
$this->redirect();
which solves the problem because you keep the object. I've tried using:
$this->index()
within the controller which works fine as a redirect but the validation errors are in another method which is where the current page is loaded from:
$this->item($labs)
but when I use this it get stuck in a loop
Any ideas? I've seen this question a lot on the net but no clear answers. I'm researching using codeigniter "flash data" but think it's a bit overkill.
cheers.
I can't personally vouch for this, but according to this thread if you append the anchor to the form's action, it will work.
CodeIgniter helper:
<?php echo form_open('controller/function#anchor'); ?>
Or vanilla HTML:
<form method='post' action='controller/function#anchor'>
If you were open to using Javascript, you could easily detect a $validation_failed variable and appropriately scroll. Or, even better, use AJAX.
Another option is to put the form near the top of the page?
Ok, as far as I understood your problem, it isn't much related to the back end(codeigniter). You want the form at the bottom of the page to be 'what-users-sees-on-page-load' (since you mention anchors).
Now, what you can do is, you can set delimiters for your validation error messages using:
echo validation_errors('<div id="bottom_form_error">', '</div>');
Using jQuery ScrollTo, do:
$( function() { $('#bottom_form_error').ScrollTo(); } );
And, the user will be scrolled to the errors at the bottom of the page. Don't forget to include jQuery too.
Anchor hash fragment click is different - it is scrolling at ∞ speed.
I hope that is what you wanted.
P.S. I am ignoring what you said below this line:
Does anyone know how to do this in codeigniter?
as I felt it is not really relevant to the question.
I want to execute a Action and stay on the same page.
I created the link to eh action like this:
<?php echo(link_to('Add to Watchlist', 'housing/addToWatchlist')) ?>
which executes this action with a redirect
echo('ADDING TO THA WATCHLIST');
$referrer = $request->getReferer();
return $this->redirect($referrer);
as suggested here: symfony link to change language and stay on the page
This solution works but unnecessary reloads the page, which may be necessary to change the language but not to add an item to a Watchlist.
Without reloading the page you need to use Javascript and an Ajax approach.
http://www.symfony-project.org/jobeet/1_4/Propel/en/18
Also check out link_to_remote.
im using a form in php to submit some information into my database
so i used two function to do this
but how to show the result in th same page that has the form
To load the same page you have to assign the variable $_SERVER[PHP_SELF] for the form action field.
<form action='$_SERVER[PHP_SELF]?op=ban' method='post'>
then when the page get load you just check the post variable ,if it contains the appropriate data then print the result with the form.(Normally people using div tag to print the results )
It's as easy as this:
if (isset($_POST['submit']))
{
// do something with your data
}
form();
Forgive me if I am wrong. I think you have copied the code from some where and using it without understanding how forms work.
<form action='index.php?op=ban' method='post'>
The above code says to which page the values should be submitted. As you can see above the values in the form will be submitted to index.php. So the DB operations will(should) happen in index.php and the Thank you message can be shown in index.php.
If you want to show your result in the same page then you will have to submit to the page in which the form resides. But in this case you should have a logic in the page to decide whether the form was submitted or was it loaded first time.
The code snippet in your question does not tell us name of the file the code exists so we wont be able to tell you whether the result will be shown in the same page. Aslo the source code is not complete.
Post a detailed source code and we will be able to help. Hope it helps.
it should be shown on the next request.
because your app should perform an HTTP redirect after POST request.
it can be same page though
I have a php file that contains a HTML form, then PHP logic, then an HTML footer...in that order.
I am trying to get the values from the form into some php validation logic in the botton of the page (but before the footer) using <?php VALIDATION LOGIC HERE ?>.
the problem is when the validation finds an error, the php logic will die() and hence, my HTML footer will not be executed.
is there a way to get my HTML footer to execute despite my php die();? ...or is there a better overall way to integrate my HTML and PHP? Thanks! Anyhelp would be much appreciated.
EDIT:
I actually have die() almost everywhere in my code where I am about to connect to a database. If the user credentials are correct, they connect..if credentials are wrong then it will die()..
Is this good practice and use of die()? it seems the solution to my problem is to use return() INSTEAD OF die()...in order to continue processing the HTML footer.
Also, I have situations such as mysql_connect() or die(). How can i would continue processing the remaining HTML page when die() is executed before the HTML is processed? ..i don't think mysql_connect() or return; is good practice right?
Thanks so much again in advance! The feedback has been very helpful!
As other states, you should have multiple files; header.php, index.php, footer.php, formvalidator.php.
In your index.php file, you should include header.php and footer.php.
In the form tag, action is sett to load formvalidator.php
In the form validator script, you could have something like this:
// All form fields are identified by '[id]_[name]', where 'id' is the
// identifier of the form type.
// The field identifier we want to return is just the name and not the id.
public function getFormData() {
$formData = array();
foreach ($_POST as $key => $value)
{
// Remove [id]_
$name = preg_replace('!.*_!', '', $key);
if (is_array($value)) {
$formData[$name] = implode(',', $value);
} else {
$formData[$name] = $value;
}
}
return $formData;
}
Now you can loop through the array and validate each field.
If you find an error, echo an error message, otherwise process the form.
Update
Answer to your update.
You should "never" use die(). Instead, exit thefunction you are in and return an error message. If you simply die(), you never know what went wrong where.
It is not possible to do server validation of a form unless you click the submit button.
You can put the code I gave you in the same PHP file as the form, and when you submit, you simply reload the same page (just set action="<?= $_SERVER['PHP_SELF'] ?>")
If you want to validate fields before submit, you must to this using javascript, like e.g. jQuery.validate.
Hmm... seem like you need some more knowledge of how to mix PHP with HTML.
Take a look at this beginners guide on how to work with forms in PHP.
I would use an external file for form processing and validation, then redirect back to the form page on error/success, displaying an error/success message.
I just make one header.php and one footer.php file. If there is an error just return instead of die.
This way at the top of your page you can just put:
<?php include('header.php');?>
///put in whatever html there may be
<?php
/// put your form and processing info here
///just return if you need to prevent further processing
?>
///put in whatever html there may be
<?php include('footer.php');?>
there are many better ways to do what you are doing. but to answer your first question, you can create a function called footer that returns a string with html needed to be displayed in the footer and call the die(footer()); but... why do you use die ? can't you just count the errors and display them somewhere in the result ? you should not kill the script that way.
And for the second question. you can use as BenTheDesigner said, a html page with the form action pointing to a php script that validates and either returns to the form if something went wrong or go somewhere else if not. but there too, you should remove the die() function and call something else to redirect you. you can use a template system like smarty to separate your logic from your html presentation. you can write it all in a single file but try to write you're entire logic at the top of the file and all the html at the bottom. and use <?=$var?> to display php stuff, or simple conditionals for diferent html results. but don't use die(). it just complicate things I guess.
Using die() is not a good practice because it will not show a friendly message to the user visiting your site. You should be absolute sure you want to use die. For example, you may use it in procedures when you suspect there is a hacking attempt. Instead try to use if else structure to show or hide things. Here is the possible prototype that you may want to implement:
// if there is a validation error, show it, otherwise not
if ($error == true)
{
// show footer
}
<!-- Your footer goes normally here -->