How do I obtain URL variables with Javascript - php

I'm writing a log-in system using PHP, mySQL and Javascript. My site is effectively a 1 page app written in javascript - only 1 html page. All interaction and navigation is done through javascript.
When a user registers, I create their record in the db with a 32 digit key in the activation column. I e-mail this to the registrant as an activation link. This takes them to a php file that activates their account (or not if there is an error). All well and good.
After activation (or error) I could take them to an html page (e.g. header('somesite.com/success.html') telling them whether their account is activated or not but I'd much rather take them back to a specific function in my 1 page javascript site. How can I do this?
I can take them to the site but how do I pass a message from my php re-direct to the site so it knows whether to display a success or error message?
Do I put it in the URL of the re-direct e.g. http://somesite.com?activation=success? If so, how do I get this variable into my javascript?
I could set a session variable from the php activation script and check it in my code but that seems very clumsy.
I could set a hash in the URL and pick that up in the code but I avoid hash navigation if I can. Any ideas on the method to achieve this?
Final answer from the help below and elsewhere on the site:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
then a redirect on registration such as somesite.com?email=somebody%40else#somewhere.com&key=7da93f78cb4942555863c161f50f258d
I can get these variables as simply as getURLParameter('email') and getURLParameter('key')
Thanks for everyone's help. Gotta love this site

You can get the variables from the URL with Javascript:
I actually asked a similar question (I can't find it) about getting URL variables with Javascript, and somebody very helpfully gave me this function:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {vars[key] = value});
return vars;
}
So to obtain a GET variable called 'activation' you would simple call the function like this:
getUrlVars()['activation']

since you have everything in your one page app, you could use that for the activasion as well -- have the activation link go to http://homesite.com?activation=<32characterkey> and when your app detects the GET param, use AJAX to call the PHP activation, and notify the user of the outcome.

You should use to AJAX to login and call your functions in the AJAX success/error callbacks.
You can do that easily with jQuery $.ajax() function
http://api.jquery.com/jQuery.ajax/

Related

AJAX or Direct Link

What is the best way to handle Ajax vs. Full page requests with PHP ?
I mean if I click a button that calls Ajax function and loads necessary info into a div and changes the URL.
How do I make that link work if the user copy it and use later to reach the same page.
In some of the apps I separate it with a hash. Something like a router and my code goes something like this:
var preRoute = document.URL.split('#');
if(preRoute[1] != undefined) {
//ajax call
} else {
//default page
}
you can try Jquery Adress http://www.asual.com/jquery/address/,
demo here
http://www.asual.com/jquery/address/samples/state/
or
http://vietcode.vn
You could check the headers. jQuery for example will add the following key/value to the header: X-Requested-With: XMLHttpRequest for ajax calls. See also this question
Using: jquery pjax - https://github.com/defunkt/jquery-pjax
you can detect on server side if you get X-PJAX request header
And a great feature of this plugin is the history manipulation and ease of use.

Use PHP to change contents of an element

For my login page, currently if the password is incorrect I have to redirect to another page. Is there any way I just insert or show the error message that shows up on the error page on the regular login page using PHP, thus eliminating the need for an error page? i could easily do it with jQuery ($("#error").css("visibility","visible");, but I don't know how to interact with the DOM using PHP, because it's executed on the server.
You can make all the Javascript(including Jquery) and HTML work using PHP by simply echoing the data. For example:
<?php
echo "<script>$('#error').css('visibility','visible');</script>
?>
Remember using Single quotes in the Javascript so as not to clash with double-quotes of echo function of PHP.
You really don't have to hide/show elements if I understand your issue correctly. You just echo out an error message when there are an error. Something like:
<?php
$showErr = false;
if ($err == true) {
$showErr = true;
}
//Put this part in code where you want content of the #error to be displayed
if ($showErr == true) {
echo '<div id="error">ERROR MESSAGE HERE</div>';
}
?>
If the error message needs to be generated in PHP, you may want to consider using AJAX. It is a JavaScript method for getting data from the server and doing something with it in client-side code, without changing the page of the web browser. However, it gets a bit more complicated to do it right, and doing it wrong will just make everything slower and buggier.
The idea would be to use an AJAX request (such as jQuery's ajax function) to submit the form data to a specially crafted link which returns a fragment parseable in JavaScript instead of an entire web page. That fragment would tell the client whether the log in was successful or not. If successful, the fragment should contain login credentials which the JavaScript callback should use to set any session cookies and redirect to whatever page you should end up on. If not successful, the fragment should contain the error message which the callback should display to the client. The JavaScript handling the AJAX request must also account for any transmission errors and it should provide feedback to the user that the form was in fact submitted; these things are provided by the browser with normal form submission but not with AJAX requests.

PHP Session Variable In JavaScript

How could I input php in this so when it has a correct password it stores the information as a cookie and then allow the deletion to it too.
<SCRIPT language="JavaScript">
<!--hide
var password;
var pass1="password";
password=prompt('Please enter your password to view this page!',' ');
if (password==pass1){
alert('Password Correct! Click OK to enter!');}
else
{
window.location="//Some Location//";
}
//-->
</SCRIPT>
If its simple enough (As per the title)
var varname = '<?php echo $_SESSION["variable_name"]; ?>';
But you have to seriously consider your logic. You are checking for authentication on javascript, which is going to be dumbest move in a web application.
The password is totally exposed, and any one can view them or turn off the javascript as a whole, then your whole site becomes vulnerable.
My suggestion is an AJAX request to a PHP page which separately checks and verifies the password and then returns message to the Javascript.
This is completely wrong:
You will have password displayed in the source code of the page and in the history of the browser for anybody to see. So even if they don't have the password, they can just check the source-code to get it.
You need to protect the current page server-side as anybody that disables javascript can open it now. An easy way to do that, would be to handle the login server-side and set a certain session variable for a successfully logged-in user. You can then check at the top of your page if that session variable is set.

How can I deny users access to parts of my Backbone App if they have not logged in?

So I've got a Backbone application + web homepage. Right now, if you login to my website, I create a global object with your user details from the database. However, you can still just hit one of the routes in the application directly.
How should I handle users who are not "logged in" and redirect them to a "you must login page"?
Is this a standard operation? Basically, I have a REST url setup that returns just
{ sessionId: [php-session-id-here] }
If they are logged in, it would return something more like this:
{
sessionId: [php-sess-id],
userId: [user-id-from-db],
firstName: [f-name],
lastName: [l-name]
}
Ideas? Thanks!
What I've done in the past is to include on every page along with jQuery (actually, added to the jQuery file) an extension on the AJAX method to check for a custom code that I send when a user isn't logged in. When that value was seen it redirected the user to the login page regardless of what was going down.
This was because that site had a time out on login, so a user could get logged out while sitting on a page and then the AJAX request would just fail. If you don't have a timeout on the login the odds of ever seeing this issue are slim. Just ignore requests that come from users that aren't logged in.
If you need help coding this, start here: Extending Ajax: Prefilters, Converters, and Transports.
Really shouldn't require anything as complex as pseudo-code:
JS needs to do some AJAX, so JS talks to server
PHP checks for login if needed
If not logged in, send back the abort message (I used a converter to catch a "notLoggedIn" dataType. However this could also be done with a transport, they are just more complex.)
JS sees the abort message and does a window.location redirect rather than return AJAX message.
If you want, you could load a lightbox with a login form and send that via AJAX to PHP where a re-login can take place, if you remember the AJAX attempt that failed you can send it again after login. Then the user doesn't even need to leave the page to log back in.
If you're using jQuery, you can set a global ajaxSetting that allows you to do certain things upon certain http codes. Some pages I read recommend adding to your JSON a url field to point to where to login, but I figure that's just up to you. So the only modifications you'd need to implement what I've mentioned is 1. change the http code to something reasonable like 401 (unauthorized) and implement the http code handler. But I wouldn't call this standard, I'd just say that's what several people have done (including myself).
<?php
function IsLoggedIn()
{
if(isset($_SESSION['id'])) // Change that to what you want
{
return 1;
}
else
{
return 0;
}
}
?>
Then in your code, you could use something like:
if(isLogged()){ header('Location: http://google.com'); }

PHP code cannot see query string param on return in Facebook oAuth flow

I am doing some integration with Facebook Open Graph using their oAuth flow and having issues with parsing query string parameters they return.
On my callback URL, they pass back an "access_token" parameter with a hash (#). so the callback would be:
http://mydomain.com/callback.php#access_token=foobar123
where foobar123 is my access token I'm trying to parse out.
However, no matter what I do, my PHP code cannot see if and I've done every debug trick I know (even using phpinfo() to go through everything). The URL is stated only as http://mydomain.com/callback.php. It's as if the rest of the URL isn't really there!
This code returns nothing:
$token = $_REQUEST['access_token'];
Any help would be greatly appreciated... I'm obviously missing something simple.
The url fragment (the part after #) is never passed to the server and so the PHP script would never see it.
The way you can handle it is using javascript on callback page which would take the url's hash part and post it to another page as query string parameter.
callback1.php
<script type="text/javascript">
var h = window.location.hash;
window.location = 'http://example.com/callback2.php?'+h;
</script>
callback2.php
<?php
$access = $_GET['access_token'];
?>
Although I'd suggest you have a look at Facebook Javascript and PHP SDK for what you're trying to do. All the basic oAuth functionality is already built in there.
to have the token passed as a query string to the server, just go to your facebook application settings, and look for the "Authenticated Referrals" section in the "Auth Dialog" tab.
Everything after # character is available only on the client side. You can try use javascript to access this value and store it in cookie or redirect user to the different URL. Some mock-up:
<script type="text/javascript">
var token = 'foo'; // In real, get value by parsing URL
window.location ('http://mydomain.com/callback.php?token=' + token);
</script>

Categories