S.Al S.Al - 2 months ago 6
Javascript Question

Send fetchAll array via ajax

I have this method that retrieves a list of dates from my database.

function getdate($id) {
$select = $this->db->query("select * from dates where user_id= '$id' ");
$row = $select->fetchAll(PDO::FETCH_COLUMN);
return $row;
}


And I have a model file "load calendar.php" which calls the method getdate:

$dates = $user->getdate($id);
echo $dates;


I want to be able to store the array $dates in an array my js file:

$(document).ready(function() {
var dbdates = new Array();
$.ajax({
type: 'POST',
url: 'loadcalendar.php',
data: { dates:dates },
success: function(response) {
dbdates = response;
alert(dbdates);

}

});


However, when I alert dbdates, nothing comes out. My 'getdate' method works. I only need help with the Ajax call. Thank you in advance!

Answer

Analyze these statements here,

$dates = $user->getdate($id);
echo $dates;

getdate() method actually returns an array, and what you're trying to do with echo $dates; is, you're trying to convert an array to a string, which won't work.

Instead, json_encode the array and echo it, like this:

$dates = $user->getdate($id);
echo json_encode($dates);

Also, add dataType: 'json' setting in your AJAX request, like this:

$(document).ready(function() {
    var dbdates = new Array();
    $.ajax({
        type: 'POST',
        url: 'loadcalendar.php',
        data: { dates:dates },
        dataType: 'json',
        success: function(response) {
            dbdates = response;
            console.log(dbdates);
        }

    });
});
Comments