I'm newbie to Ajax, I know when I want to pass data to PHP file I need to use Ajax, but I not sure the Ajax can use like what I coded. If can't, anybody can help me on this? Cause I want to use the html5 geolocation to get the user location. I tried geoplugin before but the IP I get always is the server IP not the user IP, I got try to ask here for the geoplugin but no work. I have tried this html5 geolocation to display my lon and lat, it is correct one, but I want to pass the variable to another PHP file for calculate the nearest distance with data get from MySQL.
In index.php
<script>
$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation);
} else {
$('#location').html('Geolocation is not supported by this browser.');
}
});
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
type:'POST',
url:'index1.php',
data:'latitude='+latitude+'&longitude='+longitude
}
});
}
</script>
In index1.php
<?php
session_start();
$link=mysqli_connect("localhost","id2135226_ukwai1203","ukwai1203");
mysqli_select_db($link,"id2135226_demo");
$lat=$_POST['latitude'];
$lon=$_POST['longitude'];
$sql = "select branch_id,(6371 * 2 * ASIN(SQRT( POWER(SIN(($lat -
branch_lat)*pi()/180/2),2)+COS($lat*pi()/180
)*COS(branch_lat*pi()/180)*POWER(SIN(($lon-branch_lon)*pi()/180/2),2))))
as
distance From Branch ORDER BY distance ASC LIMIT 1";
$res=mysqli_query($link,$sql);
while($row=mysqli_fetch_array($res)){
$_SESSION['location']=$row['branch_id'];
?>
<script>
window.location="http://ukwai1203.000webhostapp.com/fyp/user/shop.php";
</script>
<?php
}
?>
change your code to this:
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
method:"POST",
url:"index1.php",
data:{
latitude : latitude,
longitude : longitude
}
});//ajax end
}//function end
Consider using IDE like eclipse to help you spot missing brackets etc.
And when working by modifying old code check libraries versions like jquery version.
Related
I'm using mapbox api to display maps and directions. It's easy and it works well. I want to know how to update a marker's location on the map without refreshing a page. I read this page and this page in their documentation. I understand their examples but I'm not fully grasping how to implement realtime data in my codes without causing the page to refresh. Right now I have a script that updates the user location in the database every 15 seconds and returns longitude, latitude. I have the data now what? This is where I get highly confused. If you can help I would really appreciate. I have stripped down the codes for the sake of this question.
map.html
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.css" rel="stylesheet" />
<script type="text/javascript" src="geolocation.js"></script>
<!--Display map-->
<div id="map"></div>
<!--mapbox script-->
<script>
mapboxgl.accessToken ='pk.xxxxxxxx';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center:[$longitude,$latitude],
zoom: 15
});
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates:[$longitude,$latitude]
},
properties: {
title: '',
description: ''
}}]
};
geojson.features.forEach(function(marker) {
var el = document.createElement('div');
el.className = 'marker';
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup({ offset: 25 })
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
});
</script>
geolocation.js
setInterval(function () {
$.get("https://ipinfo.io", function (response) {
//variables
var user_id = $('.userid').val();
var geoLocation = response.loc;
//build array
var values ='geoLocation=' + encodeURIComponent(geoLocation)
+ '&userid=' + encodeURIComponent(user_id);
$.ajax({
type: 'POST',
url: 'https://mywebsite.com/mobile/geolocation.php',
data: values,
success: function (data) {
//returns new longitude
var lon = data.longitude;
//returns new latitude
var lat = data.latitude;
}
});
}, "jsonp");
}, 15000);
geolocation.php
$geoLocation= mysqli_real_escape_string($conn,$_POST['geoLocation']);//coordinates
$userid= mysqli_real_escape_string($conn,$_POST['userid']);//userid
//split coordinates into lat and longitude
$longitude = substr($geoLocation, strpos($geoLocation, ",") + 1); //put it first
$latitude =preg_replace('/^([^,]*).*$/', '$1', $geoLocation); // put it second
//insert new coordinates
$insertgeo = $conn->prepare("INSERT INTO user_geolocation (latitude,longitude,userid) VALUES(?,?,?)");
$insertgeo->bind_param("sss",$latitude,$longitude,$userid);
$insertgeo->execute();
$insertgeo->close();
//return answer to json
$result = array('message' => 'success',
'userid'=>$userid,
'longitude'=>$longitude,
'latitude'=>$latitude);
header('Content-Type: application/json');
echo json_encode($result);
The documentation resources you've linked are helpful, but I think this add live realtime data example is even better for your use case. If you zoom out of the map to see a larger region of the world, you will see a blue rocket icon marker which moves every two seconds without refreshing the page. In essence, this is exactly what you're looking to do! I'll explain how the example is working so that you can use the same logic to update your own marker locations without refreshing the page as well.
The rocket icon in this example is added to the map with a source and layer. The source specifies all the underlying data (in this case, the updating GeoJSON served by the https://wanderdrone.appspot.com URL), and the layer specifies how that data should be styled on the map. If you visit this URL, you'll see that the coordinates update each time you refresh the page.
So, the code below:
Gets the GeoJSON from the url every 2 seconds.
Gets the map's 'drone' source using Map#getSource.
Sets the data used by the source in (2) to be the GeoJSON at the url using Map#setData.
window.setInterval(function() {
map.getSource('drone').setData(url);
}, 2000);
Your current implementation is using HTML-based markers via GL JS's Marker component. So, instead of switching to this source-and-layer based approach outlined above, you could use the Marker#setLngLat method each time the user's location updates in your database. This also will not refresh the whole page.
I have a map that when clicked, the latitude and logitude populate some hidden text fields in a form. What I'd like to do is perform some calculations on these coordinates (find the nearest town), populate the 'Townland' field in the form with the name of the town, then submit everything on clicking submit.
I've been trying to do this by using ajax to send the contents of the lat and lng fields to a php file that does the processing, but I can't get it to work. The sql query works when I manually enter latitudes and logitudes instead of trying to pull them from the other file.
Any help would be great, thank you!
The javascript in my php form page to call the php file that does the calculations
<script type="text/javascript">
$('lat').change(function(){
var lat=document.getElementById('lat').value;
var lng=document.getElementById('lng').value;
$.ajax
({
url: '../Controller/PRACTICEtown.php',
data: { var : lat, var : lng},
type: 'post',
success: function(result)
{
$('#Townland').value(result);
}
});
});
</script>
The external php file that I want to pick up the lat and lng from the above and perform calculations on, returning the name of the town.
<?php
function getTown(){
$conn = Connect();
/**
* Use the Haversine Formula to display the 100 closest matches to $origLat, $origLon
* Only search the MySQL table $tableName for matches within a 10 mile ($dist) radius.
*/
$origLat = $_POST['lat'];
$origLon = $_POST['lng'];
$dist = 50; // This is the maximum distance (in miles) away from $origLat, $origLon in which to search
$query = "SELECT Townland, lat, lng, 3956 * 2 *
ASIN(SQRT( POWER(SIN(($origLat - lat)*pi()/180/2),2)
+COS($origLat*pi()/180 )*COS(lat*pi()/180)
*POWER(SIN(($origLon-lng)*pi()/180/2),2)))
as distance FROM townland WHERE
lng between ($origLon-$dist/cos(radians($origLat))*69)
and ($origLon+$dist/cos(radians($origLat))*69)
and lat between ($origLat-($dist/69))
and ($origLat+($dist/69))
having distance < $dist ORDER BY distance limit 1";
$result = mysqli_query($conn, $query) or die(mysql_error());
if($row = mysqli_fetch_assoc($result)) {
echo $row['Townland'] ;
}
}
getTown();
?>
<script type="text/javascript">
$('lat').change(function(){
var lat=document.getElementById('lat').value;
var lng=document.getElementById('lng').value;
$.ajax
({
url: '../Controller/PRACTICEtown.php',
data: { lat : lat, lng : lng},
type: 'post',
success: function(result)
{
$('#Townland').value(result);
}
});
});
Note ajax data field
instead of
data: { var : lat, var : lng},
use
data: { lat : lat, lng : lng},
edit: in your comment to your own question you say that the id of your townland input is "townland", but in the ajax success function you want to change value of "Townland" (Upper Case!)
I have a script Ajax/jQuery this autoupdate a statistics in my site this is the code:
<!--Jquery/AJAX script-->
<script type="text/javascript">
function updateStats(stat)
{
var stat = ["online","newestPlayer","cuentas","personajes","guilds"];
var url = "template/Next/stats_do.php";
$.each(stat, function(i, key){
$.post(url, {stats: key}, function(data) {
$("#" + key).text(data);
});
});
}
setInterval('updateStats("updateStats")', 500);
</script>
Work all fine. for the results i use. for example...
But i have a ProgressBar with php. The code for work is (a part)
<?= round (HERE MY RESULT*100/$pBar2max); ?>%
The problem is that putting the does not allow multiplication in order to get the percentage
and i try
$onlines = <span id="online">
and insert a echo in the code, but not work, any solutions? i need extract a number in text for multiply with *100
I have a script where i am trying to send some location information to a php page, carry out a mysql search query and get the results back without going to another page.
my php works fine, and i have had the page working that it redirects to the php page, however when i try and use the code below, i do not get any results passed back.
Javascript code
function phpRedirect(loc) {
// var radius = get('r'); // Retrieve GET values for search radius and
// var numResults = get('n'); // number of results
var radius = 10; // Retrieve GET values for search radius and
var numResults = 5; // number of results
var latitude = loc.coords.latitude; // Get long, lat and accuracy from
var longitude = loc.coords.longitude; // location object
var accuracy = loc.coords.accuracy;
var xmlHttp = new XMLHttpRequest(); //not the cross browser way of doing it
xmlHttp.open("GET", "find.php?lat=" + latitude + "&long=" +
longitude + "&acc=" + accuracy + "&r=" + radius
+ "&n=" + numResults, true);
xmlHttp.send(null);
}
$(function ()
{
$.ajax({
url: 'find.php', //the script to call to get data
type: "post",
data: { getData: true },
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var name = data[0];
$('#output').html("<b>username: </b>"+username);
}
});
});
function error(loc) {
// This is called if the location can't be found.
document.write("Error finding GPS location");
}
// Use navigator to get current user location. If found, calls 'phpRedirect()',
// If not available calls 'error()'. Includes timeout and ensures highest acc.
navigator.geolocation.getCurrentPosition(phpRedirect, error, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
<div id="output">this element will be accessed by jquery and this text replaced </div>
Below is the output from my php query,
$result=mysql_query($query) or die (mysql_error());
while($row=mysql_fetch_assoc($result)) $data[]=$row; // Turn result to array
$acc_package = array('location_accuracy'=>"$accuracy"); // Include result array
$output[] = $acc_package; // and accuracy value inside
$output[] = $data; // an output array.
print(json_encode($output)); // Convert output array to json format and print
Which gives the following results
[{"location_accuracy":"122000"},[{"username":"bobbyj","distance":"0.484367160806139"}]]
Sam, I have a few suggestions for you.
First, the jQuery library is great and the AJAX module works amazing :) It's great that you are using it! No need to mix that old XMLHTTP junk with it (they do basically the same thing). So get rid of that and replace it with jQuery ajax.
Let's start with something really basic:
$.ajax({
url: 'find.php',
type: "POST",
data: { lat: lattitude }
}).done(function( msg ) {
alert(msg);
});
Put your other variables in the data: as well.
On your PHP page, try a simple var_dump($_POST); so you can see what is coming through. The AJAX should make an alert with contents of the PHP page.
Work your way up from this with your Mysql :)
I have the following javascript function
function success_callback(p)
{
lat = p.coords.latitude.toFixed(2);
lon = p.coords.longitude.toFixed(2);
}
Now I want to transfer both the variable to PHP using Jquery AJAX, I am pretty new to Jquery, I am not able to figure out how to do it. I want to transfer the variables to the same PHP file where this JS code resides. Is that possible ?
Yes it is. You could post the variables using the data string. Have a look at the Manual.
$.ajax({
type: "POST",
data: "lat="+lat+"&lon="+lon,
success: function(){
//callback code
alert("Done!");
}
});
using ajax call, you can send values to another php file, in case of same file needs to use condition needs to be checked.but best is to pass parameters to another file for pressing.
Where you wanted to use/why you wants those on same page?
You could use jQuery.get(). The syntax is easy
function success_callback(p) {
lat = p.coords.latitude.toFixed(2);
lon = p.coords.longitude.toFixed(2);
var coords = {
lat: lat,
long: lon
};
$.get('mypage.php', coords, function () {
alert('data sent');
});
}
And in your PHP script, you use the $_GET
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$long = isset($_GET['lat']) ? $_GET['long'] : 0;
javascript:
$.get('index.php?lat='+ lat + '&long=' + lon)
php:
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$lon = isset($_GET['lat']) ? $_GET['long'] : 0;
If your current page is named index.php.
Keep in mind the current page is going to process again unless you specifically program your php not to. You asked to send it to the current page, though, so that is what this does.