Home > Enterprise >  Pass and use a PHP variable in a Javascript file with Ajax
Pass and use a PHP variable in a Javascript file with Ajax

Time:12-22

I have a PHP script in which I get the content of a query made into a Postgresql database :

<?php
require_once 'connection.php'; 
$query1 = pg_query("This_is_my_query");
$instruction = "[";
while ($row = pg_fetch_array($query1)) {
    $row1= $row['row1'];
    $row2= $row['row2'];
    $instruction .= "{name : '". $row1. "', y : ". $row2. "},";
}
$instruction .= "]";
echo $instruction;
?>

The echo $instruction gives :

[{name : 'Prestation', y : 1}]

Then I have a JS file in which I try to display and use the $instruction variable.
I use Ajax and my script is the one :

$.ajax({
    url : 'Path_To_Php_File_Is_OK', // requesting a PHP script
    dataType : 'json',
    type: "GET",
    async : false,
    success : function (data) { // data contains the PHP script output
       alert(data);
},
error: function(data) {             
    alert('error');
},
})

The result is that the success function is not called and I have the alert('error'). But when I use the dataType 'text' and not 'Json', the success function is ok and I have the alert(data).
How to explain that behaviour ? And how could I parse the PHP variable $instruction ?

Any help would ve very appreciated, thanks !

CodePudding user response:

  1. There is no need to create a json string manually. Just build up and array and encode it to json with json_encode()
  2. You have to set JSON content-type in the response headers
  3. Closing ?> tag is redundant and is not recommended to use (see PSR-12)

So eventually your code should look like this

<?php

require_once 'connection.php';

$query1 = pg_query("This_is_my_query");

$instructions = [];
while ($row = pg_fetch_array($query1)) {
    $row1 = $row['row1'];
    $row2 = $row['row2'];
    $instructions[] = ['name' => $row1, 'y' => $row2];
}

header('Content-Type: application/json; charset=utf-8');

echo json_encode($instructions);
  • Related