Data not passing to php file - javascript

Getting trouble sending users geolocation through AJAX into a php file.
Here the code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
$.ajax({
type: 'POST',
data: pos,
url: '/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
Have tried diferent ways to write data like:
data: {pos},
data:({pos}),
data: {lat: position.coords.latitude, lng: position.coords.longitude},
And that it's the error that I get in template-userslocation.php:
Notice: Undefined index: pos in /home/.../template-userslocation.php on line 7
SOLVED:
The problem was that I've been working in Wordpress and it has it own way to handle with javascript:
here the info

pos is the name of the variable, from PHP it will not know that, it will only see $_POST['lat'] and $_POST['lng']
So use:
$.ajax({
type: 'POST',
data: {'pos': pos},
url: '/wp-content/themes/atripby/template-userslocation.php'
});
Then from PHP access like:
$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;

Related

Ajax POST can't read from PHP

Im writing a javascript and wanted to send the data to PHP page addProject-logic.php through ajax POST.
Although the POST request success on the javascript, but on my php page i couldnt echo, it showed undefined "latLng"
My file structure:
Structure
addMap.js :
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng
currentLatitude = latLng.lat()
currentLongitude = latLng.lng()
var latlng = {
lat: currentLatitude,
lng: currentLongitude,
}
//Post LAT LNG TO POST
function postLatLng() {
$.ajax({
type: 'POST',
url: '../includes/actions/addProject-logic.php',
data: {
latLng: latlng,
},
success: function (response) {
window.alert('Success')
},
})
}
var geocoder = new google.maps.Geocoder()
geocoder.geocode(
{
location: latlng,
},
function (results, status) {
if (status === 'OK') {
if (results[0]) {
input.value = results[0].formatted_address
map.setZoom(18)
map.panTo(latLng)
postLatLng()
} else {
window.alert('No results found')
}
} else {
window.alert('Geocoder failed due to: ' + status)
}
},
)
})
i create a function postLatLng then execute in another action
Whenever I echo on php addProject-logic.php page, echo $_POST['latLng']; it showed undefined array key latLng
Your example is a bit vague as you don't show what addProject-logic.php file does but here's a fresh example with a javascript call and a php code.
I'm simplifying by using javascript (you can convert to jQuery) and removing geocode as it seems it is not the issue here (but then, your example is vague).
I'm using fetch to make the requests in order to show the different steps. Notice the JSON.stringify call.
// Data is
var latlng = {
lat: 42,
lng: 42
}
function postLatLng() {
fetch('addProject-logic.php', {
method: 'POST',
body: JSON.stringify({
latLng: latlng
})
})
// the response sent back via php is json
.then(response => response.json())
.then(json => {
// The data returned by the php script contains latLng
window.alert(json.latLng)
})
.catch(err => {
console.error(err)
})
}
On the php side:
<?php
// Header for the JSON response
header('Content-Type: application/json; charset=UTF-8');
// parsing the post content
// My guess is you miss both this call and the JSON.stringify in the js
$data = json_decode(file_get_contents('php://input'), true);
// here we send back the post data.
echo json_encode([
'latLng' => $data["latLng"],
]);

javascript function before google maps load

