William Sharp
William Sharp

Reputation: 55

PHP variable to JS variable using AJAX

I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.

<script>
    var mapCode;
    var used;
    var active;

    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                mapCode: $mapCode,
                used: $used,
                active: $active,
            },
            dataType: "text",
        }); 
    }
</script>
<?php
  ini_set('display_errors', 1); 
  error_reporting(E_ALL);
  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "database";

  // Create connection
  $conn = mysqli_connect($servername, $username, $password);
  mysqli_select_db($conn, $dbname);

  // Check connection
  if (!$conn) 
  {
    die("Connection failed: " . mysqli_connect_error());
  }
  // echo "Connected successfully";

  $query = "SELECT mapCode FROM mapCodes";
  $result = mysqli_query($conn, $query);
  $mapCode = mysqli_fetch_row($result);

  $query1 = "SELECT used FROM mapCodes";
  $result1 = mysqli_query($conn, $query1);
  $used = mysqli_fetch_row($result1);

  $query2 = "SELECT active FROM mapCodes";
  $result2 = mysqli_query($conn, $query2);
  $active = mysqli_fetch_row($result2);

  mysqli_close($conn);  
?>

I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working

Upvotes: 0

Views: 94

Answers (4)

Javed Sayyed
Javed Sayyed

Reputation: 149

If the file extension is .php and not .js then this should work

<script>
    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                mapCode: "<?php echo $mapCode; ?>",
                used: "<?php echo $used; ?>",
                active: "<?php echo $active; ?>",
            },
            dataType: "text",
        });
    }
</script>

If you have .js file then declare javascript variable before including your js in .php file

<script>
    var mapCode = "<?php echo $mapCode; ?>";
    var used = "<?php echo $used; ?>";
    var active = "<?php echo $active; ?>";
</script>

then in .js file you will get easily

<script>
    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                mapCode: mapCode,
                used: used,
                active: active,
            },
            dataType: "text",
        });
    }
</script>

Upvotes: 1

Ultrazz008
Ultrazz008

Reputation: 1688

How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:

<?php
  ini_set('display_errors', 1); 
  error_reporting(E_ALL);
  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "database";

  // Create connection
  $conn = mysqli_connect($servername, $username, $password);
  mysqli_select_db($conn, $dbname);

  // Check connection
  if (!$conn) 
  {
    die("Connection failed: " . mysqli_connect_error());
  }
  // echo "Connected successfully";

  $query = "SELECT mapCode FROM mapCodes";
  $result = mysqli_query($conn, $query);
  $mapCode = mysqli_fetch_row($result);

  $query1 = "SELECT used FROM mapCodes";
  $result1 = mysqli_query($conn, $query1);
  $used = mysqli_fetch_row($result1);

  $query2 = "SELECT active FROM mapCodes";
  $result2 = mysqli_query($conn, $query2);
  $active = mysqli_fetch_row($result2);

  mysqli_close($conn); 
  // Outputing results:
  echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>

Then in ajax, use success for listening return message after ajax finished:

<script>
    var mapCode;
    var used;
    var active;

    function downloadCode() {
        $.ajax({
            type: 'GET',
            url: 'getMapCode.php',
            data: {
                /** Your data to send to server **/
            },
            dataType: "text",
            success: function(data) { /** Here is data returned by php echo **/
                var temp = $.parseJSON(data);
                mapCode = temp['mapCode'];
                used = temp['used'];
                active = temp['active'];
            }
        }); 
    }
</script>

Upvotes: 0

Mac A.
Mac A.

Reputation: 103

My current project is actually dealing with lots of ajax calls, here is the simplified version of what I use to communicate with server:

// php
// needed functions
function JSONE(array $array)
{
    $json_str = json_encode( $array, JSON_NUMERIC_CHECK );
    if (json_last_error() == JSON_ERROR_NONE)
    {
        return $json_str;
    }
    throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
    if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
    header('Content-Type: application/json');
    print JSONE($array);
    exit();
}

// pack all data
$json_output = array(
    'mapCode'   => $mapCode,
    'used'      => $used,
    'active'    => $active
);

// output/exit
output_array_as_json( $json_output );


// javascript
function _fetch()
{
    return $.ajax({
        url: 'getMapCode.php', // url copied from yours
        type: 'POST',
        dataType: 'json',
        success: function(data, textStatus, req){
            console.log('server respond:', data);
            window.mydata = data;
        },
        error: function(req , textStatus, errorThrown){
            console.log("jqXHR["+textStatus+"]: "+errorThrown);
            console.log('jqXHR.data', req.responseText);
        }
    });
}

window.mydata = null;
_fetch();

I have not tested this, but let me know I'll fix it for you.

Upvotes: 0

Moys&#233;s Oliveira
Moys&#233;s Oliveira

Reputation: 21

You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag

Upvotes: 0

Related Questions