Invalid value for property <position> - javascript

I'm attempting to combine perl and Javascript to map IP address Lat/Long locations to a Google Map using the Google Maps API v3. What I'm getting back is in the marker, I'm getting the error: Uncaught Error: Invalid value for property <position>: 43.073052,-89.40123
My code is:
#!/usr/bin/perl -w
use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
use CGI::Session ( '-ip_match');
use SOAP::Lite;
use lib '/home/schreiber/perl5/lib/perl5';
use JSON qw(encode_json);
$session = CGI::Session->load();
$q = new CGI;
my $soap = SOAP::Lite
-> uri('http://v1.fraudlabs.com/')
-> proxy('http://v1.fraudlabs.com/ip2locationwebservice.asmx')
-> on_action(sub { join "/", "http://v1.fraudlabs.com", $_[1] });
$license = "<removed>";
#if($session->is_expired) {
# print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
# print "Your session has expired. Please login again.";
# print "<br/>Login";
#} elsif($session->is_empty) {
# print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
# print "You have not logged in";
#} else {
print $q->header(-cache_control=>"no-cache, no-store, must-revalidate");
open (IPF, "/home/access_log");
#incomingarray=<IPF>;
$i = 0;
foreach $pair(#incomingarray) {
($ip, $rest) = split(/ - - /, $pair);
$incomingarray[$i] = $ip;
chomp $ip;
$i++;
}
close (IPF);
my %hash = map { $_, 1 } #incomingarray;
my #distinctIP = keys %hash;
$j = 0;
my #iplocation;
foreach (#distinctIP) {
my $method = SOAP::Data->name('IP2Location')->attr({xmlns =>
'http://v1.fraudlabs.com/' });
my #params = SOAP::Data->name('inputdata' => \SOAP::Data->value(
SOAP::Data->name(IP=>$_),
SOAP::Data->name(LICENSE=>$license)
));
my $result = $soap->call($method => #params);
$lat = $result->valueof('//LATITUDE');
$long = $result->valueof('//LONGITUDE');
push(#iplocation, "$lat,$long");
}
my $json = encode_json(\#iplocation);
# print "Content-Type: text/html\n\n";
print '<html>
<head>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(44.49, -91.30),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(\'map_canvas\'),
myOptions);
var coord_data = new Array();
coord_data = '.$json.';
var marker;
for (var i = 1; i < coord_data.length; i++) {
console.log(coord_data[i]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(coord_data[i]),
map:map
});
marker.setMap(map);
}
}
function loadScript() {
var script = document.createElement(\'script\');
script.type = \'text/javascript\';
script.src = \'//maps.googleapis.com/maps/api/js?sensor=false&callback=initialize\';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map_canvas" style="width: 100%; height: 100%"></div>
</body>
</html>
';
#}
Any assistance would be greatly appreciated.

The problem is that when you assign the position here --
marker = new google.maps.Marker({
position:coord_data[i],
map:map
});
-- you give it a raw JSON object, but it's expecting a google.maps.LatLng object. You will want to assign it like this--
position: new google.maps.LatLng(coord_data[i].lon,coord_data[i].lat)
See here also for some good samples of the Gmaps API usage:
https://developers.google.com/maps/documentation/javascript/v2/examples/

Related

How can I add json data into an array that are comprised of lngs and lats?

I am beginner to programming. I am building a website that will retrieve longtitudes and latitudes from database.Then It will show points on google map then It will route between points. But I could't store json data in an array.I am getting different errors.
This is my code.
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['ajax'] ) ){
$dbhost = 'localhost';
$dbuser = 'id1111790_root';
$dbpwd = '12345678';
$dbname = 'id1111790_longlat';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$places=array();
$sql = 'select
`location_name` as \'name\',
`location_Latitude` as \'lat\',
`location_Longitude` as \'lng\'
from `maps`
limit 100';
$res = $db->query( $sql );
if( $res )
while( $rs=$res->fetch_object() )
$places[]=array( 'latitude'=>$rs->lat, 'longitude'=>$rs->lng, 'name'=>$rs->name );
$db->close();
header( 'Content-Type: application/json' );
echo json_encode( $places,JSON_FORCE_OBJECT );
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyAaWYmMhckn2kI5t-1bM9XkQsg0QxrozWc' type='text/javascript'></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var getacara=0;
var latLngs = [];
var bounds;
//var latLngs = [];
function load() {
directionsDisplay = new google.maps.DirectionsRenderer();
var center = new google.maps.LatLng(-33.9, 151.2);
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
setRoute();
directionsDisplay.setMap(map);
$.ajax({
url: document.location.href,/*'phpmobile/getlanglong.php'*/
data: { 'id': getacara, 'ajax':true },
dataType: 'json',
success: function( data, status ){
$.each( data, function( i,item ){
latLngs.push(new google.maps.LatLng(data[i].lat,data[i].lng));
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
function setRoute() {
var start = latLngs[0].lat + ',' + latLngs[0].lng;
var end = latLngs[latLngs.length - 1].lat + ',' + latLngs[latLngs.length - 1].lng;
var waypts = [];
for (var i = 1; i < latLngs.length - 1; i++) {
waypts.push({
location: latLngs[i].lat + ',' + latLngs[i].lng,
stopover: true
});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
document.addEventListener( 'DOMContentLoaded', load, false );
</script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas, #map_canvas {
height: 80%;
}
#media print {
html, body {
height: auto;
}
#map-canvas, #map_canvas {
height: 650px;
}
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
You told JSON_ENCODE to force everything to be an object so the arrays you created inside of $places will now be objects. Therefore process the data you receive as an object.
success: function( data, status ){
$.each( data, function( i,item ){
latLngs.push(
new google.maps.LatLng(item.lat,item.lng)
);
});
},
The error you're getting (Uncaught TypeError: Cannot read property 'lat' of undefined) points that you're not getting what you expect when you're trying to use the lat property.
Check if the data[i] variables have the right values in your $.ajax callback. If data is not there, it might mean you're not properly returning data from your PHP code, or that the database is not accessible, or that it was empty.
You're also accessing the lat property in setRoute(). Note that setRoute() gets executed before the data comes back from the server, so latLngs is still an empty array. The $.ajax callback will be executed at some point in the future, when your server responds (even if it's quick, for JavaScript, that is "later"). In the meantime, the rest of your JavaScript keeps executing, and setRoute() tries to read from latLngs[0] but latLngs doesn't have anything in it yet.
I recommend you read about JavaScript promises and deferred execution, it may help clear that confusion. You may also want to read about the JavaScript event loop, which will help you understand why some actions are kicked to be executed in the future.

Pass PHP variable to javascript to show location of IP on Google Maps [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here on the same page U am using the php code to return an ip of domain and I would like to pass this php $ip variable to the below javascript code, in the button tag. How can I pass this php $ip variable into the below javascript code.
Here is the php submit part, without google maps:
<form method="post" action="">
<input type="text" name="name">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit']))
{
$ip = gethostbyname($_POST['name']);
echo $ip;
}
?>
Here is the javascript code in this code: I would like to pass above php $ip variable
I would like to remove the input tag and button tag in this javascript code because their existing two input and submit button tags on the single page
My goal in this project is to lookup the location of the IP and show it on google maps.
<script type="text/javascript">
$(function(){
try{
IPMapper.initializeMap("map");
//IPMapper.addIPMarker("111.111.111.111");
} catch(e){
//handle error
}
});
</script>
<input id="ip" name="ip" type="text" />
<button onclick="IPMapper.addIPMarker($('#ip').val());">Geocode</button>
<div id="map" style="height: 500px;width:500px; ">
</div>
For reference: the IPMapper code in javascript
/*!
* IP Address geocoding API for Google Maps
* http://lab.abhinayrathore.com/ipmapper/
* Last Updated: June 13, 2012
*/
var IPMapper = {
map: null,
mapTypeId: google.maps.MapTypeId.ROADMAP,
latlngbound: null,
infowindow: null,
baseUrl: "http://freegeoip.net/json/",
initializeMap: function(mapId){
IPMapper.latlngbound = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(0, 0);
//set Map options
var mapOptions = {
zoom: 1,
center: latlng,
mapTypeId: IPMapper.mapTypeId
}
//init Map
IPMapper.map = new google.maps.Map(document.getElementById(mapId), mapOptions);
//init info window
IPMapper.infowindow = new google.maps.InfoWindow();
//info window close event
google.maps.event.addListener(IPMapper.infowindow, 'closeclick',
function() {
IPMapper.map.fitBounds(IPMapper.latlngbound);
IPMapper.map.panToBounds(IPMapper.latlngbound);
});
},
addIPArray: function(ipArray){
ipArray = IPMapper.uniqueArray(ipArray); //get unique array elements
//add Map Marker for each IP
for (var i = 0; i < ipArray.length; i++){
IPMapper.addIPMarker(ipArray[i]);
}
},
addIPMarker: function(ip){
ipRegex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
if($.trim(ip) != '' && ipRegex.test(ip)){ //validate IP Address format
var url = encodeURI(IPMapper.baseUrl + ip + "?callback=?"); //geocoding url
$.getJSON(url, function(data) { //get Geocoded JSONP data
if($.trim(data.latitude) != '' && data.latitude != '0' && !isNaN(data.latitude)){ //Geocoding successfull
var latitude = data.latitude;
var longitude = data.longitude;
var contentString = "";
$.each(data, function(key, val) {
contentString += '<b>' + key.toUpperCase().replace("_", " ") + ':</b> ' + val + '<br />';
});
var latlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({ //create Map Marker
map: IPMapper.map,
draggable: false,
position: latlng
});
IPMapper.placeIPMarker(marker, latlng, contentString); //place Marker on Map
} else {
IPMapper.logError('IP Address geocoding failed!');
$.error('IP Address geocoding failed!');
}
});
} else {
IPMapper.logError('Invalid IP Address!');
$.error('Invalid IP Address!');
}
},
placeIPMarker: function(marker, latlng, contentString){ //place Marker on Map
marker.setPosition(latlng);
google.maps.event.addListener(marker, 'click', function() {
IPMapper.getIPInfoWindowEvent(marker, contentString);
});
IPMapper.latlngbound.extend(latlng);
IPMapper.map.setCenter(IPMapper.latlngbound.getCenter());
IPMapper.map.fitBounds(IPMapper.latlngbound);
},
getIPInfoWindowEvent: function(marker, contentString){ //open Marker Info Window
IPMapper.infowindow.close()
IPMapper.infowindow.setContent(contentString);
IPMapper.infowindow.open(IPMapper.map, marker);
},
uniqueArray: function(inputArray){ //return unique elements from Array
var a = [];
for(var i=0; i<inputArray.length; i++) {
for(var j=i+1; j<inputArray.length; j++) {
if (inputArray[i] === inputArray[j]) j = ++i;
}
a.push(inputArray[i]);
}
return a;
},
logError: function(error){
if (typeof console == 'object') { console.error(error); }
}
}
Maybe...
<button onclick="IPMapper.addIPMarker($('<?php echo $ip ?>').val());">Geocode</button>
Not an expert on javascript
A better solution would be to add the data to the element and use an event listener.
<button data-ip-marker="<?= htmlspecialchars($ip) ?>">Geocode</button>
and in JavaScript
$(document).on('click', '[data-ip-marker]', function() {
var marker = $('#' + this.getAttribute('data-ip-marker'));
if (marker.length) {
IPMapper.addIPMarker(marker.val());
}
});

Refresh PHP that grabs Co-Ords for google maps API

I am using the google maps API to show the last position a form was submitted to my site. So I am pulling the lon and lat values from a php file as variables but I need the script to refresh every 5 seconds so that the maps marker updates without page reload.
Here is the google api script:
<script>
function initialize() {
var myLatlng = new google.maps.LatLng<?php
require($DOCUMENT_ROOT . "php_includes/mobile_loc.php");
?>;
var mapOptions = {
zoom: 15,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Last Scan'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And here is the php file:
<?php
include_once("php_includes/db_conx.php");
$sql = "SELECT * FROM patdub ORDER BY STR_TO_DATE(Timestamp, '%d/%m/%Y %H:%i:%s') DESC LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query);
$lon = $row['Lon'];
$lat = $row['Lat'];
echo "($lat, $lon)";
?>
Any ideas? I've tried different AJAX methods but just can't seem to figure it out!
Edit: The line of code below is basically the bit I need to refresh every 5 seconds but without any div tags or anything because that interferes with the google api script..
<?php require($DOCUMENT_ROOT . "php_includes/mobile_loc.php"); ?>;
You want to call load the file your PHP script is in, assuming that it is in it's own file, you would do that like so and you can then update your DOM using the return from the AJAX call.
You would wrap the AJAX call in a javascript loop such as setInterval() like this:
setInterval(function() {
$.ajax({
url: "php_script.php"
}).done(function(return) {
console.log(return);
});
, 5000);
To call it every 5 seconds.
To incorportate it with your Google function (I have no knowledge of google maps so this may not be 100% accurate):
<script>
function initialize(myLatlng) {
myLatlng = myLatlng || new google.maps.LatLng<?php require($DOCUMENT_ROOT . "php_includes/mobile_loc.php");?>;
var mapOptions = {
zoom: 15,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Last Scan'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
setInterval(function() {
$.ajax(function() {
url: 'php_script.php'
}.done(function(response) {
var latlong = response;
initialize(latLong)
});
}, 5000)
</script>

Passing a javascript variable to a php file that creates XML

I am new here but use thee forums daily, so please forgive any etiquette errors! My question is actually very similar to this post Dynamically update variables in external PHP XML generation script . I need to pass a user input from a js var to a php script to query a db to then create an XML. I can get the file to work hardcoded. The ajax call I am using works in that it will pass a var to php using $_get, but it cant seem to output an XML file if I then try to use the passed variable unless it is hardcoded; I have this file working perfeclty in another context with hardcoded sql query. I am not sure if the query is not being passed correctly in the get method or not? maybe the code will help explain my issue a little better.
downloadUrl("XML.php"+queryString, function(data){
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var type = markers[i].getAttribute("type");
var address = markers[i].getAttribute("address");
//var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + type + "</b> <br/>" + address;
var icon = "http://maps.google.com/mapfiles/kml/pal4/icon52.png";
var title = markers[i].getAttribute("address")+ ' Fatalities: ' +markers[i].getAttribute("deaths");
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon,
title: title
});
bindInfoWindow(marker, map, infoWindow, html);
}
});//downloadUrl
}//load
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
var type = document.getElementById('confType').value;
var queryString ="?type=" + type;
request.open('GET', "XML.php"+queryString, true);
var params='type='+type;
request.send(params);
}
function doNothing() {}
<?php
$type = $_GET['type'];
//$type='RiotsProtests';
//$type= mysql_real_escape_string($type);
require("phpsqlajax_dbinfo.php");
$query = "SELECT * FROM incident WHERE EVENT_TYPE = `$type`"; //<-------------||||||
$result = mysql_query($query);
if (!$result) {die('Invalid query: ' . mysql_error());}
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
header("Content-type: text/xml");
($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("type",$row['EVENT_TYPE']);
$newnode->setAttribute("address", $row['LOCATION']);
$newnode->setAttribute("lat", $row['LATITUDE']);
$newnode->setAttribute("lng", $row['LONGITUDE']);
$newnode->setAttribute("deaths", $row['FATALITIES']);
$newnode->setAttribute("actor1", $row['ACTOR1']);
$newnode->setAttribute("actor2", $row['ACTOR2']);
}
echo $dom->saveXML();
?>
I have tried putting in the queryString, using SESSION_vars, but nothing seems to work. Whenever i call the XML file, it doesnt seem to output anything, like the xml isnt properly getting populated. When i change the header to xml/plain, i get proper output from a hardcode query, but the xml process does not seem to like the variable. please help!!

Refresh google map markers from mysql

I can pull this information from my MySQL table and display what I need to but I would like some help on how to refresh this data every 5 seconds or so with the current code that I have.
There isn't much data to show, just like 5 or 8 markers at any given time. I have included my current code that I use to pull the data. I am sort of OK with PHP/MySQL but very new to Google Maps.
<script type='text/javascript'>
//This javascript will load when the page loads.
jQuery(document).ready( function($){
//Initialize the Google Maps
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
//Load the Map into the map_canvas div
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Initialize a variable that the auto-size the map to whatever you are plotting
var bounds = new google.maps.LatLngBounds();
//Initialize the encoded string
var encodedString;
//Initialize the array that will hold the contents of the split string
var stringArray = [];
//Get the value of the encoded string from the hidden input
encodedString = document.getElementById("encodedString").value;
//Split the encoded string into an array the separates each location
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
//Separate each field
addressDetails = stringArray[x].split("&&&");
//Load the lat, long data
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
var image = new google.maps.MarkerImage(addressDetails[3]);
//Create a new marker and info window
var marker = new google.maps.Marker({
map: map,
icon: image,
position: lat,
content: addressDetails[0]
});
//Pushing the markers into an array so that it's easier to manage them
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
//Initialize your first couple variables
$encodedString = ""; //This is the string that will hold all your location data
$x = 0; //This is a trigger to keep the string tidy
//Now we do a simple query to the database
// DB INFO CONNECTION IS HERE AND WORKS
$result = mysql_query("SELECT * FROM `ulocation` WHERE `ul_lat`!='' AND `ul_long`!='' AND `ul_onduty`='1'",$db1);
//Multiple rows are returned
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
//This is to keep an empty first or last line from forming, when the string is split
if ( $x == 0 )
{
$separator = "";
}
else
{
//Each row in the database is separated in the string by four *'s
$separator = "****";
}
$status='0';
$cadd = sql::getval('cal_address', 'call', "WHERE `cal_id`='$row[14]'");
$num = sql::getval('cal_num', 'call', "WHERE `cal_id`='$row[14]'");
$pcond = sql::getval('cal_pcond', 'call', "WHERE `cal_id`='$row[14]'");
$list="$num $cadd";
//Saving to the String, each variable is separated by three &'s
$encodedString = $encodedString.$separator.
"<table border=0 width='350' height='20' class='maincolm' cellpadding=0 cellspacing=0><td align=left valign=top><h2></h2></td><tr><td width=100%><font size=3 face=arial><p><b>".$row[2].
"</b>".
"<br>Address: $list".
"<br>Call Type: $pcond".
"<br><br>Lat: ".$row[5].
"<br>Long: ".$row[6].
"</td></table>".
"</p>&&&".$row[5]."&&&".$row[6]."&&&".$row[8]."&&&".$row[14];
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
<? echo "<body oncontextmenu=\"return false\" style=\"overflow: hidden; \" topmargin=0 leftmargin=0 rightmargin=0 bottommargin=0>";
<div id=\"map_canvas\"></div>
</body>
</html>";
?>
setInterval(function() {
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
// change the DOM with your new output info
}
});
}, 300000);
This will run an ajax call to any page you want, with any post data you want every 5 minutes.
FOR MORE CLARITY:
Let's say we have a PHP page called refreshComments.php that does this:
$result = mysql_query("SELECT * FROM `comments` WHERE `articleId` = $_POST['articleId']");
while($data = mysql_fetch_array($result)) {
$output[] = $data;
}
echo json_encode($output);
What this is doing is doing that simple query, and printing it out in a JSON object
In our Javascript, we have a page called scripts.js that does this:
setInterval(function() {
$.ajax({ url: 'refreshComments.php',
data: {articleId: '2'},
type: 'post',
success: function(output) {
// dynamically append new comments
console.log(output); // this just logs is
}
});
}, 300000);
What is this JS file doing? On an interval of 300000 milliseconds (or 5 minutes), it sends an ajax request to refreshComments.php. refreshComments.php responds with a JSON of our new data, and in the success() function, we use that new data.

Categories

Resources