I have to put markes on google maps, but the array with lat, long is made by an Ajax request.
Map is loaded before the initialization of the array and I don't see the markers.
I think that this is the problem but I'm not so sure. hope you can help me
<script>
$(document).ready(function() {
setVariable('<?php echo $_SESSION["token"]?>');
});
</script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXX&callback=initMap">
</script>
coord = new Array();
function setVariable(token) {
format="text/plain";
$.ajax({
url: BASE_URL + "reports",
type: "GET",
contentType: "application/json; charset=utf-8",
headers: {'x-access-token': token},
cache: false,
success: function(data){
if (data.success){
$.each(data.data.reports, function (i, item) {
coord[i] = [ data.data.reports[i].lat , data.data.reports[i].lng ] ;
});
console.log(coord)
}else{
alert(data.error.message);
}
},
error: function(data){
console.log(data);
}
});
}
function initMap() {
var myLatLng = {lat: 43.1107168, lng: 12.3908279};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: myLatLng
});
var marker, i;
for (i = 0; i < coord.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(coord[i][0], coord[i][1]),
map: map,
title: 'Hello World!'
});
}
}
How can i resolve this?
thank you very much.
You will need to restructure the code in order to make this work. We need to add markers on the map only after we have fetched the lat/long data successfully by making an AJAX request. We could do this in the following manner.
<script defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXX&callback=initMap">
/*
We will keep a global variable that would contain a reference to the google map object.
It would be initialized as soon as the script for google maps is loaded and initMap function is called subsequently.
*/
var GoogleMap;
coord = new Array();
function setVariable(token) {
format="text/plain";
$.ajax({
url: BASE_URL + "reports",
type: "GET",
contentType: "application/json; charset=utf-8",
headers: {'x-access-token': token},
cache: false,
success: function(data){
if (data.success){
$.each(data.data.reports, function (i, item) {
coord[i] = [ data.data.reports[i].lat , data.data.reports[i].lng ] ;
});
console.log(coord)
var marker, i;
for (i = 0; i < coord.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(coord[i][0], coord[i][1]),
map: GoogleMap,
title: 'Hello World!'
});
}
}else{
alert(data.error.message);
}
},
error: function(data){
console.log(data);
}
});
}
function initMap() {
var myLatLng = {lat: 43.1107168, lng: 12.3908279};
GoogleMap = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: myLatLng
});
}
Hopefully, this should work!

How Can I store city name obtained from geolocation to a variable and send ajax request?

