2017-04-20 02:10



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) {
function drawError(status) {
    console.log('Error: ' + status);
// handles the response, adds the html
function getRequest(url, success, error) {
    var req = false;
        // 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);
    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';
var urlRequest = getRequest(
    urlString, // URL for the PHP file 
    drawOutput,  // handle successful request 
    drawError    // handle error

Edit: Here's my HTML:

<!DOCTYPE html>
    <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>
    <div id="header">Hanabi Lobby<hr></div>
    <div id="body">
        <div id="info-row">
                <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>
        <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 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>
            <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 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>
    <div id="footer">Sweet game bro!</div>

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

header('Access-Control-Allow-Origin: *');
if(!isset($_GET["game_id"]) || !isset($_GET["client_timestamp"])){
        print(json_encode(array("error_code" => "1", "message" => "missing game_id or client_timestamp")));
$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")));

// 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);
    $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);
$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);

// 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 {
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • douwen3965 douwen3965 4年前

    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.

    点赞 评论 复制链接分享