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!
Related
It's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages that come from a file separate to the html/php form.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
All the research I've done hasn't gotten me far. I understand that sending the headers isn't good practice. I looked at ob_open (php function-I think it was called) and couldn't figure out how to properly use it. I couldn't find a question on here that satisfied the conditions I'm trying to meet either.
Any help is certainly appreciated.Thank You
EDIT: This is not a duplicate of 'Passing error messages in PHP'.
-------While the idea is similar, they are 'Passing error messages in PHP' before the headers are sent. Therefore it's not the same.
Store the error in a session and echo it on the destination page.
Put session_start() at the top of the code of the form.php page. Like this:
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<head>
Then replace the echo error with:
$_SESSION['error'] = 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
Use this in your conditions instead of the echo. Then in the form.php page:
if (isset($_SESSION['error'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
}
The unset makes sure that the error is repeated.
An HTTP Redirect causes a new HTTP request. Since php is stateless, it cannot natively support remembering a message to display to a specific user in another request. In order to get around this limitation, you would need to use a stateful storage mechanism (session or cookies), or pass the error message along to the next request via query string parameter. The usual way this is handled is by using session storage to save flash messages.
Here is a library that can make it a bit easier for you https://github.com/plasticbrain/PhpFlashMessages
Set session of error and display on the page on which you are redirecting
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
}
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 am converting all the values from xml to CSV successfully in the 2nd page(Export page). But i want to display a message "data converted successfully" in the first page(seat-matrix ).
I am failing to display the message in seat-matrix.php (1st page). Please help me.
In "Seatmatrix.php" file I have the following code.
<form name="export" action="export.php">
<input type="submit" name = "export" value="Export" title ='Exports all the above info to excel'>
</form>
In export.php file I have alert function and included header function to redirect to seat-matrix page as show below.
<?php
echo "
<html>
<head>
<SCRIPT LANGUAGE='javascript'>
function Result() {
alert (\"Data exported successfully\");
}
</SCRIPT>
</head>
<body>
";
// export feature code
echo "<SCRIPT LANGUAGE='javascript'>Result();</SCRIPT>\n";
header('location:Seat_matrix.php');
?>
Javascript doesn't get run until the browser gets it. Because of the header redirect it will never get run in the browser.
Your best bet is to set a session variable, then check if it is set in Seat_matrix.php. If it is, add your javascript.
A simpler way would be to post the result back to the original page and have it check. You would need to change your code to something like this:
if (isset($_GET['result']) {
if ($_GET['result'] == "success") {
echo "Data exported successfully.");
}
else {
echo "Error exporting data.";
}
}
<form name="export" action="export.php">
<input type="submit" name = "export" value="Export" title ='Exports all the above info to excel'>
</form>
And in the other code add the result variable to the url:
header('location:Seat_matrix.php?result=success');
Summary:
The first time you call Seat_matrix.php, there is no result variable and it program runs at it does now. Once the second program is executed, it calls back Seat_matrix.php and passess the variable result. The second time Seat_matrix.php is called, it checks if the result variable was passed and shows the message. You will probably have to play a little bit with the location where you want the message.
I hope this helps. Good luck!
Edit
To get rid of the $_GET variable after you write the success message, you could try something like:
if (isset($_GET['result']) {
if ($_GET['result'] == "success") {
echo "Data exported successfully.");
}
else {
echo "Error exporting data.";
}
unset ($_GET);
}
I haven't tested the above method, but I believe it might work.
You can use JavaScript to do the redirect instead:
<SCRIPT type='text/javascript'>
alert ('Data exported successfully');
window.location = 'Seat_matrix.php';
</SCRIPT>
Hello every I want to pass a message from php to JavaScript function and then redirecting to another page i want to show that message . Plz help me out . here is the sample code
Php
if ($result){
$success = "New Page has been added successfully.";
} else {
$error = "Unable to process at this time.";
}
Java script
<script type="text/javascript">
window.location="admin.php?page=add_user";
</script>
i want this &success message on another page by using this javascript function . i have tried in this way
window.location="admin.php?page=add_user&<?php echo $success?> ";
check this
echo '<script type="text/javascript"> window.location="test.php?page=add_user&msg='. $msg .'"; </script>';
Because you have spaces in your response, in order for it to be useful in the url you need to url encode it. See php urlencode function. Also, you have to give name to the query string parameter.
Change you JavaScript like this:
window.location="admin.php?page=add_user&success=<?php echo urlencode($success); ?>";