0

I'm trying to use XmlHttpRequest to run a php script from a javascript file. But for some reason, my code is only returning the php code as a string instead of actually running it.

The php runs perfectly fine if I run it alone from a global url, but it won't run from the javascript file, implying there's something wrong with my javascript request?

I'm running everything locally on Ubuntu with Apache and nodejs. I was directed to this link earlier: PHP code is not being executed, instead code shows on the page, but it seems Ubuntu does not have an httpd.conf file and uses an apache2.conf instead. I'm not sure what the difference is or how to mess with it without breaking it. Also, doesn't the above link only imply that it's php's fault? But my php file runs perfectly fine when accessed through a global url.

Here's the snippet of javascript that's supposed to call the php file:

function drawOutput(responseText) {
    console.log(responseText);
}
function drawError(status) {
    console.log('Error: ' + status);
}
// handles the response, adds the html
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        console.log("XML request failed.");
        return false;
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}
var urlString = '../tests/server_scripts/page_load.php' + encodeURIComponent('game_id') + '=0&' + encodeURIComponent('client_timestamp') + '=10';

//var urlString = "http://rpal.cs.cornell.edu/YH/public/tests/server_scripts/page_load.php?" + encodeURIComponent('game_id') + '=0&' + encodeURIComponent('client_timestamp') + '=10';
//var urlString = 'http://localhost/YH/WebHanabi/public/tests/server_scripts/page_load.php&' + encodeURIComponent('game_id') + '=0&' + encodeURIComponent('client_timestamp') + '=10';
console.log(urlString);
var urlRequest = getRequest(
    urlString, // URL for the PHP file 
    drawOutput,  // handle successful request 
    drawError    // handle error
);

Edit: Here's my HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Hanabi Lobby</title>
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="/js/classList.js"></script>
    <script src="/js/socket.io.js"></script>
    <script src="/js/bokeh.js"></script>
    <script src="/js/lobby.js"></script>
</head>
<body>
    <div id="header">Hanabi Lobby<hr></div>
    <div id="body">
        <div id="info-row">
            <ul>
                <li><span class="info-title">Name:</span><span class="editable" title="Click to edit"><span class="name editable-text">My Name</span><i class="fa fa-edit edit"></i></span></li>
                <li><span class="info-title">Room:</span><span class="room">My Room</span></li>
            </ul>
        </div>
        <div id="content">
            <div class="column">
                <div class="column-title">Rooms</div>
                <div class="column-container rooms">
                    <ul class="room-list">
                        <li class="joinable" x-room="room 1">room 1</li>
                        <li class="joinable" x-room="room 2">room 2</li>
                        <li class="selected-room" x-room="room 3">room 3</li>
                        <li class="joinable" x-room="room 4">room 4</li>
                    </ul>
                    <ul class="bottom-buttons">
                        <li id="new-room-button"><i class="fa fa-plus-circle" style="position: absolute; left: 10px; bottom: 5px;"></i> New Room</li>
                    </ul>
                </div>
            </div>
            <div class="column">
                <div class="column-title">Participants</div>
                <div class="column-container participants">
                    <ul class="clients-list">
                        <li class="ready">person 1</li>
                        <li class="not-ready">person 2</li>
                        <li class="ready">person 4</li>
                    </ul>
                    <ul class="bottom-buttons">
                        <li id="ready-button"><i class="icon fa fa-play-circle" style="position: absolute; left: 10px; bottom: 5px;"></i><span class="text">Ready</span></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <div id="footer">Sweet game bro!</div>
</body>
</html>

And here's the PHP file I'm trying to run from the javascript:

<?php
header('Access-Control-Allow-Origin: *');
include("connection.php");
//specific
if(!isset($_GET["game_id"]) || !isset($_GET["client_timestamp"])){
        print(json_encode(array("error_code" => "1", "message" => "missing game_id or client_timestamp")));
    return;
}
$game_id = $_GET["game_id"];
$client_timestamp = $_GET["client_timestamp"];
if(!is_numeric($game_id) || !is_numeric($client_timestamp)){
    print(json_encode(array("error_code" => "2", "message" => "game_id or client_timestamp malformed, integers only")));
    return;
}

// jsonp
$jsonp = false;
if (isset($_GET["callback"])) {
    $jsonp = true;
    $jsonp_methodname = $_GET["callback"];
}

