issue capturing the hashed URI parameters in Coldfusion [duplicate] - facebook

I have such url - http://www.coolsite.com/daily-plan/#id=1
What the easiest way to parse that string and read a hash value (the value after #id=)?
Thank you

On client side (i.e. from JavaScript) you can check window.location.hash to get hash. On server side, general answer is 'it is impossible' since hash is not sent in request to server.
Upd: I maybe misunderstood the question. My answer is about how to get hash part of url either in browser or in server side code during request processing, not about string processing.
Upd2: Answer to comment here because it doesn't fit in comment.
How does it work when user clicks on your navigational links?
I assume hash is changed and corresponding content is downloaded via AJAX request from web service or REST.
For example if your user has URL www.example.com in his browser and this page shows a list of product categories. User clicks one category and URL changes to www.example.com/#id=5 and products from that category(with ID=5) are downloaded via AJAX and shown on the page. No postback, only partial page refresh.
Is this close to your scenario?
Now you want user to paste/enter www.example.com/#id=5 directly in the browser address bar and go directly to list of products in that category.
But /#id=5 is not sent to server with request by the browser, so there is no way to get that value on server side, and you can do nothing about it since it is the browser decided not to send this data and you don't have it on server side.
In our project we use solution when server returns only common page code/html, i.e. header, footer, without main/center part of the page. Then there is a JavaScript code which executes right after this common HTML loaded. It takes window.location.hash and sends it to web service via AJAX and web service returns content (HTML) for the main part of the page.

new URI("http://.../abc#xyz").getFragment();
See the Javadocs for URI

Here is how to capture anchor links. Works across all web frameworks.
I'll use an example scenario to illustrate: let's say we need to capture a deep URL http://server.com/#/xyz requested by an unauthenticated user so that they can be redirected to that deep URL post-login.
The unauthenticated user requests http://server.com/#/xyz (everything from the '#' onwards is not sent to the server).
All the server knows is that the user wants http://server.com/ and that they are unauthenticated. Server redirects the user to a login form.
Here's the clever bit: the client is still waiting on their original request so if the server includes a hidden element in the login form with some JS that references window.location.href, it can capture the full URL of the original request complete with the anchor portion:
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<!-- XXXXXXXXX CLEVER BIT XXXXXXXXXX-->
<script>
document.write('<input type="hidden" name="from" value="'+document.location.href+'"/>');
</script>
<!-- XXXXXXXXXX-->
<div>
<input class="submit-button" type="submit" value="Submit"/>
</div>
</form>
The user authenticates themself and the original URL is sent with the POST. The server can then relay the user to the original deep URL.

String url = " http://www.coolsite.com/daily-plan/#id=1";
int sharpPos = url.indexOf('#');
String q = null;
if (sharpPos >= 0) {
q = url.substring(sharpPos);
}
Surely you can use various methods of string manipulation including regular expressions.
But actually your example is strange. Typically parameters of URL are passed after question mark. In this case you can just use standard class URL:
String q = new URL(" http://www.coolsite.com/daily-plan?id=1").getQuery();

what you are using to do this ?
If you are using jsp or servlet following will be useful to you
if (request.getParameter("#id") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request.getParameter(i)+"</b>!");
}
If you are using javascript for it following function will be useful to you
function getURLParameters()
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
alert(arrParamNames[i]+" = "+ arrParamValues[i]);
}
}
else
{
alert("No parameters.");
}
}

REPLACE the '#' with '?' when parsing the url. Check the code below
String url = "http://www.coolsite.com/daily-plan/#id=1";
String urlNew = url.replace("#", "?");
String id = Uri.parse(urlNew).getQueryParameter("id");

If you URL will the same as you write and doesn't contains anythins else then whis code on Java will help you
String val = "http://www.coolsite.com/daily-plan/#id=1";
System.out.println(val.split("#id")[1]);
Don't forget check to null value.
P.S. If you use servlet you can get this parameter from request.getAttribute("id").
With best regards,
Psycho

if your url get from OAuth callback,then you can't!
because the full url won't send to service because of hash(#)

Related

Redirecting based on GET request data in GitHub pages

