Changing the address of the website, as per the php being used - php

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"

Related

Example of JS / jQuery to submit a form handled by PHP

I have PHP code like this: (for signing out - located in a php page together with other php handlers for different functions and this file is included in pages like index.php or other relevant pages.)
if(isset($_POST['signout'])) { // logout button
// Clear and destroy sessions and redirect user to home page url.
$_SESSION = array();
session_destroy();
// redirect to homepage (eg: localhost)
header('Location: http://localhost/index.php');
}
I normally use a <form action="index.php" method="post"> where the function is currently included and <input type="submit" name="signout"> for such things but this time i would like to use an anchor tag like:
<a href="" >Sign Out</a> for signing out.
Would anyone be kind enough to show an example code that will trigger a submit that will be handled by the given PHP code above.
Either a jQuery or Javascript solution would do. I would just like to see a complete example on how this works.
There's good reason for using a POST for submitting authentication tokens which usually commences or alters the session state - but these don't really apply to the problem of closing the session - why not just just trigger this via a GET?
But if you really must do a POST, and you really must do it via a a href (rather than styling a submit button) and you really must do it via javascript (which will break if the client has javascript disabled) then...
<script>
function sendForm(formId)
{
if (document.getElementById(formId).onsubmit())
document.getElementById(formId).submit();
}
<script>
<form id='logout'>
<input type='hidden' name='signout' value='1'>
</form>
logout

How to redirect and inform the user if his or her password is incorrect?