//insert new id
$user_id = isset($_GET["user_id"]) ? $_GET["user_id"] : generateRandomString(40);
if(!isset($_GET["user_id"])){
    $st1 = $mysqli->prepare("INSERT INTO users (user_id, user_info) VALUES (?, ?)");
    $user_info = isset($_GET["user_info"]) ? $_GET["user_info"] : "";
    $st1->bind_param("ss", $user_id, $user_info);
    $st1->execute();
}
$st = $mysqli->prepare("INSERT INTO player_pageload_log (user_id, server_timestamp, game_id, version_id, session_id, client_timestamp, host_domain, referrer_host, referrer_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$server_timestamp = time();
$version_id = isset($_GET["version_id"]) ? $_GET["version_id"] : 1;
$session_id = isset($_GET["session_id"]) ? $_GET["session_id"] : generateRandomString(36);
$host_domain = $_SERVER["HTTP_HOST"];
$referrer_host = $_SERVER["HTTP_USER_AGENT"];
$referrer_ip = $_SERVER["REMOTE_ADDR"];
$st->bind_param('siiisisss', $user_id, $server_timestamp, $game_id, $version_id, $session_id, $client_timestamp, $host_domain, $referrer_host, $referrer_ip);
$st->execute();

// Return response as either json or jsonp if method wrapper (as GET param 'callback') was specified.
$json_response = json_encode(array("error_code" => "0", "message" => "success", "user_id" => $user_id, "session_id" => $session_id));
if ($jsonp) {
    print($jsonp_methodname . '(' . $json_response . ');');
}
else {
    print($json_response);
}
?>
Community
  • 1
  • 1
wheeeee
  • 1,046
  • 2
  • 14
  • 33
  • Are you running the script from the filesystem or from the server, is it something like `file:///var/www/html/index.html`? – Marcos Casagrande Apr 20 '17 at 02:16
  • and if it's not `file:///` but indeed as `http://localhost`, then look at your js console. – Funk Forty Niner Apr 20 '17 at 02:18
  • Looking at another previous question of yours http://stackoverflow.com/q/43421794/1415724 you state that you tried `//InsertAbsolutePathHere/tests/my_file.php` and `file:///InsertAbsolutePathHere/tests/my_file.php` - the problem is clear thoughout all your past questions. – Funk Forty Niner Apr 20 '17 at 02:21
  • Do you have COORS access to that PHP page? – StackSlave Apr 20 '17 at 02:23
  • @Fred-ii-, do you mean the value for my variable urlString in the code above? You can see all the ones I've tried. It seems that both the ones that start with http end up giving me an error "No Access-Control-Allow-Origin header", so I was hoping to avoid it by using the relative path with ".../tests/page_load.php", but that's the one that dumps the text into my console. – wheeeee Apr 20 '17 at 03:17
  • @PHPglue So I tried sticking "header('Access-Control-Allow-Origin: *');" at the very beginning of my php file, second line after " – wheeeee Apr 20 '17 at 03:24
  • Include your HTML and PHP. – StackSlave Apr 20 '17 at 07:02
  • @PHPglue I've edited the post to add my HTML and PHP. (I hope that's what you were asking for?) – wheeeee Apr 20 '17 at 14:19
  • Definitely has to do with your Server. If it's not translating `.php` files then it would just give you the String. Oh, you don't need that COORS access if your JavaScript and PHP are in the same domain. – StackSlave Apr 21 '17 at 09:33
  • So I've tried using the http:// localhost/... version, but it keeps giving me a "no 'Access-Control-Allow-Origin' header is present on the requested resource". I believe I do need the headers in this case? But it seems they aren't working the way I'm using them. – wheeeee Apr 21 '17 at 18:50

1 Answers1

0

I'm assumning the javascript file is running locally?

Then the problem is because PHP needs to run through apache and the PHP engine before you can display it. What your code is actually doing is going to the backend, opening a file with the .php extension and reading that file. Instead of using an absolute file path, try using a URL.

  • By url, do you mean something like "var urlString = "http://rpal.cs.cornell.edu/YH/public/tests..." (whole thing was too long to put here)? – wheeeee Apr 20 '17 at 03:13
  • Sure, that works. But you'll need "http://" on the front. Here's the thing, PHP is just plaintext. It's not shell code like a compiled file. You cannot execute raw PHP. It has to run through an interpreter. Apache is configured to use the PHP interpreter when a user accesses a .php file. Outside of apache, if you're trying to just grab the file and read it, you'll end up doing just that: reading it. An alternative is to execute a shell command "php myphpfile.php" – Andrew Pearson Apr 20 '17 at 03:16
  • I'm sorry, I didn't quite understand that explanation. I'm very new to backend and everything. I'm not entirely sure how Apache works. All I know is that there's a set of files somewhere that collectively make up this Apache, and without it, php doesn't run. But why will php run normally when I open the file in my browser, but not when I call it from javascript? Is it just because the file I'm calling it from starts with .js and not .php, so Apache can't find it? – wheeeee Apr 20 '17 at 03:21
  • PHP is just a text file, you can read it with notepad. It's not executable code. When you open it like you're doing, it's no different than opening it in a text editor. PHP needs to run through what is called an "interpreter". What this does, is it converts PHP code into executable code _at runtime_. This is important to know. PHP isn't executable until it runs through the interpreter. Apache knows which interpreter to use. If you are bypassing apache, which you are doing, then your PHP is just a pain ol run of the mill text file. – Andrew Pearson Apr 20 '17 at 19:03
  • Thanks! So now I'm getting a "no 'Access-Control-Allow-Origin' header is present on the requested resource". Would you happen to know how to fix that? I'm assuming this means I need the CORS headers thing in the php file, but you can see where I've tried that, and it's still giving me the same error. – wheeeee Apr 21 '17 at 00:54