Basically I'v got a HTML Form that links to a php file in a different location for it's action, Currently I'm using the form to update the users profiles and then send them back to the editprofile.php. Basically at the top of editprofile.php if they've submitted the query I want to display the result of either "Profile Updated" or "Failed to Update", issue is I can't workout how to display query results when the query is in a different file.
I tried to do this;
<?php
if(!$query)
{
echo '<div class="editfail">Profile failed to update!</div>';
}
else
{
echo '<div class="editsuccess">Profile successfully updated!</div>';
}
?>
Except the issue with this is that the query hasn't been run on this page, it was run from another page and then redirected back to the editprofile page using a header, so how can I display the same results as above when the query is being executed from another location?
You can send parameter when you are redirecting back the file.
example
if(mysql_query($update_query))
{
header('location:editprofile.php?msg="success to save"');
}
else
{
header('location:editprofile.php?msg="failed to save"');
}
Or even you can send flag also
if(mysql_query($update_query))
{
header('location:editprofile.php?flag=0');
}else
{
header('location:editprofile.php?flag=1');
}
And check the value of flag in your editprofile.php file to display proper message.
You shouldn't mess around with the headers fxn unless you need to - depending on output_buffer settings etc they can be a pain:
You can do what you want - all in 1 single page:
So something like this -As a matter of common convention, and to a degree security, you should post the form to itself - you can integrate whatever else from the other page into the pass/fail profile logic block:
<?php
$query = htmlentities($_POST['profiletext']); #sanitize avec tu code du jour
if(!$query || $query != 'someacceptablevalue))
{
#If it's not posted, or its not a good value, tell them it failed
# and redisplay the form to try again
$query_msg = '<div class="editfail">Profile failed to update!</div>';
$profile_form = "<div_class='profile_rest_of_page stuff'>
<form action='#' method='post'>
<input type='text' id='profiletext' name='profiletext/>
</form>
</div>";
}
else
{
# They did it - Success, and link to next step
$query_msg = '<div class="editsuccess">Profile successfully updated!</div>';
$profile_form = 'No form needed - you did it';
}
#One block below handles all in 1 page with above logic:
echo "<body>
<div class='profile_message_container'>
$query_msg
</div>
<div_class='profile_rest_of_page stuff'>
$profile_redo<br/> You did it <a href='next'>next</a>
</div>
</body>
";
?>
You can do this in two ways:
Send the query results in the link like a GET which could be tampered with
Process the form in the same page that has your form as follows
if(isset($_POST['some_name'])) {
// Process form
} else {
// Display form
}
Related
I have a page which allows the user to "create a topic", open submitting this the form goes to another through a verification process which inserts the topic into the database and re-directs to back to the main page. However I want my verification page "add topic" to display an error message if all fields are not filled in. here is a my code, please can you tell me where I would need to add this validation code to notify the user to fill all fields:
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['name'];
$email=$_POST['email'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, email, datetime)VALUES('$topic', '$detail', '$name', '$email', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
My suggestion would be create a separate php file called validation and inside the validation file add a function. Of course you can create this function inside the same php file. If you made the separate use an include statement to place it on your page. Also a quick post-back to itself would be good since you could easily be able to get access to the posted variables and already be on the page to show errors. Otherwise you would have to return the Errors in a get, post or session. If everything was successful you could post or redirect right after the postback (maybe to a success page) and the user would only see the postback if errors present.
include_once("Validation.php");
as shown above.
validateNewTopic($topic, $detail, $name, $email, $datetime)
{
}
Then inside you could use if statements to check conditions. If you want a quick solution you can create a variable to hold all the errors.
$Error = "<p class='errors'">;
if ($topic == "")
{
$Error+="topic is required";
}
if ($Error != "<p class='errors'">)
{
return $Error +"</p>";
}
else
{
return "";
}
Since you are posting the values you can catch them in a variable on postback to validate.
$topic = $POST['topic'];
$Error=validateNewTopic($topic);
if ($Error != "")
{
?>
echo $Error
<?php
}
else {
//run sql code and show success
}
By putting the paragraph tags inside the $Error messages we can just echo and it will already be in the paragraph tag with the class errors. You can make it prettier by using an un-ordered list and when adding an error using list items. I'm not sure how familiar you are with php but at anytime you can stop writing php code by closing the tags. (< php ?> and reopen < ? php) as shown above in the if statement. I know this was not 100% clear but this is something you should try/research and practice since it is used so often. Good luck!
You can send the error to the main page by using php GET request, and then display it.
I have a page with links to reports. Whenever somebody clicks on one report, they can download the excel file. However, sometimes there are no fields to make a report; in that case, I want to display an alert message and after they click on "accept", they get redirected to the main panel. When they click on the report, they go to a controller that uses a switch to get the data. If there's no data, the model returns FALSE; so at the end of the controller, I check:
if ($result_array != FALSE)
to_excel($result_array->result_array(), $xls,$campos);
else {
echo "<script>alert('There are no fields to generate a report');</script>";
redirect('admin/ahm/panel');
}
If I get rid of redirect('admin/ahm/panel'); then the alert works, but it moves the user to the page that was supposed to generate the excel file. But if I use the redirect, the controller moves the user to the main panel without showing the alert.
echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";
and get rid of redirect line below.
You were mixing up two different worlds.
use this code to redirect the page
echo "<script>alert('There are no fields to generate a report');document.location='admin/ahm/panel'</script>";
Combining CodeIgniter and JavaScript:
//for using the base_url() function
$this->load->helper('url');
echo "<script type='javascript/text'>";
echo "alert('There are no fields to generate a report');"
echo "window.location.href = '" . base_url() . "admin/ahm/panel';"
echo "</script>";
Note: The redirect() function automatically includes the base_url path that is why it wasn't required there.
The redirect function cleans the output buffer and does a header('Location:...'); redirection and exits script execution. The part you are trying to echo will never be outputted.
You should either notify on the download page or notify on the page you redirect to about the missing data.
echo "<script>
window.location.href='admin/ahm/panel';
alert('There are no fields to generate a report');
</script>";
Try out this way it works...
First assign the window with the new page where the alert box must be displayed then show the alert box.
This way it works`
if ($result_array)
to_excel($result_array->result_array(), $xls,$campos);
else {
echo "<script>alert('There are no fields to generate a report');</script>";
echo "<script>redirect('admin/ahm/panel'); </script>";
}`
that worked but try it this way.
echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";
alert on top then location next
//functions.php:
<?php
function fx_alert_and_redirect($msg, $page){
**echo "<!DOCTYPE html><html><head>Login...</head><body><script type='text/javascript'>alert(\"" .$msg . "\");window.location.href=\"$page\";</script></body></html>";**
}
?>
//process_login-form.php:
<?php require_once '../app/utils/functions.php'; ?>
<?php
// ...
fx_alert_and_redirect("Mauvais nom d'usager ou mot de passe!", "../index.php?page=welcome");
?>
I have a list of comments for a given article and I have a form underneath the comments for a user to add their own comments.
I'm using php to do some form validation.
This is the process:
User fills out form (or not) and hits submit button. page refreshes.
PHP validates user input and either submits comments if no errors or
generates a list of errors.
If errors exist display the errors.
The problem is that I want the errors to display underneath the comments before the form which it does but when th epage refreshes, the top of the page is displayed and i need it to go straight to the errors and form (much like a page anchor)
Is this possible?
This is called after the submit button is clicked
if(empty($errors)){
$result = post_comment('event',$event_id, $sendername, $senderemail, $userurl, $comment);
if ($result == 'Correct') {
//header('Location: /'.$_SERVER['REQUEST_URI']);
header('Location: '.$_SERVER['REQUEST_URI']);
}
else {
$send_error = $result;
and this is near the comments and form where i want to page to go to if errors exist
// If there was an error sending the email, display the error message
if (isset($send_error)) {
echo "<a name=\"commentsform\"></a>";
echo "There was an error: ".$send_error;
}
/**
* If there are errors and the number of errors is greater than zero,
* display a warning message to the user with a list of errors
*/
if ( isset($errors) && count($errors) > 0 ) {
echo ( "<h2 class='errorhead'>There has been an error:</h2><p><span class='bold'>You forgot to enter the following field(s)</span></p>" );
echo ( "<ul id='validation'>\n" );
foreach ( $errors as $error ) {
echo ( "<li>".$error."</li>\n" );
}
echo ( "</ul>\n" );
}
}
}
Give the form an ID which can be jumped to via the URL:
<div id="submitComment">
<!-- Comment form here -->
</div>
And then redirect the user back to the same URL with the appropriate hash tag:
header('Location: http://www.example.com#submitComment');
Find your form tag, it will look something like this
<form action='yourpage.php'>
Put a hash tag after the URL along with the anchor it will go to upon submission-
<form action='yourpage.php#commentsform'>
Using page anchors you can jump the user to any part of the page by changing the hash in the url.
Make the form send the user to to anchor like so:
<form action='yourpage.php#comments'>
And make an anchor where you want your user to end up:
<a name="comments"></a>
I'm using this code:
if(isset($_POST['btitle'])) {
if(count($errors) > 0) {
foreach($errors as $error)
$errContent .= "<li>".$error;
echo notification(
$errContent,
FALSE,
"The following errors were encountered:"
) . "<div style='margin-bottom: 10px;'></div>";
}
else {
echo notification(
"<li>New form added!",
TRUE,
"Success:"
) . "<div style='margin-bottom: 10px;'></div>";
}
}
When I type something in the input named 'btitle' and hit the submit button, everything is fine, until I refresh the page - it should loose the data and start again after refreshing, but it keep saying "Success:" even if the 'btitle' input is empty.
What am I doing wrong?
you need to redirect the user to the same page and loose the post data.
header("Location: file.php?success=true");//or ?errors[]=blabla
exit();
now, in the same page (file.php) you need to:
if(isset($_GET['success']) && $_GET['success'] == true){
//handle true
}else if(/* here you can ask about errors or what ever */){
}
BTW, if you don't do it, the entire submitting form will be act again like you resubmit it.
for instance, if you insert data to the database, it will be insert over and over again when you refresh the page, so if you redirect as suggested, you loose the posted data and now you can show the errors or success.
When you hit refresh, your browser resends POST data to the page. This question has been asked many times, for instance here and here. Take a look at the answers to some of those questions to get an idea of what you can do.
I have a situation where a user fills out 1 of 2 forms on a registration page and is sent to a software download page. If they sign up as a new user, form is processed inserted into a MySQL database and they go to the page no problem.
Here is my issue. If they are a returning user and enter a license key, the processor script checks to see if its valid against the database and if it is it sends them to the software download page. If it is NOT a valid license key (heres what I dont like) the screen goes to the url of the script, page is white, an alert pops down telling them its not a valid license key and they are returned to the registration page to try again. I hate this. I need to figure out a way to either pop the alert on the registration page w/o leaving it or better yet display some kind of message on the page. One drawback is that the script is and always will be on a different server than my forms. Ive tried curl and had success with other situations but can't close the MySQL connection on this one. Is there another way to achieve some semblance of "cross domain AJAX" I would really like it to not go to the script url/white page/alert then return them. I would like it to happen all on one page. Here is that part of my script:
if ($_POST['license_code'] != "")
{
$result = mysql_query("(//mysql stuff here)");
if (($row = mysql_fetch_assoc($result)))
{
header("Location: http://" . $redirect);
}
//here is the part I dont like
else
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The license ID you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
}
mysql_close($link);
}
//I use jquery valiadate.js for CS validation, but realize this is necessary and would like it to behave like the desired result for the above
else
{
if (strpos($_POST['email1'], '#') === false)
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The email address you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
return;
}
thx
Is it possible to remove the alert and when you redirect to registrationpage.php also send a parameter using the redirect url and popup an alert or error message after the redirect ?
Look into using AJAX. jQuery has a great API for this:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/load/
EDITIED - For cross-domain
You could do something like this:
<div id="results"></div>
<script type="text/javascript">
$("#the_form").submit(function() {
$.getJSON("http://remote.domain/script/to/validate.php?data=" + escape($(this).serialize()) + "&callback=?", function(data) {
$("#results").html(data);
});
return false;
});
</script>
This will (once the IDs are pointed at the correct elements) intercept the form submission, pull together the values from the form (through the serialize() function), and shoot it out to the validation script via AJAX. The output of the script is displayed in the #results div.
Hope this helps!