<script>
new Vue({
el: '#fad' ,
data: {
data: {},
},
mounted() {
var self = this;
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function(location) {
$('#country').html(location.results[0].address_components[5].long_name);
$('#state').html(location.results[0].address_components[4].long_name);
$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
})
var lat = position.coords.latitude;
$.ajax({
url: 'https://api/post//',
data: {
lat: position.coords.latitude,
lon: position.coords.longitude,
city:location.results[0].address_components[2].long_name,
},
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status == 1) {
self.data = e.data;
console.log(e.data)
}
}
});
console.log(lat);
}
function error(err) {
console.log(err)
}
}
})
</script>
This is my code. I am able to get lat and lon values and pass. But I am not able to pass city. When I do this way, I am getting error. I am very weak in js and this is the first time doing a project. Please help me to obtain the result. I need to send name of city through ajax request. <span id="city"></city> in html gives me the city name. How to get the city name in script and send this by ajax request. Please help me?
I think you were trying to make the AJAX function in the wrong place. The getCurrentPosition is asynchronous so the response is not necessarily available immediately - thus the ajax request that you are trying to send should be sent only on getting the response from getCurrentPosition
<script>
new Vue({
el: '#fad' ,
data: {
data: {},
},
mounted(){
var self = this;
navigator.geolocation.getCurrentPosition( success, error );
function success( position ) {/* geolocation success callback */
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON( GEOCODING ).done( function( location ) {
$('#country').html(location.results[0].address_components[5].long_name);
$('#state').html(location.results[0].address_components[4].long_name);
$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
/*
As this is an asynchronous process, make the
ajax request here.
*/
var lat = position.coords.latitude;
console.log( lat );
$.ajax({
url: 'https://api/post//',
data: {
lat: position.coords.latitude,
lon: position.coords.longitude,
city: location.results[0].address_components[2].long_name,
state: location.results[0].address_components[4].long_name,
country: location.results[0].address_components[5].long_name
},
type: 'POST',
dataType: 'json',
success: function(e) {
if( e.status == 1 ) {
self.data = e.data;
console.log( e.data )
}
}
});
});
}
function error( err ) {/* geolocation error callback */
console.log( err )
}
}
});
</script>
You have a syntax error in your code, that's why it's not running.
In your $.ajax call, you have a semicolon after
city:location.results[0].address_components[2].long_name;
which is a syntax error, remove the trailing ;
EDIT
You updated your answer and fixed the trailing ;, next to that the code seems to run ok, check the snippet below.
Here's a small snippet with reformatted code. Don't forget to change your $.ajax url, unless you really want to POST to https://api/post
new Vue({
el: '#fad',
data: {
data: {},
},
mounted() {
var self = this;
navigator.geolocation.getCurrentPosition(function () {
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function (location) {
$('#country').html(location.results[0].address_components[5].long_name);
$('#state').html(location.results[0].address_components[4].long_name);
$('#city').html(location.results[0].address_components[2].long_name);
$('#address').html(location.results[0].formatted_address);
$('#latitude').html(position.coords.latitude);
$('#longitude').html(position.coords.longitude);
});
$.ajax({
url: 'https://api/post//',
data: {
lat: position.coords.latitude,
lon: position.coords.longitude,
city: location.results[0].address_components[2].long_name,
},
type: "POST",
dataType: 'json',
success: function (e) {
if (e.status == 1) {
self.data = e.data;
console.log(e.data)
}
}
});
},
function () {
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="fad"></div>

Getting response in network but console return error with cross origin

I'm using google map api for web...
Also I'm calling search nearby api directly from jquery to search places,
this is error in console
this is response in network
I've already added to use api from all referrer in google api console.
var param = {
key: "My_Key",
location: pos.lat+','+pos.lng,
radius: 3000,
type: "church"
};
$.ajax({
url: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + jQuery.param(param),
method: "GET",
async: false,
success: function(resp) {
console.log(resp);
},
error: function(error) {
console.log(error);
}
});
Don't use the Places API web service from javascript on the client, use the Google Maps Javascript API v3 Places Library.
example in documentation
proof of concept fiddle (using the posted request parameters)
code snippet:
var map;
var service;
var infowindow;
function initialize() {
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '3000',
type: ['church']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map"></div>
Try adding dataType : 'jsonp' in your $.ajax call as,
$.ajax({
url: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" + jQuery.param(param),
method: "GET",
dataType : 'jsonp',
async: false,
success: function(resp) {
console.log(resp);
},
error: function(error) {
console.log(error);
}
});
Hope this helps!

laravel 5 loading addresses in google map api

I am new to json and laravel and I would like to put my question forward.
I have a database table called dealer_address which has id, address, state, pin, city.
My javascript to load the map with some addresses are:
<script type="text/javascript">
$(function(){
$('#test1').gmap3({
map:{
options:{
center:[46.578498,2.457275],
zoom: 5
}
},
marker:{
values:[
{latLng:[48.8620722, 2.352047], data:"Paris !"},
{address:
$.ajax({
url: '/maps2/',
type: 'get',
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
console.log(results);
}
})}
],
options:{
draggable: false
},
events:{
mouseover: function(marker, event, context){
var map = $(this).gmap3("get"),
infowindow = $(this).gmap3({get:{name:"infowindow"}});
if (infowindow){
infowindow.open(map, marker);
infowindow.setContent(context.data);
} else {
$(this).gmap3({
infowindow:{
anchor:marker,
options:{content: context.data}
}
});
}
},
mouseout: function(){
var infowindow = $(this).gmap3({get:{name:"infowindow"}});
if (infowindow){
infowindow.close();
}
}
}
}
})
});
</script>
However, I would like to display addresses on the map from the database result.
public function ShowData()
{
$location = '700016';
$results = DB::table('dealer_address')
->where('dealer_address.city', 'LIKE', '%'.$location.'%')
->orWhere('dealer_address.pincode', 'LIKE', '%'.$location.'%')
->orWhere('dealer_address.state', 'LIKE', '%'.$location.'%')
->get();
dd($results);
return View::make('/maps2')->with('data', json_encode($results));
}
My dd($results) is working fine. Where and what do I need to change in my javascript to pass this json ?
I believe you can simplify your return statement to this:
return json_encode($results->toArray());
Laravel 4.2
return Response::json($results->toArray());
Laravel 5.1
return response()->json($results->toArray());
You could create
var options = [your data]
and after call $('#test1').gmap3(options)
When you have options
You can call ajax for json data and setit
options.marker.values.address[0] = response

Categories