GET HttpRequest not working on HTML5 target?

Monkey Targets Forums/HTML5/GET HttpRequest not working on HTML5 target?

sjohne(Posted 2014) [#1]
Hey everyone,

I am using MonkeyX77A (the free demo version). I created a local webserver (Apache/XAMPP) and created a .php test file.

echo "Hello ".$_GET['name']."!";


Then I took the example code from the HttpRequest module documentation and changed only the web address to my local webserver.

Import mojo
Import brl.httprequest

Function Main()
	New Game
End

Class Game Extends App Implements IOnHttpRequestComplete

	Field req:HttpRequest
	
	Method OnHttpRequestComplete:Void(req:HttpRequest)
    
        Print "Http GET complete!"
        Print "Status="+req.Status()
        Print "ResponseText="+req.ResponseText()
        
    End

	Method OnCreate()
	
		SetUpdateRate 60
		
		req=New HttpRequest("GET","http://localhost/merchantsim/test.php?name=Stefan",Self)
        req.Send()
	
	End
	
	Method OnUpdate()
	
		UpdateAsyncEvents
	
		If KeyHit(KEY_ESCAPE) Then EndApp()
	
	End
	
	Method OnRender()
	
		Cls
		
		DrawText "Http GET bytes received="+req.BytesReceived(),0,0
	
	End

End


The problem is: If I use the Desktop target everything goes fine.

Http GET complete!
Status=200
ResponseText=Hello Stefan!


But when using the HTML5 target (which is the primary target I am want to develop for) I get an empty response:

Http GET complete!
Status=0
ResponseText=


I tried this with different web addresses and also the example from bananas/mak. Everything works fine on the Desktop target but as soon as I try with HTML5 I get no response text. The same goes for POST. Desktop target processes everything fine, HTML5 only shows empty response text.

Does anybody have an idea where the problem could be?


Midimaster(Posted 2014) [#2]
Do not use the monkey build in server and do not start the app by pressing F5 in monkey.

Install Xampp and copy your project folder "myApp" to the "C:\xampp\htdocs\" folder.

Inside monkey open "C:\xampp\htdocs\myApp\myApp.monkey" and edit/write it as used before. Compile the project by pressing F7

Start Xampp as a apache server. Open a browser with adress "http://localhost/MyApp/MyApp.build/html5/MonkeyGame.html"

Search for keyword XAMPP here in forum and you will find some post exactly about this problem


nikoniko(Posted 2014) [#3]
sjohne wrote:
Does anybody have an idea where the problem could be?


It may be security if you did crossdomain request..

Try request to the same domain, port, subdomain, don't load MonkeyGame.html from filesystem, via webserver only.


sjohne(Posted 2014) [#4]
Ai caramba! I already had it set up like Midimaster suggested... but opened the MonkeyGame.html via double click and not by going to localhost/... grr!

Thanks for the fast and useful help guys :-)...

Here the step by step solution if anybody else ever finds this topic:

1. After installing xampp make sure your monkey project files (projectname.monkey and projectname.build) are inside the ...xampp/htdocs folder. They can be inside a sub-directory but must be reachable by typing "localhost" in your browser address bar.

2.Compile your project by pressing F7. You can also "run" it as usual and then discard the open window.

3. Open the MonkeyGame.html created by the compiler in your webbrowser, but make sure that you use the path of your webserver. In most cases this will be:

http://localhost/subdirectory/projectname.build/html5/MonkeyGame.html


If you are unsure about the path just type "localhost" into your browser address bar and click through the directories until you find the MonkeyGame.html. If your "localhost" shows only a XAMPP page you have to delete .../xampp/htdocs/index.html.

Monkey rocks!


Prime_8(Posted 2014) [#5]
I got the same . with HTML5 .
soon as i put my PHP on my remote host / domain , it seemed to be able to POST & GET to the PHP server , but nothing is coming back.

as long as game & php target are on same domain it's all fine .
wonder if there is a way around that ?


sjohne(Posted 2014) [#6]
Hey Prime_8 do you mean your PHP files are on an actual server you try to address via a real domain? But you are calling the Monkey HTML file locally or from a different URL? If so you probably need to enable "Cross-Site XMLHttpRequests". See here: http://harthur.wordpress.com/2009/10/15/configure-apache-to-accept-cross-site-xmlhttprequests-on-ubuntu/

You can't call a PHP file from a different server/domain with Javascript (that's what Monkey is using) in the Apache standard config.


Prime_8(Posted 2014) [#7]
man your are quick . .yeah they needed to me both on my local server , or both on my www domain server .
I will see about enable "Cross-Site XMLHttpRequests".


Prime_8(Posted 2014) [#8]
nuts , im testing with uniform server on my win 7 laptop. LOL
I cant find that setting in my php.ini


Sensei(Posted 2014) [#9]
I added this snippet to the top of my PHP page which allowed the script on my VPS to return response.text to the game:

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");



Prime_8(Posted 2014) [#10]
nice , the origin of * , is there any security risks we should check on that as it open cross domain requests ?
for me i just had to add a sub domain vs the * , but i have not gotten arround to it . but * is obviously every origin .

hmm searched and found a snip and edited it to work hand for my Uniform Server Zero server to play nice with teh one Monkey X launches apps with on build.l

$http_origin = $_SERVER['HTTP_ORIGIN'];
// is it form some local server on diff port , or a specific domain ?
// if so simply allow iy by setting the Access-Control-Allow-Originto the incomming $http_origin
if ( preg_match( "/localhost:/i", $http_origin) || $http_origin == "http://www.domain2.com")
{  
    header("Access-Control-Allow-Origin: $http_origin");
}

edit as you need .
This way the PHP script works on my laptop or remote server .


Sensei(Posted 2014) [#11]
I had a further thought about the access control origin being allowed from * (all), and i'd like to know what you guys think as it's somethign I'm currently implementing in Spacewhale.
The game sends your highscore to the server, and the server currently returns the leaderboard highscore and displays it on your game over screen.
However, to ensure the request to the server URL comes only from the game and not other nefarious sources, could I not hardcode a key in the game and send that as an "authentication" to the PHP script and only upon verifying it being valid, will it set a PHP session and thereby allow the game to further communicate with the server?


Prime_8(Posted 2014) [#12]
[qote]"could I not hardcode a key in the game and send that as an "authentication" to the PHP script and only upon verifying it being valid, will it set a PHP session and thereby allow the game to further communicate with the server?"[/qote]

you bet .. you have some ways , tag the key as a var in the URI , but if you do try using POST no GET , POST can do just about everything GET can , but post is hidden / not retained , so slightly harder to intercept .
GET's can persist from page to page .

i am just messing and learning monkey x (coming from MinGW C/C++) , i i use something like this:
Class MyPHPinfo
	Field baseURL:String = "loopback:80"
	Field key:String = "app7894561230" ' some big stupid key , possibly even hash it 
	Field refreshTime:Int = 5000 ' my app looks for data every few seconds. 
	Field lastSendTime:Int = 0  
	Field isBusy:Bool = False
	
	Method New()
		baseURL = "loopback:80"
		refreshTime = 5000
		lastSendTime = 0
	End
	Method New(_baseURL:String, _refreshTime:Int = 5000)
		baseURL = _baseURL
		refreshTime = _refreshTime
		lastSendTime = 0		
	End	
End


PHP
<?php
header("HTTP/1.0 888 Fun Stuff"); // sets return status to custom # as you like. 
// i use 888 to tell my app/exe's that they reaches one of my PHP pages . 
header("Server: "); // scrub server info from return header to client / app they dont need to know it 
header("X-Powerd-By: ");
header('content-type: text/html; charset=utf-8'); // set as you need this is PHP default stype 
//header("access-control-allow-origin: *"); // << um no unless you must 
 
$http_origin = $_SERVER["HTTP_ORIGIN"];
   
$rawdata = file_get_contents('php://input');
// echo "Debug: This is the message content :>" . htmlspecialchars($rawdata) ."<:". PHP_EOL ;
// $rawdata  is not the vars in the URI , but what may have been 'posted'
 

function curPageURL(){
 $pageURL = 'http';
 if($_SERVER["HTTPS"] == "on") { $pageURL .= "s";}
 $pageURL .= "://";
 if($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"] ;
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] ;
 }
 return $pageURL;
}
// returns whole URL

function curPageName(){
 return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
// just the page name 

function curPageQUERY(){
 $url = curPageURL();
 return  parse_url($url , PHP_URL_QUERY);
} 
// current page args/vars  stuff after the '?' in URI , handy if POST data is lost on your server 
 
$str = curPageQUERY();
parse_str($str); 
 

if ($_SERVER["REQUEST_METHOD"] == "POST")
{ // do stuff if request was of a POST 
   // your PHP server may clear the post global too quick . 
   // so see fucntions below to get the post VARS 

if ($key != "key7894561230" )
{ die("bad key"); } // if not our key , you are not worth processing further . 

// for origin management only if a incomming key was cool  
// still specific filters exist for subdomains and ports .
//header("access-control-allow-origin: *"); << wide open
// filterd access control   , see if allowable domains , or parts of dmains exist in the $http_origin string
// if yes then set the allow to this $http_origin .
if( preg_match( "/localhost/i" ,  $http_origin ) || preg_match( "/yourdomain.com/i" ,  $http_origin ) )
{	// there can be no echo calls before this header or it wont work and could throw a PHP  error  
	header("access-control-allow-origin: $http_origin");
	echo "Debug: yep:"; // safe to echo now. 
} else { echo  $http_origin . PHP_EOL ;
die(" bad origin "  ); } // if not , not worth processing below .

?>


my PHP is rusty , and that could be all wrong way to do what it does . LOL