Ajax POST can't read from PHP - javascript

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"],
]);

Related

Cannot pass variables between javascript function and ajax in django project

This is a proper noob question it would seem, so apologies, but I can't seem to solve it so I'm reaching out for some assistance.
I have a function in my .js file that interacts with the Google Places library to autocomplete a field in a form. I then have an ajax function that runs when you click the submit button which creates variables in the django session. The data of interest to me is lat and long.
However, for some reason, I can't seem to get the data to pass from one to the other. I know the ajax function is working because if I type in fixed values they propagate through to django, but I can't seem to get it to update dynamically.
const csrf = document.getElementsByName('csrfmiddlewaretoken');
var lat;
var lng;
function autocomplete_location() {
let defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(49.6331, -11.7247),
new google.maps.LatLng(59.4850, 1.5906));
let input = document.getElementById('id_your_location');
let options = {
bounds: defaultBounds,
types: ["address"],
fields: ["name", "geometry"],
};
let autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', function() {
// Get place info
let place = autocomplete.getPlace();
// Do whatever with the value!
lat = place.geometry.location.lat()
lng = place.geometry.location.lng()
console.log(lat)
console.log(lng)
})
}
$(document).ready(function (){
$(".btn").click(function (){
$.ajax({
url: '',
type: 'POST',
data: {
'csrfmiddlewaretoken': csrf[0].value,
'lat': lat,
'long': lng,
},
success: function (response) {
console.log(response)
window.location.replace('/new_path/')
},
error: function (error) {
console.log(error)
}
})
})
})
UPDATE -----------------------------------------------------------
I have managed to get this working. I have moved the ajax call into the autocomplete function, but it only works when I click the submit button, it does not work when I press the enter key, so I need to brush up on my JS and ajax to solve that problem.
const csrf = document.getElementsByName('csrfmiddlewaretoken');
function autocomplete_location() {
let defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(49.6331, -11.7247),
new google.maps.LatLng(59.4850, 1.5906));
let input = document.getElementById('id_your_location');
let options = {
bounds: defaultBounds,
types: ["address"],
fields: ["name", "geometry"],
};
let autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.addListener('place_changed', function() {
// Get place info
let place = autocomplete.getPlace();
// Do whatever with the value!
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
console.log(lat)
console.log(lng)
$("form").submit(function (){
$.ajax({
url: '',
type: 'POST',
data: {
'csrfmiddlewaretoken': csrf[0].value,
'lat': lat,
'long': lng,
},
success: function (response) {
console.log(response)
// this is not good. But I couldn't find a better way to redirect
// window.location.replace('/coach/')
},
error: function (error) {
console.log(error)
}
})
})
})
}
where do you call autocomplete_location() ? try passing lat and long in that function as parameters e.g. autocomplete_location(lat, long)

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>

Data not passing to php file

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;

Getting Error Passing values from Controller Laravel to Ajax Jquery GET Json

I´m using Laravel 5.4 for Backend server
This is my Backend side of Controller:
$locations = Neighborhood::where('House_id', $id)->get();
$json = json_encode($locations);
return response()->json($json);
This is my Ajax Jquery Script:
$(document).ready(function (){
var map = new GMaps({
div: '#mymap',
lat: 32.651287,
lng: -16.885297,
zoom:15
});
$.ajax({
url:"api/maps/house/1",
type: "GET",
dataType: 'json',
crossDomain: "true",
success: function (result) {
if (result.type == false) {
alert("Error occured:" + result.data);
return false;
}
$.each(data,function(index,obj){
alert(obj.name);
});
},
error: function(result){
alert(result);
}
});
});
I´m getting error result alert with Obj Obj
This is my JSON Strucutre:
"[{\"id\":1,\"name\":\"Dolce Vita\",\"House_id\":1,\"lat\":\"32.647471\",\"lng\":\"-16.914049\"}]"
When you do response()->json, response will converted to json. SO you do not need to do json_encode before it
https://laravel.com/docs/5.5/responses
So change your controoler to
$locations = Neighborhood::where('House_id', $id)->get();
return response()->json($locations);
This line not required $json = json_encode($locations);. Remove that line from your code. because that is nor required. return response()->json($locations); this line will send response in json format.
$locations = Neighborhood::where('House_id', $id)->get();
return response()->json($locations);

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