Skip to content
Advertisement

Cannot use Json data from ajax response text [closed]

I am working with javascript to fetch data from a database using ajax. The response text is as follows:

{"task":"r","category":"s","duration":"0"}{"task":"read","category":"s","duration":"10"}{"task":"read","category":"o","duration":"10"}

I used json_encode($data) on the php script which fetches the data from the MySql database. How do I store the task, category and duration of the response text in separate variables. I cannot use the response obtained. Here is the code:

 if (mysqli_query($conn,$query)){
    $result = mysqli_query($conn,$query);
    $tasks = mysqli_fetch_all($result,MYSQLI_ASSOC);
    foreach($tasks as $task){
        echo json_encode($task);
    }
    mysqli_free_result($result);
}

 get(url){
    let xhr = new XMLHttpRequest();
    xhr.open('GET',url,true)
    xhr.onload= function(){
        if (this.status===200){
            let data = this.responseText;
            console.log(data);
        }
    }
    xhr.send();
}

Advertisement

Answer

Try to declare the type of data received type with dataType : “json”

Like this:

$.ajax({
       type: "POST",
       url:"php/page.php",
       dataType:"json",
       success: function(data)
         {
            console.log(data);
         },
       error:function (data) {
             console.log("Error"+data)}
  });

Also your data should be a single json array and not a multiple json object

Try this:

$array = new Array();

$ c = 0;

while(condition){
  $array[$c] = your_c_object
  $c++;
}

echo json_encode($array);

You should have a output like this on console.log

[{"task":"r","category":"s","duration":"0"}, 
{"task":"read","category":"s","duration":"10"}, 
{"task":"read","category":"o","duration":"10"}]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement