Example of JS / jQuery to submit a form handled by PHP - 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

Related

web pages using javascript cant work if user's browser has javascript disable...so is there any way to run command like onclick without javascript?

plz anyone help me give me solution to run command like onclick without javascript....thanks
//javascript code:
function selectedproperty(id)
{
document.getElementById("pid").value=id;
document.getElementById("form1").submit();
}
function singleproperty(id)
{
document.getElementById("pid").value=id;
document.getElementById('form1').action="singlepropertydetail.php"
document.getElementById("form1").submit();
}
// html/php code
<ul>
<?PHP
$sql=mysql_query("select build_name,flat_no,property_id from new_property where owner='".$ownerid."'") or die(mysql_error());
while($row=mysql_fetch_row($sql))
{
echo "<li onclick='singleproperty(".$row[2].");' >".$row[0]." ".$row[1]."</li>";
}
?>
</ul>
You put a form with a button inside the li. The user clicks on the button and if js is disabled it posts back to the server and it does the logic presenting the user with the required modification to the page. You JavaScript to prevent the form from submitting and handle the logic client side if js is enabled.
Here is an idea of how it would look
<li onclick='singleproperty(".$row[2].");' >
<form method='post' onsubmit='return false'>
<input name='singleproperty' type='hidden' value='".$row[2]."'>
<input type='submit' value='".$row[0]." ".$row[1]."'>
</form>
</li>
To Pass the values to the server you can do either of the below
Use a submit button which will submit the form to the server. This will hide the parameters from the URL and would use request body.
If your page is just doing read operation it is safe to perform GET request on the page where the parameters will be present in the URL.
If you want to write an app which should work in the absence of JavaScript you must use design principles such as Graceful degradation & Progressive enhancement. Explaining in detail on how to achieve this will be outside the scope of this Question & Answer site.
Or, you can have a separate HTML only site as GMail does.
The decision of whether to support JavaScript less browser or have a separate site or do graceful degradation has to be thought through before the application is written and corresponding compromises has to be made well in advance.

Convert $_GET variables to $_POST and redirect page

I'm sending info through a link read in an email via $_GET (i.e. link in email is in form http://website.com?dogs=cats"). But I want the site URL to not have the appendages visible. So I've tried:
Linking to a page which saves the $_GET in a hidden form fields, then automatically submits the form; problem is that the back button then leads back to this intermediary page
Same as above, opening intermediary page in new tab, then having the form load another new tab (_blank), and closes itself; works fine, except in IE these are windows, which are annoying
I'm considering saving the $_GET results in a cookie, then redirecting the page with a header(), then extracting data and expiring the cookie.
Is there an easier way that I'm overlooking?
How about starting a session and storing them to the $_SESSION variables?
Here is a sample implementation of how you can make a hidden arguments on links. This sets a custom handler on the links which will copy hidden argument into the form and send it through post request. It is not a substitute to the session, but it can have it's own uses.
<form id="form" method="post" action="">
<input id="dogs" type=hidden name="dogs">
</form>
Sample link
<script>
$(function(){
$('a').click(function(ev){
ev.preventDefault();
$('#dogs').val($(this).attr('data-dogs'));
$('#form').attr('action',$(this).attr('href')).submit();
}
});
</script>

onclick replace php included file

I am not sure if what I am trying to do is possible but here it is.
I have a header, inside that header is a php include for "login.php"
On "login.php" is a link that takes the user to "forgot.php".
What I would like to do is, instead of the user being taken to "forgot.php" is to just refresh the page with "login.php" include replaced with "forgot.php" or do some sort of content switch out, sort of like using an Iframe.
I dont want to bring the user to a new page, I just want to switch out the content displayed inside my header.
Thanks for any help you can provide, code samples appreciated.
If you are trying to accomplish this without reloading the page you will need to use AJAX.
If you want to just keep the login.php you can perhaps do something like:
link
with php something like
<?
if ( isset($_GET['p']) && $_GET['p']=="forgot") {
include('forgot.php');
} else {
include('login.php');
}
PHP is parsed in it's entirety before the page is displayed in a user's browser, therefore, things such as onclick() or onsubmit() that are featured in JavaScript (a client-side language) are not available in PHP.
There would be a few solutions possible:
1) Use AJAX to submit a query to the server and replace the HTML content on the page with the result.
2) As you mentioned, use iFrames.
3) Have a hidden <div> on your login.php page that contains the HTML for forgot.php, and use a simple JavaScript onclick() method to swap the page contents. In this case, both "pages" would actually all be in the same file of login.php.
I can think of two things:
What I would do, assuming that the differences between your login.php and forgot.php aren't too different because you don't to change the page, is to put the html for the forgot.php just below the html for the login.php and hide the login.php html and show the forgot.php content.
example:
<div id = "login">
<!-- Login HTML -->
</div>
<div id = "forgot" style = "display:none" >
<!-- forgot password HTML -->
</div>
<input type="button" value="Forgot Password?" onclick="forgot()" />
Javascript:
function forgot(){
document.getElementById('login').style.display='none';
document.getElementById('forgot').style.display='block';
}
Otherwise, you could use an ajax call to the page and insert the necessary elements. This would create a noticeable pause.
You can't change the include statement from javascript because the script was already executed by the time you see your page in the browser.
Use ajax to dinamically change the content of the page without refreshing.
If you're using jquery the code would be pretty simple:
<script type="text/javascript">
$(document).ready(function() {
$('#link').click(function() {
$.get('script.php', function(data) {
$('#divOfContainer').html(data);
});
});
});
</script>
<div id="divOfContainer"><!-- the content to be fetched with ajax will be put here --></div>
Link

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.

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

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"

Categories