3

Very basically, I'm trying to set the value of a variable in one file based on the return value of a function in another file. This is then returned via AJAX, however, the AJAX always seems to indicate an error. Code below:

updateTurn.php

<?php
//This is called by AJAX
require_once('functions.php'); //include necessary file
$player = getCurrentTurn(); //call function 
echo $player;
?>

functions.php

...
function getCurrentTurn()
{
    //the query and connection function appropriately
    include_once("getConn.php");
    $query = $GLOBALS['conn']->prepare("SELECT turn FROM Game");
    $query->execute();
    $result=$query->fetch(PDO::FETCH_ASSOC);
    return $result['turn']; //return the result of the query
}
...

AJAX

function checkForTurnChange(){
    $.ajax({
        type:"GET",
        url:"updateTurn.php",
        async:true,
        cache:false,
        timeout:10000,
        success:function(data){
            alert(data);
        },
        //this is where AJAX is returning
        error: function(XMLHttpRequest, textStatus, errorThrown){
            alert(textStatus +": "+ errorThrown);
        }
    });//end AJAX
};//end function

The error is caused by the line $player = getCurrentTurn();. If I remove this and echo any string value then it works correctly. This is incredibly basic but I can't seem to see my error. All help appreciated.

EDIT: The AJAX calls error: which results in this alert :

AJAX error message

10
  • is the defination of getCurrentTurn() contained in a class in functions.php file? Commented Jun 5, 2015 at 9:34
  • @Sourabh no, the file simply contains functions only. As far as I can see, there is no need for me to instantiate any objects. Commented Jun 5, 2015 at 9:37
  • yes not need if you do not intend to do so, can post what is the response you are getting from your ajax call? Commented Jun 5, 2015 at 9:39
  • Edited to show AJAX response Commented Jun 5, 2015 at 9:46
  • are all the files in the same directory? You're error callback is being fired that points to an http error Commented Jun 5, 2015 at 9:52

1 Answer 1

1

Resolved:

Removed include("getConn.php"); from getCurrentTurn() within functions.php and relocated it to be available for the entire file, not just locally available for that function. Therefore, functions.php should be:

include("getConn.php");
...
function getCurrentTurn()
{
$query = $GLOBALS['conn']->prepare("SELECT turn FROM Game");
$query->execute();
$result=$query->fetch(PDO::FETCH_ASSOC);
return $result['turn'];
}
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.