I have a heat map application on OpenLayers (using XAMPP 1.8.0 and MySQL) where user enters two date and time intervals and selects whether he/she would like to view all the data between those two datetimes or view them based on hourly/daily/weekly/monthly intervals. However, when I type in two date and times as input and try to visualize the data, I can only visualize all the data between those two intervals. Whenever I choose hourly, daily, weekly etc from my HTML drop down menu and press fetch queries button, I get an Error in Ajax POST message. What could be the cause here? The codes are below:

The HTML Post part:

$(document).ready(function(){

 // ajaxForm submission
 $('#ajaxForm').submit(function() {
  $.ajax({
   type: 'POST',
   url: 'heatQuery.php',
   //url: 'http://localhost/heatQuery.php',
   data: $(this).serialize(),
   dataType: 'json',
   success: function(response)
   {   
       // update the points for heatmap layer          
       updateHeatMap(response);

   },
   error: function(errorMsg)
   {
       alert(errorMsg);
       }


  });

  return false;
 });
});

The PHP Part:

setupDB.php

<?php

$mysql_hostname = "localhost";
$mysql_user = "myuser";
$mysql_password = "mypassword";
$mysql_database = "mydatabase";
$bd = mysql_connect($mysql_hostname, $mysql_user) or die("Oops some thing went wrong");
    mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");

?>

heatQuery.php

<?php
include 'setupDB.php';
$coords_array = array();

function getPoints($dateTimeBeg,$dateTimeEnd)
{
$ses_sql= "SELECT lat,lon FROM `mytable` WHERE calltime >= '$dateTimeBeg' AND calltime <= '$dateTimeEnd'";  
    $result = mysql_query($ses_sql,$bd) or die('Error: ' . mysql_error());
    if($result)
    {
        $num_of_rows = mysql_num_rows($result);
        if($num_of_rows > 0)
        {
            while($row = mysql_fetch_row($result))
            { 
                array_push($coords,array($row[0],$row[1]));     
            }
            array_push($coords_array,$coords);
        }
    }
}

