Failng to display "data saved" message in the front end - php

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>

Related

How to call php function on html form submit - in the same page

Okay so I have an html form in Add.html. When I click submit, I would like the data to be added to my database via php and then return to the same form with "instance added" or "failed blah blah."
The only way I know how is to set the form action to a separate php file and call that - but then the php file renders and I do not return to the same form.
I would like to not have to add a "return to form" button and would prefer to return to the form on submit with a status message.
Any better ways to do this?
A very simple way to do is to do following :
yourpage.php
<?php
if(isset($_POST)){
//data posted , save it to the database
//display message etc
}
?>
<form method="post" action="yourpage.php" >....
You can do a redirect in php, to the html form - and you can set a "flash message" - to show "instance added" by saving "instance added" to the session and showing that value when you redirect to html.
you can use this trick
<?php if (!isset $_POST['Nameofyourinput']){
?>
<form method="post" action="add.html">
// your inputs here along with the rest of html
</form>
<?php
}
else
{
// Update you database and do your things here
//in your request variable you can add the error you want if things didn't go well, for example
$result = mysqli_query($connection, $sql) or die('Instance not added !'.$req.'<br>'.mysql_error());
// and then
echo (" instance added")
};
The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
Just give nothing to the action attribute. It will refer to your current page.
<form method="post" action="">
Other way to do this are:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Or just add '#'
<from method="post" action="#">
To handle php code. Write your code inside it.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// write your code here.
}
You should change your file extension from .html to .php .
Well you can employ old school AJAX. For instance,let's say we have a form that takes in a number N,and once we click the calculate button we should see the result the of 2^N displayed on the same page without the page being refreshed and the previous contents remaining in the same place. Here's the code
<html>
<head>
<title> Simple Math Example</title>
<script type="text/javascript">
var request = new XMLHttpRequest();
function createAjaxObject(){
request.onreadystatechange = applyChange;
request.open("POST","calculate.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("N="+document.getElementById('N').value);
}
function applyChange(){
if(request.status == 200 && request.readyState == 4){
document.getElementById('resultSpace').innerHTML = request.responseText;
}
}
</script>
</head>
<body>
<fieldset>
<legend>Enter N to get the value of 2<sup>N</sup> ::: </legend>
<input type="text" name = "N" id = "N">
<br>
<input type="button" value = "Calculate" onclick="createAjaxObject()">
</fieldset>
<div id="resultSpace">
</div>
</body>
The file calculate.php is the same file with the above code. When the calculate button is clicked, it calls a function createAjaxObject which takes in a value N and sends the value to the same file via the POST method. Once the calculation is done, a response will be sent. And if the response is successful, it will be sent to a function called applyChange which will render it to the same page via JavaScript.

Displaying query results in a different place from the query

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
}

How to prevent html elements from being a part of response in $.ajax success response?

I am submitting an html form through ajax and printing the errors through the same .php file. My code looks a bit like
1.php
<?php
if(!cond){
echo "error1"
}else{
echo "error2"
}
?>
<form action="#">
<button> and other elements.
Now if i print $('#err').html(response) from my .js on any error it obviously prints whatever 1.php has to offer including html button and what not. My problem is I don't want these html entities in my response. I can obviously match for each and every error from .js and print them all individually but I was wondering if there is an efficient way to do this.
Well, if doing everything in a single file is a requirement, you could just check HTTP_X_REQUESTED_WITH header like this:
<?php
if(!cond){
echo "error1"
}else{
echo "error2"
}
if (!strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
?>
<form action="#">
<button> and other elements.
<?php
}
But a better way to go is to create separate php file which will handle your errors.
You can only return an error code and handle it by javascript something like this:
in present.php
eval("x=" + response);
if(x.Err=='2')
{
//show error and ...;
}
and in service.php :
$Res[Err]=2;
echo json_encode($Res)

Display alert message and redirect after click on accept

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");
?>

improve my PHP user interaction

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!

Categories