Assuming I have a block of code like this on a login page:
<form action="login_action.php" method="post">
<div id="account">
<div class="form-label">Username:</div>
<div class="form-input"><input name="username" type="text" /></div>
<div class="form-label">Password:</div>
<div class="form-input"><input name="password" type="password" /></div>
<div class="form-submit"><input type="submit" value="Submit" /></div>
</div>
</form>
The login_action file queries the database with the given credentials and if they are correct performs $_SESSION['username'] = $username;
This works fine. However, if the user provides incorrect credentials, ideally the page would not redirect and instead it would display an error message on the page on the line before username. This is the part I am confused on how to tackle.
Would I instead have to capture the submit button press with JQuery and post the user credentials to the php file with AJAX? This would then get rid of the form on the login page. I suppose then I could return a string specifying whether or not the credentials were valid and if not, it would append a message to the account div that the credentials were incorrect.
Would that be the standard approach to this sort of problem? Since recently discovering AJAX I am using it for almost everything and I'm not sure if in this case it is the ideal solution. Overriding the submit button's default behavior and removing the form seems kinda hacky to me but I'm not sure. Is this how SO would solve this?
What I normally do is, use condition statement & redirect back to form if the password is incorrect. Assume your form page is form.php, the redirect could be form.php?status=password.
Then you can display an error message in your form
if ($_GET['status'] == 'password')
echo "Incorrect Password";
You can do this almost anyway you like, the only advantage to the AJAX method (that I can see) is perhaps less bandwith hog.
$("form").submit(function(e){
e.preventDefault();
//AJAX & other code here
});
The method that most basic login forms use is to have the login form post back to itself. If there is a problem with the username or password, just echo an error message to the page with PHP.
If for some reason you really want a separate handler page, you can use "flashes" where you store an error message temporarily in the session. The login page can then display that error message and erase it from the session.
Sending the values from the form to a php script via ajax is pretty much the perfect solution. The page wont reload, and the user will get a response quickly from the server. Here's your jQuery:
$('#form').submit(function(e){
// there are many ways to assemble this input data array, this is an easy clunky way,
// you could also use $.each to iterate over all input elements, get their
// vals, and pop them into the inputVals array.
var inputVals = [$('#input_id1').val(), $('#input_id2').val()];
$.ajax({
url:"your_php_script.php",
type: 'POST',
data:inputVals,
success:function(data){
// data returned from php script as a 'json_encode' string
}
});
return false;
})
//`
if(isset($_GET['msg']))
{
$message=$_GET['msg'];
}
?>` add following to ur login form
// ----------------------
// add this code to display error message if password dont match
<p id="m2">
<?php
if(isset($_GET['msg']))
{
echo $message;
}else{
echo "enter password";
}
?>
</p>
//------------------
add this code to your login.php script
$message="password do not match";
header("Location:index.php?msg=$message");

how to show a pop-up message(like this site) on submit form

i use of php and jquery in my application
i want when users submit success a form in page1 , forward form page1 to page2 and show a pop-up message(like this site) "success" and when they do not submit success , dont forward and just show pop-up message "error"
how i can implement this process?
thanks?
In your form, you can add some javascript into your form tag like so...
<form action="page2.php" onsubmit="if (CONDITION) {alert('Success'); return true;} else { alert('Error'); return false;}">
<input type="submit" value="Submit">
</form>
You can just a call a function ("return checkCondition();") in the onsubmit part and write the function in a separate Javascript file.
If the Javascript in the onsubmit part returns true, then it will go to the page specified in the action. If it returns false, then the form validation fails and it will stay where it is.
You would use something like this:
<?
if($form_success) { //
header("location: formpage2.php?success=1");
}
else {
header("location: formpage1.php?error=1");
}
?>
If you wanted to pass form data from page1 to page2 on success, use either or URL query string or store whatever's in $_POST in $_SESSION.
For the popup message, I would check for a success value in the query string of formpage2 and from there use javascripts alert to alert the user of their success.
I would not rely on Javascript itself in the first "return CheckCondition() in onsubmit" (by Muddybruin), but I would use it! I would not rely on it because the visitor CAN turn of Javascript and easily bypass the functionality.
I would also use the "header-redirection-answer" (by Levi Hackwith), but I would modify it to:
<?php
//checkform.php
if($form_success) {
//Include template or code here when form is successful
}
else {
//Include template or code here when form is unsuccessful
}
?>
If you absoutely must go to a specific file when form is successful, then I would include it instead of redirecting it. This is because redirections can cause unnessary issues regarding to links indexing in searchengines and it would be a lot slower than to just include directly into the checkform.php. Also keep in mind that header redirects must be sent BEFORE any other output is sent from the script.

Do browsers support autocomplete for ajax loaded login forms at all?

My problem is, that the browsers' (IE&FF) autocomplete does not work for my login form.
I have a webapp with CakePHP & jQuery. To allow visitors to login/register unobtrusively. The login form is inside a div, which is loaded via AJAX. (This enables logging in without a page reload.)
The browsers do recognize it as a login field, as they prompt me to save the credentials when clicking login. And they really do save the username/password, as they appear between the saved ones in the browser settings. But the saved username/password is never entered automatically. They do not appear pre-entered when the page loads. When I start typing in the username, the username appears as a suggestion, but even when you select it, the password is not entered next to it. Why? How can I get this working?
That you can test it yourself, here is a simple AJAX login form:
http://gablog.eu/test/ajaxlogin.html
It loads the following login form, if you go to the url below, autocomplete will work for just the plain form, so it is not a problem with the form itself, but rather that it is AJAX loaded:
http://gablog.eu/test/loginform.html
The layout:
<div id="user-bar">
<script type="text/javascript">
$(function() {
$("#user-bar").load('loginform.html').html();
});
</script>
</div>
The view loaded (when not logged in):
<form id="form-login" action="" onsubmit="login(); return false;">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" value="Login"/>
<div id="login-error" class="error-message"></div>
</form>
<script type="text/javascript">
function login() {
$.post('/ajax/login', $("#form-login").serialize(), function(data) {
if (data.success) {
$("#user-bar").load('userbar.html').html();
} else {
$("#login-error").html(data.message);
}
}, "json");
}
</script>
To clarify: I do not want to use AJAX autocomplete, I want the browser's autocomplete to work for my login form. This is an issue between my form and the browser. jQuery submission seems to play a minor role, as the usernames/passwords are saved. They are just not auto-entered for ajax loaded HTML elements! (The test site does not use jQuery submission.) Related question: browser autocomplete/saved form not work in ajax request
Autocomplete, in Firefox at least, triggers during page load. Adding the content afterwards would miss the window of opportunity.
A login form is tiny. I'd include it in the page from the outset and consider hiding it with CSS until it is wanted.
In case it helps, msdn says (towards the bottom of the page):
Note: if both of the following
conditions are true:
The page was delivered over HTTPS
The page was delivered with headers or a META tag that prevents
caching
...the Autocomplete feature is
disabled, regardless of the existence
or value of the Autocomplete
attribute. This remark applies to IE5,
IE6, IE7, and IE8.
I've emboldened the interesting bit.
.
I don't think you can get the form autocomplete to work if you load the form via ajax (security-wise I don't know if it can be really be abused or not, but the fact that a script could start loading fields into the page to see what data gets inserted doesn't look too good to me).
If you can, the best option would be to add a conditional block to the php file and include the form or not depending on whether the user is logged or not. If for some reason you can't do that, you might want to try to do a document.write() instead of the ajax call (and yes, using document.write is ugly :)
I see case when login form has to be pulled with ajax - if rest of the website loads as static html (cache). Login form (or authed user info) cant be displayed statically.
So your solution is to pull the form right after declaration (end tag) of the DOM element that serves as parent element for ajax-pulled loginform's html, ex:
<div id="loginforms_parent"></div>
<script language="javascript">
/* ajax request and insert into DOM */
</script>
And browser has the form in DOM onLoad. Tested, firefox does autocomplete in that case.
I'm not happy with loading the login form into my page at load time so I filed a issue with Chrome instead;
http://code.google.com/p/chromium/issues/detail?id=123955&thanks=123955&ts=1334713139
there is answer given : http://www.webmasterworld.com/javascript/4532397.htm . it does something with submit method and then uses click method. as i know values are not saved if form is not submitted. i think author of that solution just makes it submitted though submit button is not clicked by user.

HTML Redirect To Original Page

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

Categories