Saint Robson
Saint Robson

Reputation: 5525

Ajax Successfully Receive Data From Server, But Failed Sending It

I have this ajax works fine :

$.ajax({
    url: "../../../controller/ctrl.test.php",
    success:function(expirytime){
        alert(expirytime);
    }
});

but when I need to send data to server and add this lines, then it won't alert the expirytime again :

$.ajax({
    url: "../../../controller/ctrl.test.php",
    type: 'POST',
    contentType:'application/json',
    data: JSON.stringify(data),
    dataType:'json',
    success:function(expirytime){
        alert(expirytime);
    }
});

please note that data is json data. and I have it on above those codes. so, it's not empty. I just wondering why by adding POST mechanism into my first ajax cause alert(expirytime); stop working?

what's wrong with my code? thank you

update : for this test purpose, there's nothing in PHP file, but just echo-ing date and time

<?php
$date = '2016/04/30 00:00:00';
echo $date;
?>

Upvotes: 0

Views: 52

Answers (2)

Barmar
Barmar

Reputation: 782653

Since you have dataType: 'json', jQuery expects the response from PHP to be valid JSON. But

echo $date;

is not returning valid JSON. When jQuery calls JSON.parse() on that response it gets an error, so the success function is not called.

Change that line to:

echo json_encode($date);

and it should work. Or change dataType: 'json' to dataType: 'text'.

Upvotes: 2

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

Try This

$.ajax({
    url: "../../../controller/ctrl.test.php",
    type: 'POST',
    data: { JSON.stringify(data) },
    dataType: 'json',
    success:function(expirytime){
        alert(expirytime);
    }
});

Upvotes: 1

Related Questions