0

I get statusText: OK value, but I cannot get PHP object or array values. https://paste.fedoraproject.org/paste/1-HWWEJKvSbCYKUkoGHytA

I have Fedora 30 with 2.4.39 HTTPd, PHP 7.6, MySQL: 10.3.12. I'm using latest jQuery. I set it into my PHP file:

header('Content-type: application/json');
$.ajax({
  url: 'get.php',
  type: 'post',
  })
  .done(function(a) {
    $("#workSpace").html(a); 
    alert(a)
    $.each(a, function( key, value ) {
      $("#workSpace").html(key + ": " + value);
    });
   })
   .fail(function(a) {
        $("#workSpace").html(a); 
   })
   .always(function(a) {
        var example = Object.keys(a)

        $.each(example, function( key, value ) {
       $("#workSpace").html(key + ": " + value);
    });
    });
});

I expected work with objects or array passed by PHP like this.

{id:1, name: hola, description: That's an example}
{id:2, name: hello, description: That's nice}
{id:3, name: welcome, description: That's so way}

However, I just only get statusText: OK

sincorchetes
  • 351
  • 1
  • 4
  • 13

2 Answers2

0

you will not have many responses from your PHP in one request made, try to collect all the data received from your db in a variable. Modify your php code as follows.

header('Content-type: application/json');
$conn = new mysqli('localhost','root','example','tasks');
$stmt = $conn->query("SELECT * FROM task")->fetch_array();
$array = array();
while ($getResults = $stmt->fetch_array())
{
    $array[] = $getResults;
}

/* free result set */
mysqli_free_result($getResults);

/* close connection */
mysqli_close($conn);

echo json_encode($getResults);

Regards

Daniel Luna
  • 341
  • 2
  • 9
0

have you try something like this :

$array = array();
while ($getResults = $stmt->fetch_array())
{
    $array[] = $getResults;
}

echo json_encode($array);

and adding the content type on the $.ajax request :

  $.ajax({
    url: 'get.php',
    type: 'post',
    dataType: "json"
  })
          .done(function (a) {

            $("#workSpace").html(a);
            alert(a)
            $.each(a, function (key, value) {
              $("#workSpace").html(key + ": " + value);
            });
          })
          .fail(function (a) {
            $("#workSpace").html(a);
          })
          .always(function (a) {
            var example = Object.keys(a)

            $.each(example, function (key, value) {
              $("#workSpace").html(key + ": " + value);
            });
          });
Renziito
  • 78
  • 3