I used to have a dynamic website, which made use of GET requests to specify pages, e.g. https://www.example.com?n=about. I have now moved over to a Jekyll site on GitHub Pages (with a custom domain), but ideally would like these old links to work.
Currently, as one would expect, such links simply return the index page. Is there any way to get the above url to redirect to https://www.example.com/about/?
There is no built-in option in GitHub pages. You cannot redirect URLs using a .htaccess file on the server.
But you can of course use client-side Javascript code:
<script>
var queryString = window.location.search;
if (queryString === "?n=about") {
window.location.replace("https://www.example.com/about/");
}
</script>
For different URLs, you'd need to store the mapping between the old and new URL, and then use a switch statement (or an if/else) to perform the redirect.
<script>
var queryString = window.location.search;
var mapping = {
"?n=about": "https://www.example.com/about/",
"?n=home": "https://www.example.com/home/",
"?n=test": "https://www.example.com/test/"
};
switch (queryString) {
case "?n=about":
window.location.replace(mapping["?n=about"]);
break;
case "?n=home":
window.location.replace(mapping["?n=home"]);
break;
case "?n=test":
window.location.replace(mapping["?n=test"]);
break;
}
</script>
Learn more about the location.search property.

how so synchronize GET API call in Angular Component?

I just started with Angular and I have an issue with its components and an API call. I have the following content in these files
user.component.html:
<div>
<p>
{{user.name}}
</p>
</div>
user.component.ts:
getUser() {
this.user = this.postService.getPosts();
console.log('TWO');
console.log(this.user);
return false;
}
user.service.ts:
getPosts(){
this.http.get('https://XXXXX/yyy').subscribe(data => {
this.str = data[0];
console.log('ONE');
});
return this.str;
}
The Get response is done correctly and I am able to display the data in the html file ONLY if user is loaded, but the first time that I try to do the request to the API the component.ts finishes its execution before the service, and user is not populated correctly, making the html render empty, so with above code I get this printed in console:
TWO
undefined
ONE
I think if it would be synchronized, it would print:
ONE
John
Two
I found this post but I wasn't able to understand it: Angular - Wait until I receive data before loading template
Can someone please try to help me with this?

How can I redirect an address starting with #!

