0

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 !

2
  • 3
    You need to send a JSON header from the PHP I believe. You also should use json_encode rather than manual JSON creation. Commented Dec 20, 2021 at 15:59
  • 2
    Please do not create your own json string. Something will inevitably go wrong. Instead, build up an array or object and use json_encode Commented Dec 20, 2021 at 16:03

1 Answer 1

2
  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);
Sign up to request clarification or add additional context in comments.

1 Comment

Great that is working ! Thank you very much @Hast !!

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.