Ajax post returns multiple arrays with objects that have multiple values

So I have a php file that gets messages from a database (ajax.php) and a javascript file that makes ajax request to that ajax.php file (main.js).

What I want: When the php is responding multiple times, the js file would make a table row for every one of them.

main.js:

function doAjax(variable) {
    $.ajax({
        type: "POST",
        url: "ajax.php"
        data: { content: variable },
        dataType: 'JSON',            
        success: function (response) {
            response.forEach(function(data) {
              $(".messages-table").append("<tr><th>"+from+"</th><th>"+text+"</th><th>"+date+"</th><th>"+num+"</th></tr>")
            })
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
        }
    });
}

ajax.php:

<?php

...

foreach ($messages as $message) {
    $from = $message['contact_value'];
    $text = $message['message'];
    $date = $message['date'];
    $num = $user['phone_number'];
    echo json_encode(array("from"=>"$from", "text"=>"$text", "date"=>"$date", "num"=>"$num"));
?>

But when i do that I get this error in developer console:

parsererror SyntaxError: Unexpected token < in JSON at position 0
    at parse (<anonymous>)
    at Qb (jquery.min.js:4)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

Cheers

1 answer

  • answered 2018-01-13 18:03 sanjun dev

    Your ajax.php should be like this

    <?php
    
      ...
    
      foreach ($messages as $message) {
        $from = $message['contact_value'];
        $text = $message['message'];
        $date = $message['date'];
        $num = $user['phone_number'];
        echo json_encode(array("from"=>$from, "text"=>$text,"date"=>$date,"num"=>$num));
    ?>
    

    if you really want the quotes then use ' ' (singlequotes) instead.

    And the javascript file.

     success: function (response) {
      var success = $.parseJSON(response);
      $(".messages-table").append("<tr><th>"+success.from+"</th><th>"+success.text+"</th><th>"+success.date+"</th><th>"+success.num+"</th></tr>");
    }
    

    i think you don't need to use the forech loop if you call the doAjax function every time.