passing value to another page using javascript - php

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

Related

How can I see $_POST variable from a form using JQuery?

I am trying to obtain the $_POST variable generated from a login form using JQuery.
My web page has three sections Header, Navigation and Main.
"Main" contains the form and should be changed depending on the results of the input to the form, (login validation).
I can get the "main" section to change when thr form is submitted but cannot obtain the $_POST variables created by the form's tags.
I suspect I need to use ajax in order to do this but I am totally new to ajax and can't find a good and simple example to follow.
Help and suggestions as to how I can get this working would be greatly appreciated.
Here are the test files that I am using to try this out. (The array dump in TEST_1.php is always returned empty)
TEST.php
<?php
session_start();
echo "<!DOCTYPE html><html lang='en'><head>";
echo "<script language='JavaScript1.1' src='scripts/KSG.js'></script>";
echo "<script type='text/javascript' charset='utf-8'>
function valid_mem(){
if (document.form_1.member.value.length === 0){
req('Username.');
return false;
}else{
if (document.form_1.mpass.value.length === 0){
req('Password');
return false;
}return true;
}}
</script>";
echo "<script src='js/jquery-1.8.0.min.js'></script>";
echo "</head>";
echo "<body style='background-color:#eeeecc'>";
echo " <div style='background-color:#6495ed; height: 80px;'>";
echo " <div class='col-md-12 text-center'><b>HEADER</b> div</div>";
echo " </div>";
echo " <div id='mainx' style='background-color:#cccccc; height: 600px;'>";
require ('TEST_0.php');
echo " </div></body></html>";
?>
TEST_0.php
<?php
echo "<script type='text/javascript' charset='utf-8'>
$(document).ready(function(){
$('#form_1').submit(function(e){
e.preventDefault();
var z = valid_mem();
if(z){
var x = $('#form_1').attr('action');
alert('debug_1: '+x);
console.log(x);
$('#mainx').load(x);
}
});
});
</script>";
echo "<form id='form_1' name='form_1' action='TEST_1.php' method='post'>";
echo "<b>MAIN</b> div<br>A test form using submit<br><br>";
echo "Member: <input type='text' name='member' > ";
echo "Password: <input type='text' name='mpass' >";
echo "<button id='but1' type='submit' >OK</button>";
echo "</form>";
?>
TEST_1.php
<?php
echo " THIS IS A DUMMY PAGE: TEST 1<br><br>";
echo "<pre>";var_dump($_POST);echo "</pre>";
?>
First of all, you seem new to PHP in general. I recommend you read the "getting started" section on php.net (specifically, you shouldn't be "echo"ing everything, it makes your code hard to read - just leave it outside the tags).
Second, as PHP variables are server side, you cannot access them directly via JS. You have the following options:
Changing the page on the server side depending on the content of $_POST. As a rule of thumb, you should always do this when possible.
Embed the relevant data in $_POST in elements on the page via JQuery data attributes that can later be accessed.
As to AJAX, it is generally a great way to get data from the server side to the client side dynamically, but in this case it would be unneccesarily complicated, as $_POST is only available to the page the form is sent to.

Prompt not working with IF statement

Again, I'm very new to programming with PHP and JS. I pulled off a piece of code that is a JS prompt function within PHP to confirm a modification to data. The $confirmdelete variable is indeed "YES" when I type that in the prompt... (I checked it with an echo), but it keeps producing the "MODIFICATION ABORTED" message no matter what (and of course not changing the data).
Is my IF statement bad? Hope it is just a newb typo... Is this even a good way to do this? Thanks for any help...
<?php
//prompt function
function prompt($prompt_msg){
echo("<script type='text/javascript'> var answer = prompt('".$prompt_msg."'); </script>");
$answer = "<script type='text/javascript'> document.write(answer); </script>";
return($answer);
}
$prompt_msg = "Are you SURE you wish to make a modification? Type YES to confirm: ";
$confirmdelete = prompt($prompt_msg);
if ($confirmdelete != "YES") {
echo "MODIFICATION ABORTED <br><br>
<a href='index.php'>RETURN TO MAIN PAGE</a>";
exit();
}
?>
Ummmmm....
You cannot do that.
When the PHP code is outputted -- it is done. There is no more talking back to the server unless you add some AJAX handlers.
The only think your code outputs is this:
<script type='text/javascript'> var answer = prompt('Are you SURE you wish to make a modification? Type YES to confirm: '); </script>MODIFICATION ABORTED <br><br>
<a href='index.php'>RETURN TO MAIN PAGE</a>
Demo

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

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

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>

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