$hours = array(1 => '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '24:00');

$dateBeg = isset($_POST['date1']) ? $_POST['date1'] : "";
$dateEnd = isset($_POST['date2']) ? $_POST['date2'] : "";
$dateFreq = isset($_POST['freq']) ? $_POST['freq'] : "";

if($dateBeg && $dateEnd && $dateFreq) // if all variables are set
{
    $datetime1 = new DateTime($dateBeg);
    $datetime2 = new DateTime($dateEnd);
    $interval = $datetime1->diff($datetime2,true);

    if($dateFreq == "all")
    {
        $coords = array();
        $timeBeg = $_POST['time1'];
        $timeEnd = $_POST['time2'];
        $sp = " ";
        $dateTimeBeg = $dateBeg.$sp.$timeBeg;
        $dateTimeEnd = $dateEnd.$sp.$timeEnd;
        $ses_sql= "SELECT lat,lon FROM `mytable` WHERE calltime >= '$dateTimeBeg' AND calltime <= '$dateTimeEnd'";  
    $result = mysql_query($ses_sql,$bd) or die('Error: ' . mysql_error());
    if($result)
    {
        $num_of_rows = mysql_num_rows($result);
        if($num_of_rows > 0)
        {
            while($row = mysql_fetch_row($result))
            { 
                array_push($coords,array($row[0],$row[1]));     
            }
            array_push($coords_array,$coords);
        }
    }

    }else if($dateFreq == "hourly")
    {       
        for($i=1;$i<=24;$i+=1)
        {
            $coords = array();
            $timeBeg = $hours[$i];
            $timeEnd = $hours[$i+1];
            $dateTimeBeg = $dateBeg.$sp.$timeBeg;
            $dateTimeEnd = $dateBeg.$sp.$timeEnd;
            $ses_sql= "SELECT lat,lon FROM `mytable` WHERE calltime >= '$dateTimeBeg' AND calltime <= '$dateTimeEnd'";  
    $result = mysql_query($ses_sql,$bd) or die('Error: ' . mysql_error());
    if($result)
    {
        $num_of_rows = mysql_num_rows($result);
        if($num_of_rows > 0)
        {
            while($row = mysql_fetch_row($result))
            { 
                array_push($coords,array($row[0],$row[1]));     
            }
            array_push($coords_array,$coords);
        }
    }

        }
    }else if($dateFreq == "daily")
    {
        for($i=1;$i<=interval;$i+=1)
        {
            $ses_sql= "SELECT lat,lon FROM `mytable` WHERE calltime >= '$dateTimeBeg' AND calltime <= '$dateTimeEnd'";  
    $result = mysql_query($ses_sql,$bd) or die('Error: ' . mysql_error());
    if($result)
    {
        $num_of_rows = mysql_num_rows($result);
        if($num_of_rows > 0)
        {
            while($row = mysql_fetch_row($result))
            { 
                array_push($coords,array($row[0],$row[1]));     
            }
            array_push($coords_array,$coords);
        }
    }
        }
    }

    $coords_json = json_encode($coords_array);
    echo $coords_json;

//echo $coords;

    mysql_close($bd);
}

?>

Dani AI

Generated

Short diagnosis and focused fixes for (building on ’s hint)

The Ajax callback is showing “[object XMLHttpRequest]” because the error handler is alerting the jqXHR object itself. More important: jQuery’s dataType: 'json' will force a JSON parse — any PHP warning/HTML before the JSON will make the request fail (parsererror) even if the server returned data. The Chrome Network tab and the response body are the first things to check.

Quick, practical checks

  • Inspect the XHR in DevTools → Network: note the HTTP status and the raw response text. If the response contains PHP notices or HTML, JSON parsing will fail.
  • Make the server explicitly return JSON and no other output: call header('Content-Type: application/json; charset=utf-8'); before echo json_encode(...), and disable display_errors in production so warnings don’t corrupt output.
  • Replace the current JS error handler with one that logs useful info:
error: function(jqXHR, textStatus, errorThrown) {
  console.log('AJAX error', textStatus, errorThrown);
  console.log('Status:', jqXHR.status);
  console.log('Response body:', jqXHR.responseText);
  alert('Request failed: ' + textStatus + ' (' + jqXHR.status + ')');
}

Bugs and logic problems in the PHP to fix

  • Undefined/incorrect variables: $sp is not initialized for all branches; $interval is a DateInterval object — use $interval->days or a DatePeriod to iterate days; the daily loop uses interval (undefined).
  • Scoping and globals: functions that use the DB connection must either accept the connection as a parameter or declare global $bd; arrays like $coords_array should be initialized in the same scope they are pushed.
  • Off‑by‑one in the hourly loop: accessing $hours[$i+1] will go out of range on the last iteration.
  • Performance & security: avoid running SELECT in a tight loop for each bucket. Add an index on calltime, use a single SELECT to fetch the range and then bucket results in PHP (or use DB grouping functions), and switch from deprecated mysql_* to mysqli or PDO with prepared statements to avoid injection.

Checklist summary

  1. Inspect Network/response text; 2) enforce JSON content-type and silence PHP warnings; 3) fix undefined variables/loops and scope; 4) reduce query count and add index on calltime; 5) migrate to mysqli/PDO and prepared queries.

Recommended Answers

All 7 Replies

I added the localhost8080 to the url for the php file and now I always get an error message -regardless of any selection including visualize all data-, though this message says [object XMLHttpRequest] as the error message. What could that be about?

No no, I mean you need to have a port number that your Server is listening to in that line. The port number 8080 is common used in Apache server in development environment. I do not know how you set up your server, so I gave you the most port number...

Well according to the httpd.conf file in the xampp/apache folder, it listens to port 80 but adding http://localhost:80 didn't solve the problem, still getting the same error I mentioned in my previous post. I ran out of ideas for this one..

Another weird thing is that the mysqld.exe process actually works for a while (consuming a 10-15 % of the CPU) before Chrome gives me the error.

If you get [object XMLHttpRequest], it means you get the respond back but you attempt to display the object... You need to either call .responseText or .responseXml from the ajax (xml) object you created.

I will look into it and post an update, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.