I have a new wordpress site instead of my old Wix one.
in the old one there were page addresses like http://example.com/#!contact/ct07/ in the new one this page resides under http://example.com/contact
I've tried 3 redirections plugins but none works (Redirection, redirection editor, quick 301 redirect).
I have no access to the .htaccess file
On redirection it seems like the engine does not see the URL.
Any manageable idea besides JS ? I don't want to miss google juice
Browsers don't send the part after # to the server, so the server don't know about this part and won't be able to do the redirect.
So you have to do the redirection in javascript:
if (/^#contact\//.test(document.location.hash)) {
document.location = '/contact';
}
For SEO purpose, you may want to handle the _escaped_fragment_ parameter too
I had this problem a few weeks ago.
PHP does not get anything after hash tag, so it is not possible to parse request url and get hash. But JavaScript can.
Below you find my solution for WordPress redirects by hashtag #! :
(You should put this code in functions.php of your active theme):
function themee_hash_redirects() {
?>
<script type="text/javascript">
function themee_hashtag_redirect( hashtag, url) {
var locationHash = document.location.hash;
if ( locationHash.match(/#!/img) ) {
if ( hashtag == locationHash ) {
document.location.href = url;
}
}
}
// Examples how to use themee_hashtag_redirect
themee_hashtag_redirect('#!contact', '/qqq/');
themee_hashtag_redirect('#!zzz', '/aaa/');
</script>
<?php
}
add_action('wp_footer', 'themee_hash_redirects');

Facebook Credits Example on App Engine?

Are there any examples of using facebook credits on Google App Engine?
I found this blog post , but it's not complete
http://blog.suinova.com/2011/01/integrating-facebook-credits-api-into.html
I got the sample runwithfriends example working on the App Engine, tried to expand it with Credits, no luck so far.
Also searched for the FB developer forums, got nothing.
Any resources you can point me to?
What's not working:
1) When I click on the "pay with Facebook" button, I get an "Application Error" , without any error code.
-Checked the javascript console
-Checked the fb app settings
-Tried on local server and production server
2) The callback.py isn't complete, because i could not parse the signed request (no code available in py for me to learn from)
3) What I basically did was to add code from Suinova Designs (link above) to the existing Run With Friends app code. Didn't turn out as expected.
my code so far:
//payment_page.html
<html>
<table>
<tr><th>Name</th><th>Price</th><th> </th></tr>
<tr><td>Something to buy</td><td>10 FC</td><td><a href="" onclick="return buyit();">
<img src="http://www.facebook.com/connect/button.php?app_id=215638625132268&feature=payments&type=light_l" />
</a></td></tr>
</table>
// javascript
function buyit(){
FB.ui({
method:'pay',
purchase_type:'item',
order_info:{
item_id:'myitem',
title:'Something to buy',
price:2,
description:'Whatever',
image_url:'http://www.facebook.com/images/gifts/21.png',
product_url:'http://www.facebook.com/images/gifts/21.png'}
},
function(resp){
if(resp.order_id) window.top.location='http://apps.facebook.com/runwithfriends trial'; else alert(resp.error_message);
});
return false;
}
//callback.py
class FacebookPaymentRequest(webapp.RequestHandler):
def post(self):
signed_request = parse_signed_request(self.request.get('signed_request'),conf.FACEBOOK_APP_SECRET)
payload = signed_request['credits'] #credits:{buyer:int,order_id:int,order_info:{},receiver:int}
order_id = payload['order_id']
method = web.request.get('method')
return_data = {'method':method}
if method == 'payments_get_items':
order_info = payload['order_info'] #order_info:{item_id:'',title:'',description:'',price:0,image_url:'',product_url:''}
item = simplejson.loads(order_info) #needs to convert JSON string to dict
#check item,price,etc and reply
return_data['content'] = [item]
elif method == 'payments_status_update':
status = payload['status']
return_data['content'] = {'status':'settled','order_id':order_id}
if status == 'placed':
#just return settled status to Facebook, this may be called twice
order_details = simplejson.loads(payload['order_details'])
#check and log here
elif status == 'settled':
order_details = simplejson.loads(payload['order_details'])
#order_details:{order_id:0,buyer:0,app:0,receiver:0,amount:0,update_time:0,time_placed:0,data:'',items:[{}],status:'placed'}
buyer = order_details['buyer']
item = order_details['items'][0]
#now save this transaction into our database
else:
#may be refunded, canceled, log the activity here
return_data['content']['status'] = status
self.response.out.write(simplejson.dumps(return_data))
Your python code looks fairly normal so I would guess that you are simply having trouble with your authorization. Depending upon how you authorize (a process a fair amount more complicated that the credits system), you are likely being given a signed request that is only partially authorized... meaning you are authorized to access only certain parts of facebook, but generally not authorized to access the active/logged-in user (i.e. me).
You can verify this by determining if you signed_request is a full 80+ characters (as opposed to around 40). Generally I try to authenticate by deciphering the profile (signed_request), if that fails then I try to use a previously stored cookie, then if that fails I try to relogin the user. I determine failure by placing try/except around my calls to get a "me" object through the GraphAPI.

How to get referrer http header at Gwt Entrypoint

I Couldn't find any class/method which gives me access to the referrer header in GWT.
anyone knows about this?
See
Document.get().getReferrer()
Since you can't get the headers in javascript, I don't think you can get them in a GWT client either: Accessing the web page's HTTP Headers in JavaScript
Update:
Maybe you can update login.php to write out the referrer to a hidden input tag, maybe something like this:
<input type="hidden" name="referrer" name="referrer" value="<?php Print referrer_value ?>">
Then, in gwt you should be able to get the value using something like this:
InputElement elt = (InputElement)Document.get().getElementById("referrer")
String referrer = elt.getValue()
Note: This is untested code, and I'm not even sure that is valid php, but hope this helps!
I had the same question, but I made some changes to charge the header link tag dinamically.
I used this code:
LinkElement link = Document.get().createLinkElement();
link.setHref("css/home.css");
I don't know if is the most graceful solution, but it works!
EDIT:
If you need to modify any current element you should to do this:
NodeList<Element> links = Document.get().getElementsByTagName("link");
for(int i = 0; i < links.getLength(); i++){
LinkElement l = (LinkElement)links.getItem(i);
if( l.toString().contains("href_to_replace.css") ){
l.setHref("new_href.css");
break;
}
}
You can access to the referrer in JavaScript and pass it to Java (rather to the JavaScript compiled from Java). You need to define a JSNI (JavaScript Native Method) method in Java with a JavaScript definition. This code can access the document and window objects of the browser, although you need to respectively use $doc and $wnd variables for that purpose.
More info at
https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsJSNI
You can get the full URL String like so:
String url = Document.get().getURL();
get the index of a question mark and parse it by yourself