AS3 using PHP to confirm background URL status - php

I'm creating an Adobe Air app for our members. Each time they open the app, I want it to quickly verify their membership status in the background before it allows them to use it. Unfortunately, I don't have access to the WordPress database that would tell me this valuable information.
Would it be possible to open a URL in the background (completely invisible to the user) that pings their member's only page on our site? Currently, if a non-member tries to access that page, it redirects them to a 404 error page. By loading it in the background, would there be a way for my app to tell if it was redirected to the 404 page or not?
That might be a horrible workaround, so any better ideas are completely welcomed.

You could write a server sided PHP script which will return "true" or "false" according to a userId:
http://yourdomain.com/isMember.php?userId=XXX
And then you could use the AS3 URLLoader class like so:
var urlRequest:URLRequest = new URLRequest("http://yourdomain.com/isMember.php?userId=" + userId);
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);
function urlLoader_complete(evt:Event):void {
if(urlLoader.data == "true")
{
trace("A valid member!");
}
else
{
trace("An invalid member!");
}
}

Related

Check if Facebook is blocked then redirect [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s the best way to check if a website is up or not via JavaScript
We're about to run a campaign through our Facebook page. Ideally we'd like to have the url we're using for this campaign (eg. www.oursite.com/campaign) redirect all traffic to our Facebook url (eg. www.facebook.com/example). However, many workplace networks block social media sites, so before automatically redirecting I'd like to first check if the user's network allows Facebook: if yes, redirect to Facebook; if no, continue through to our url (www.oursite.com/campaign).
Any help would be greatly appreciated,
Ryan
(I'm ok with PHP, newb to javascript )
Facebook SDK method
Since you need to check if the user has access to facebook you could try to initialize the the Facebook SDK and base your logic on that
According to documentation window.fbAsyncInit function is called on a successful initialization of the SDK, so you might achieve your effect with something like this:
var campaignLink = "http://www.oursite.com/campaign";
window.fbAsyncInit = function() {
// facebook sdk initialized, change link
campaignLink = "http://www.facebook.com/example";
}
Please note that this is all theoretical and untested, you might need to read more here
https://developers.facebook.com/docs/reference/javascript/
Favicon method
This function tries to load the favicon.ico file of the supplied URL and takes it as an indicator on whether the site is accessible (by the user) or not. It assumes that a site has a favicon, but you could easily change that to another image which you know exists.. (example the facebook logo)
function isSiteOnline(url,callback) {
// try to load favicon
var timer = setTimeout(function(){
// timeout after 5 seconds
callback(false);
},5000)
var img = document.createElement("img");
img.onload = function() {
clearTimeout(timer);
callback(true);
}
img.onerror = function() {
clearTimeout(timer);
callback(false);
}
img.src = url+"/favicon.ico";
}
Usage would be,
isSiteOnline("http://www.facebook.com",function(found){
if(found) {
// site is online
}
else {
// site is offline (or favicon not found, or server is too slow)
}
})

make dynamic webpage from html

I have a webpage that retrieves data (via ajax/php) and shows it in an html div (id='parent'). I'd like to add a print feature, which will take the contents of parent and show it in another page.
I've never made a dynamic webpage before. All the information I show is just pulled onto the main page via ajax. So I don't know where to begin really. I assume it has something to do with those long character strings I see in the urls of lots of internet sites, but I don't know! do I just use the url character string to store information about the current state of the page so the user can go back to what they were looking at with the back button. will the back button automatically work, or do i have to listen for it and reload the page based on what i pull from that string?
Very appreciative if someone can point me to some good articles or work out a little pattern of what steps I should take to
pull data from the page
put it on another page (or is it another page? do I just clear the page i'm on and re-fill it with other data??)
enable the back button to go back to the first page.
Thank you so much!
Those long character strings you are talking about sound like SessionIDs. The idea is that you store all the data you need to share between website requests on the server and identify the user by this ID to retreive the correct dataset when she requests the next website.
PHP already supports this out-of-the-box. The documentation of the PHP session handling functionality can be found here:
http://www.php.net/manual/en/book.session.php
To take data from ajax into another tag you can do something like this
<script>
var page_request = false;
function ajax_request(url)
{
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject)
{ // if IE
try
{
page_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
page_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
else
return false
page_request.open('GET', url);
page_request.send(null);
return page_request.responseText;
}
function ChangeDiv(id, url)
{
document.getElementById(id).innerHTML = ajax_request(url);
}
</script>
then just call ChangeDiv with the url you want (e.g 'http://website.com/page.php?params=1')

Calling Javascript Function In PHP Not Working

I'm new to Google Documents and have set up a spreadsheet that accesses the amount of "Likes" on three different Facebook pages. The code is part of the library on Google Documents but I'm trying to take the resulting total and pull it up on my site which is PHP. I'm starting simply with one site just because I can't get it working.
Here is the Javascript that was written to compile the likes:
function FacebookFans(aPageId)
{
if (aPageId === undefined || aPageId === null)
{
throw "No parameter specified. Write Facebook PageID as parameter."
}
if (typeof aPageId != "number")
throw "Parameter must be number.";
// See http://developers.facebook.com/docs/reference/fql/page/ for API documentation
var url = "http://api.facebook.com/method/fql.query?query=SELECT%20page_id,page_url,fan_count%20FROM%20page%20%20WHERE%20page_id=%22" + encodeURIComponent(aPageId) + "%22";
var response = UrlFetchApp.fetch(url);
if (response.getResponseCode() != 200)
throw "Unexpected response code from Facebook.";
var responseText = response.getContentText();
if (responseText == null || responseText == "")
throw "Empty response from Facebook.";
var fan_count = 0;
try
{
var xml = Xml.parse(responseText, false);
var page = xml.getElement().getElement();
if (page == null)
throw "Wrong PageID.";
fan_count = parseInt(page.getElement("fan_count").getText());
}
catch (e)
{
throw "Problem with response from Facebook: " + e;
}
return fan_count;
}
Now, to preface, I am very new at Javascript so don't kill me if my code is way off, I'm still trying to understand. I tried to run this in the body:
<script type="text/javascript">
document.write(FacebookFans(40796308305));
</script>
I figured the function returns a value and this would print that value out (the number btw is Coca Cola's Facebook page ID, figured it was a good one to test with). Is this a conflict between Javascript and PHP? I know that's a mixture of client-side and server side scripts. The reason I'm not sure what's wrong though is that I set a var inside the Javascript and then used to document.write to call it back just to test that my code was valid and it recalled the var fine. Anyways, any help is greatly appreciated. Thanks.
I used the Google Docs script debugger to step through your script.
The first arrow is what starts the script. In the dropdown for Select Function, choose the "doit" function I created (see bottom of screenshot). Finally, you can click where the second arrow is pointing and create a breakpoint, so the debugger stops.
After stepping through all of your code, you'll be glad to know it works just fine.
Your problem must be related to your understanding of how/when the code will be run. Note there is NO PHP in any of this code, so I'm not sure why you were asking about PHP.
You need certain "Actions" to run your scripts. You can read more about how scripts are run in Google docs. But your document.write doesn't apply here because you aren't writing a script for a webpage. You are inside the Google Docs environment.
If you want to run your script outside of Google Docs, you have a problem with the UrlFetchApp call, since that is a Google specific thing. If you load that script (and put it inside tags) in a .html doc, you can use Google Chrome to find out the errors. Select Wrench Icon->Tools->Javascript Console and it will show you the error right away. Now, normally you could just translate this to something else, but Javascript does its best to prevent you from making cross domain requests (learn more).
To translate this into server side code, it's pretty simple in PHP. You are basically just calling one url and then parsing it with XML. To load the contents of the url, use file_get_contents and then parse the xml.
If FacebookFans(40796308305) really works and returns result, so the problem is somehow in document.write.
Try:
<script type="text/javascript">
alert(FacebookFans(40796308305));
</script>
To be sure that the function works. And:
<script type="text/javascript">
var a=FacebookFans(40796308305);
document.write('a='+a);
</script>
To check the different types of issues.
If nothing helps, so we need more info, how do you invoke this function.

Ajax in bookmarklet :action done but answer not given

I'm trying to do my own bookmarklet and I already tried to read some response in SO but nothing to answer the weird reaction I got from my script.
I'm doing an AJAX call from my bookmarklet, so I do the little trick :
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.src = "http://example.com/urlToMyJS.js";
document.body.appendChild(newScript);
void(0);
And the urlToMyJS.js is like this :
var u = 'http://example.com/scriptToCall.php';
var request = new XMLHttpRequest();
request.open("GET", u, true);
request.onreadystatechange = function() {
var done = 4, ok = 200;
if (request.readyState == done && request.status == ok) {
if (request.responseText) {
alert(request.responseText);
}
}
};
request.send(null);
The weird part is :
The javascript is always launched and scriptToCall.php is always called too (it logs every hit)
The alert shows the responseText when I click on the bookmarklet on example.com
Sometimes, on other sites, the alert shows nothing (but still appears)
Some other times, the alert doesn't even show... (but I still have the log hit...)
Do you have any idea why it does that? And if yes, do you have any idea how I could make it always show the responseText?
status won't be ok unless you are testing the bookmarklet on your own site (example.com).
When you run the bookmarklet on a different site to example.com (which is after all the whole point of having a bookmarklet), it will be doing a cross-origin XMLHttpRequest to example.com. Depending on what browser you're using, that might do the request, but you won't be able to read the response due to the Same Origin Policy. It's an essential security feature that you can't make user-impersonating XMLHttpRequests to other servers.
If you want to make an XMLHttpRequest back to your server, you must do it from a document on your server, typically by having the bookmarklet create an <iframe> pointing to example.com.
Alternatively, use JSONP (<script> inclusion) to call scriptToCall.php.
Well, finally, I used another trick :
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.src = "http://example.com/scriptToCall.php";
document.body.appendChild(newScript);
void(0);
This way (the PHP is sending a javascript header), no more AJAX. It was nonsense in my case since both file were in the same server/folder, 1 movement instead of 2!
Anyway, thanks bobince for all the details I might use in the future !

Displaying POST Data with jQuery?

I'm using a flash webcam to take a picture. It works great and spits back a URL via POST.
I'm coding in PHP and would like to display this POST data once it is recieved, the problem is that I dont re-load the page.
I've looked around and I'm not sure to dynamically load this array of data.
Where should I be looking? jQuery?
Ah, Figured it out. The Flash thing I have has a built in callback function, so I just have to append the data from there!
jQuery is not able to read any sort of request data other than that which appears in the URL (GET). You will need to use PHP (or some other server-side language) to handle the response created by the FLash application.
Due to the fact that you're using Flash for the process you are at somewhat of a disadvantage because unless the Flash application has some sort of JavaScript "PhotoUploaded" event notification, your page won't be notified that Flash has just submitted a picture to your server which needs to be retrieved and inserted. If you can modify the Flash application to make an external JavaScript event then you can proceed as Frankie has described in his answer; otherwise, if modifying the Flash application is not an option, then another solution would be to have your page send a request to the server every so often (5-10 seconds or so maybe), to check if there is a photo for it to display yet.
The simplest way to setup polling with your server in this fashion would be to make sure that each photo upload from Flash has a unique, pre-determined identifier that your page knows at initial load. You would then simply ping your server every few seconds with an AJAX request and pass it that unique identifier in order to find the right image should one exist.
Basic example:
function GetPhoto() {
$.get('/getphoto.php?ID=1541XJ55A6', function(response) {
if(response.ImageUrl !== "") {
$(".profile-image").attr("src", response.ImageUrl);
if(getPhotoTimer !== undefined) {
clearInterval(getPhotoTimer);
}
}
});
}
$(document).ready(function() {
var getPhotoTimer = setInterval("GetPhoto()", 10000); // every 10 seconds
});
Flash calls javascript each time it spits back the URL.
Javascript contacts server (php) and gets content
Javascript injects content onto page
Like this (flex code):
// attach a function to the completeHandler
private function completeHandler(evt:Event):void {
javascriptComplete();
}
// declare the function that will call the javascript function
private function javascriptComplete():void {
var javascriptFunction:String = "galeryUploadComplete("+Application.application.parameters.opt+")";
ExternalInterface.call(javascriptFunction);
}

Categories