3

I'm trying to get some basic Javascript and PHP working for a coding challenge I'm taking part in and I need to receive a JSON object from a PHP file to use in my Javascript that displays the current date on a HTML page. I've tried a few different methods and can't seem to get any to work, is there something I'm missing here?

I've tried using jQuery getJSON as well as running the PHP in the same HTML file as the Javascript.

This is the PHP file and its output:

echo json_encode([
    "date" => getthedate()
]);

function getthedate() {

    return date("Y/m/d");

}
{"date":"2019\/07\/04"}

This is what I've most recently been trying in Javascript:

function getDate() {

    var theDate = $.getJSON(
        "http://localhost/coding-challenge/get-date.php", 
        function(data)
    );

    JSON.parse(theDate);
    document.getElementsByClassName("date")[0].innerHTML = theDate;

}

I was expecting this Javascript to retrieve the JSON object that the PHP file echoes and then display it in the HTML file's "date" class, an empty paragraph. However this just results in a blank space where the date paragraph is.

Muowee
  • 54
  • 8
Mtaylor042
  • 31
  • 3

2 Answers2

1

$.getJSON is asynchronous, so you should set the data inside it's success callback:

function getDate() {
  $.getJSON("http://localhost/coding-challenge/get-date.php", data => {
    document.getElementsByClassName("date")[0].innerHTML = data;
  });
}
Kobe
  • 6,226
  • 1
  • 14
  • 35
  • Thanks, it looks like that's fixed the errors with the code but I'm still not getting the date on the page, looks like the JSON.parse isn't actually finding any data? – Mtaylor042 Jul 04 '19 at 12:40
  • @Mtaylor042 i just realised you're using getJSON, which i assume automatically calls JSON.parse on the response. – Kobe Jul 04 '19 at 12:42
  • Is getJSON definitely the right method to be using here, a lot of other examples on like are pointing getJSON towards a .json file, whilst this is a php file that uses json_encode and echoes the object? – Mtaylor042 Jul 04 '19 at 12:55
  • If it's encoded to JSON standards, then by all means use getJSON. It will automatically decode it for you on the frontend. As always, there is the builtin fetch api to use, which i prefer, but it's mostly down to personal preference and need. – Kobe Jul 04 '19 at 13:38
  • Still looks like there's no data being returned by the getJSON, I've tried adding the header suggested below as well. Tried using the fetch API but that doesn't seem to work either. – Mtaylor042 Jul 04 '19 at 16:58
0

Try to send the correct HTTP resonse header for JSON. Then jQuery will parse the response for you.

header('Content-Type: application/json');

echo json_encode([
    'date' => getthedate()
]);

function getthedate() {
    return date("Y/m/d");
}

JS

$.getJSON("http://localhost/coding-challenge/get-date.php", function( data ) {
    console.log(data);
    alert(data.date);
});
odan
  • 4,757
  • 5
  • 20
  • 49