Basically I want a confirmation box to pop up when they click the button asking if they sure they want to restart, if yes, then it destroys session and takes them to the first page. Heres what i got...
echo "<form id=\"form\" name=\"form\" method=\"post\" action=\"nextpage.php\">\n";
echo " <input type=\"button\" name='restart' value='Restart' id='restart'
onclick='restartForm()' />";
and for the script...
<script type=\"text/javascript\">
<!--
function restartForm() {
var answer = confirm('Are you sure you want to start over?');
if (answer) {
form.action=\"firstpage.php\";
session_destroy();
form.submit();
} else
alert ('Restart Cancelled');
}
// --
</script>";
EDIT: Note that pressing the button brings up the confirm box, but if you click okay nothing happens sometimes. Sometimes if u click cancel it still submits the form (To the original action)
Unless your session_destroy() method in Javascript actually sends a request to the PHP script or something, it looks like you are trying to put PHP code in your javascript, which will not work.
You should try redirecting them to something like firstpage.php?reset=1 and inside the PHP script, you can check for the reset flag, then call session_destroy().
You should use
onclick='restartForm(); return false;'
to prevent the form from being sent.
Also, session_destroy() is not JS AFAIK...
EDIT: you should also remember that sessions are server-side, not client side, so if you want to manipulate them you cannot do it in JS. The only thing you can do is calling a PHP (e.g. via AJAX) that does something with the sessions.
Related
i am trying to make something related to paging, where i have a array of around 400-500 values..
i want to show 9 values at a time and then after clicking on NEXT button i want to show next 9 more..
Here is the part of the code i am using to call JS function onclick of button and that function's job is to get the count from the browser and set it to next value.
<?php
session_start();
$_SESSION['count']=9;
echo "<script type='text/javascript'>
function changelistnext()
{ ";
$c=$_SESSION['count'];
$c=$c+1;
$e=$c+9;
$_SESSION['count']=$e;
echo "
alert($c)
alert($e)
}
</script>";
?>
<button id='next' value='next' onclick='changelistnext()'>Next</button>
But everytime i click on the next it shows the same value....
You can't mix JavaScript and PHP as if they were one and the same.
JavaScript is a client-side language, which is executed in your browser.
On the other hand, PHP is a server script, and sessions are also kept on server.
If you open your page's source code in a browser, you will see that the session stuff is not there - it was executed by PHP when the page was generated. You can't use sessions directly in JS.
The page contains essentially this:
<script type='text/javascript'>
function changelistnext()
{
alert(some number) // value of C when the page was generated on server
alert(some number) // ditto for E
}
</script>
You could use Ajax call to ask some script on your server to give you data for the next "page" - PHP script can access the Session variables and send what you want back to the browser.
My code has a text input and submit button which on return hides that form and displays a new button, which works. The problem I'm having is setting the value of the button (or innerHTML) to the answer in my query (which will always only be one). I have the following code:
echo '<form><button id="HCP_Btn" name="HCP_Btn" style="display:none"></button></form>';
$HCP_num = $_POST['HCP_num'];
$HCP_Query="SELECT * FROM HomeCareProviders WHERE Number='". $HCP_num."'";
$HCP_result= mysql_query($HCP_Query) or die(mysql_error());
if (mysql_num_rows($HCP_result)==0){
echo 'Sorry there are no Home Care Providers with the number entered.';
}
//HCP_Btn.innerHTML='.$row["name"].';
else {
$row = mysql_fetch_array($HCP_result);
echo '<script type="text/javascript">
HCP_Btn.style.display="";
document.form.HCP_Btn.innerHTML='.$row["name"].';
</script>';
}
You can use this Javascript code
echo '<script type="text/javascript">
document.getElementById("HCP_Btn").style.display="";
document.getElementById("HCP_Btn").innerHTML="'.$row["name"].'";
</script>';
For first change it like this
echo '<script type="text/javascript">
//HCP_Btn.style.display="";
document.form.HCP_btn.innerHTML=\''.$row["name"].'\';
</script>';
for second check if $row["name"] gives you the right value and at last check you javascript console for errors.
Also HCP_Btn.style.display=""; mean nothing like this.
The problem is probably because Your button's id is HCP_Btn but in the JS further You are accessing it like HCP_btn - the problem could be small b. Also You are missing quotes for the innerHTML value.
Change the line
document.form.HCP_btn.innerHTML='.$row["name"].';
to
document.form.HCP_Btn.innerHTML="'.$row["name"].'";
^ ^ ^
make the b uppercase add quotes ----------^
EDIT: Have You ever tried jQuery? It is commonly and widely used JavaScript framework that makes JS programming so much easier (after You know it)... With jQuery, You could just do:
echo '<script type="text/javascript">
$("#HCP_Btn").css({"display":""}).html("'.$row['name'].'");
</script>';
How is the information from your JavaScript call returned to the innerHTML itself? When does it get called and changed? I think you should do that first.
You have an user pressing a button. Then you go to the database using PHP (need a new request response for that), with AJAX or JavaScript you could make it work client side.
I think that you are mixing up server side and client side issues. You should at least need a function call on the onClick event to toggle the display of the button and show the information. That onClick event should call a JavaScript function and that will handle the change.
So here's my situation: I have a form that validates with PHP. I want to make it so that if the form fails validation, the user is forced to click through a confirmation dialog before they navigate to another page (the form is fairly large and they don't want to accidentally leave it before it's saved). I'm going about this like so:
see updated function below,
Basically use php within the function to either set the body to present the confirmation or do nothing depending on the error status of my form. Nothing happens when the form isn't submitted and I click a link, good. When the form is displaying errors and I click a link the confirmation dialog will appear but canceling it causes it to reappear. If I cancel it a second time the page request will go through even though it's not supposed to. I'm not that familiar with javascript so I'm not sure what's going on. Is there a better way I should be going about this?
Edit: I figured it out, it was a combination of things. The first was a really dumb mistake on my part: I was calling the onlick on both tags AND the tags for each link in my list, hence why the box popped up twice.
the second piece was that even though my function already returns bool, the onclick requires an explicit return declaration. I was doing:
<a onclick="forceConfirm();" href="somepage.html">Blah</a>
When it should have been:
<a onclick="return forceConfirm();" href="somepage.html">Blah</a>
Then just edit the PHP so that forceConfirm always returns true when the form hasn't been submitted, bypassing the confirmation:
function forceConfirm(){
<?php
if($form->errorStatus){
echo 'if(confirm("Are you sure you want to navigate away from this page? All unsaved changes will be lost.")){'."\n".
'return true;'."\n".'}'."\n".
'else{ return false;}';
}
else{ echo 'return true;';}
?>
}
Now I just need to figure out how to use jQuery to apply this to all links without having to put onclick events all over the place....
You can use confirm() like this:
if(confirm("Are you sure you want to proceed?")){
document.location = 'confirmed redirect url...';
}
else{
document.location = 'cancel redirect url...';
}
Then you'd wrap that in the same PHP block as in your example, displaying it if necessary and hiding it if not.
I have a one page site that has PHP code in it. Once the user presses 'Send', this sends the information to my email, then displays a messagebox saying that the action was a success to the user - great.
After the messagebox is closed, the website stays at website.com/report.php. Is there a way to redirect it back to the original page.
Also, any way to change the icon in the messagebox that pops up? Here is the code that I have:
<script language="JavaScript">alert("Your request has been sent. I will contact you soon!");</script>
Thanks.
Look into window.open and window.location
Place it after your alert()
http://www.tizag.com/javascriptT/javascriptredirect.php
Also, to answer your messagebox icon question: No, it is browser-dependent and not modifiable.
If you want to do that, your are going to need to fake it with html/css and javascript.
<script language="JavaScript">
alert("Your request has been sent. I will contact you soon!");
window.location.assign("http://website.com");
</script>
If you want to change the icon in alert box or make it look a little fancy, you could try YUI dialog
Use this code to display the alert:
function displayAlert(message, redirect) {
alert(message);
window.location.href = redirect;
}
Then, you can use code like:
displayAlert("This is the message", "http://redirect.the/user/here");
Use the php header command
<?php
header("Location: http://www.example.com/");
exit;
?>
To do a redirect in PHP, use header("Location: page.php"); for this. Before and after this your code shouldn't be sending any other output to the response. Eventually use exit(); to terminate the script afterwards.
If you need the page which was requested right before this page, then best what you can do is to include its URL as request parameter of the link to report.php and use it as redirect destination. E.g.
report
and in the report.php pass it as hidden input field:
<input type="hidden" name="referrer" value="<?php echo getParam("referrer"); ?>">
And after submitting the report do:
header("Location: " . getParam("referrer") . ")"; // getParam() returns sanitized GET parameter.
An alternative is to use the $_SERVER['HTTP_REFERER'] header (yes, including the typo) for this, but this is just not that reliable as it may be disabled or spoofed by the client.
I believe a more elegant solution is to simply present the user with a confirmation page (instead of an alert box), and place a link to the previous page there.
That would at lease work for all users.
For those users with javascript a little Ajax (jQuery) could submit the form for you, and display the confirmation nessage. All without leaving the page the user is on (negating the need for any fancy redirects).
Towards the end of your php, use this:
header('location: home.php');
This will cause the browser to load the original page.
I don't believe that the standard alert box can be altered, aside from the message. You can't change the title or the buttons, either.
Frank
I have a button in my abc.html page
<input type="button" onclick="javafun();">
on the click it goes to javascript, which further send info to my abc.php ...and the javascript function looks like:
function login()
{
xmlhttp=GetXmlHttpObject();
//alert("pass");
if(xmlhttp==null)
{
alert("Your browser does not support AJAX!");
return;
}
var url="login.php";
url=url+"?id="+username+"&passwrd="+passwrd;
xmlhttp.onreadystatechange=statechangedLogin;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
}
function statechangedLogin()
{
//alert(xmlhttp.readyState);
if(xmlhttp.responseText=="<font color='red'>Your User Name or Password is incorrect. Please try again.</font>")
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
else
{
//hwin=window.location="http://forum.research.bell-labs.com/zeeshan/qotw/login.php";
document.getElementById("mainbody").innerHTML=xmlhttp.responseText;
//hwin.document.innerHTML=xmlhttp.responseText;
//alert();
}
}
Everything works fine, but the address of the website in the address bar remains the same:
http://severname.com/abc.html
i want this address bar to change, according to the php. it should come to ...
http://severname.com/abc.html/login.php
but still should not show ?id=username&passwrd=passwrd
Is this possible, and if it is how??
Zeeshan
POST the request to ../login.php ?
instead of using ajax, wrap your form elements in
<form method=POST action="login.php">
User Name: <input name="username"><br>
Password: <input name="passwrd" type="password"><br>
<input type="submit" name="Login">
</form>
Why are you doing AJAX if you want the address bar to change?
Edit
Added real values to the form
Edit 2 More clarity.
You really should do the login via form (see #nathans post).
Rename your html login form into a php page. Lets call it loginForm.php.
Remove all the javascript functions from loginForm.php
Insert the form into loginForm using the form tag.
In login.php, you check to see if they user logged in successfully,
If the login suceeded:
$failMsg = urlencode("Logged in successfully")
header("Location: loginForm.php?okMsg=$msg&redirect=home.php");
If the login failed:
$failMsg = urlencode("Failed to login")
header("Location: loginForm.php?failMsg=$msg");
In your loginForm.php where you are displaying your error messages now, put:
<? echo htmlentities($_REQUEST['failMsg']);?>
In loginForm.php where you are displaying success log in message put
<? echo htmlentities($_REQUEST['okMsg']);?>
And in the head tag put
<? if(array_key_exists($_REQUEST,'redirect'))
{
echo "<meta http-equiv='refresh" content='5;url=/".$_REQUEST['redirect']."' />";
}
?>
There no javascript and the user gets nice pretty error messages and is forwarded to the home page after logging in.
<form method="post" action="login.php">
You don't need AJAX to do that at all. If you're using the Javascript to validate the input you can add onSubmit="return my_validation_function() ... your validation function should return true if everything was okay or false if it was not. (The false return value will stop the form from submitting)
It sounds like you don't want AJAX at all, just a regular form, unless I'm missing something.
I think you have misunderstood the whole point of AJAX. Ajax is supposed to work in the background, i.e. not changing the url. If you want that, try document.location="foobar";
Ajax hides JS interaction with your server. That's what is for. If you want your browser to point to some URL, then you shouldn't use Ajax.
The thing you're trying to archieve can be easily implemented using a simple POST request, using the good old <form>.
HTTP POST requests hide the parameters of the request from the URL, passing them inside the header of the message itself. So URLs can be clean.
As other commenters have touched upon, the real answer is that you can't change the URL of a web page (other than the "#" fragment identifier, but that's not useful to you) without causing the browser to send a request to that url.
You want to not bother trying to change the URL if you're submitting via AJAX. Or, you can make a post request as suggested in other comments.
<form method="post" action="login.php">
Your method is somewhat insecure and vulnerable to some scripting attacks. I'd look at not doing an Ajax login and just use a regular form as well. This article helped me a ton:
http://www.evolt.org/PHP-Login-System-with-Admin-Features
Evolt has another one that looks similar to what you were trying to accomplish, but I've not read it -- just Google "evolt ajax login"