How to extract the values from a external PHP contents that outputs JSON using Ajax?

Report
Question

Please briefly explain why you feel this question should be reported .

Report Cancel

I wrote the PHP file that returns my server’s current time and date
http://cgbp.org/date.php with code

<?php 
  header('Content-Type: application/json');
  $timezone = date_default_timezone_set("Asia/Manila");
  $time = date("H:i:s A");
  $date = date("m-d-Y");    

  $datecontents = array(
    "time" => $time,
    "date" => $date
  );    

  echo json_encode($datecontents);

  $fp = fopen('dates.json', 'w');
  fwrite($fp, json_encode($datecontents));
  fclose($fp);
?> 

How do I get the time and date values via Ajax request and display them in div?
Below is current that isn’t working.

$.ajax({
dataType: 'json',
url: 'http://cgbp.org/date.php',
success: function (result) {
    var InternetDate = new Date(result.date);
    var monthNames = [
                      "January", "February", "March",
                      "April", "May", "June", "July",
                      "August", "September", "October",
                      "November", "December"
                      ];

    var weekday = new Array(7);
    weekday[0]=  "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";

    var dayofweek = weekday[InternetDate.getDay()]; 
    var day = InternetDate.getDate();
    var monthIndex = monthNames[InternetDate.getMonth()];
    var year = InternetDate.getFullYear();

    //document.getElementById('time').innerHTML = dayofweek +', '+ monthIndex +' '+ day +', '+ year;
    document.getElementById('time').innerHTML = result.datecontents;
    document.getElementById('curdate').value = result.date;
}});
solved 0
1 Answer 17 views 0

Answer ( 1 )

    0
    January 11, 2017 at 7:00 pm

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    result.datecontents is not set, use the commented line instead.

    Best answer

Leave an answer

Browse

What is the capital of Egypt ? ( Cairo )

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>