Trying to send data from JS to PHP with AJAX - javascript

I am trying send some data from JavaScript to PHP, but it seems I'm not doing it wrong. I am using reverse geocoding to get the location name of a specific marker on google maps, this works just fine. However, I need that particular data on the PHP-side.
This is what my script looks like, var markerLocation is the variable I'm trying to get across (js/map_article.js):
// Reverse geocoding
function geocodeLatLng(geocoder, map, infowindow)
{
result.forEach(function(entry) {
var latlng = {lat: parseFloat(entry.lat), lng: parseFloat(entry.lng)};
geocoder.geocode({'location': latlng}, function(results, status)
{
if (status === google.maps.GeocoderStatus.OK)
{
if (results[1])
{
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
var markerLocation = results[1].formatted_address;
// Send the adress back to php
$.ajax({
type: "POST",
url: 'article.php',
data: {markerLocation : markerLocation},
success: function(data)
{
alert("success!");
}
});
}
else
{
window.alert('No results found');
}
}
else
{
window.alert('Geocoder failed due to: ' + status);
}
});
});
}
And this is what the PHP (article.php) looks like:
<?php
$id = $_GET['id'];
$sql = "SELECT * FROM blog WHERE id=$id";
$result = db_select($sql);
?>
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var result = <?php echo json_encode($result) ?>;
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="js/map_article.js"></script>
<body>
<?php
// Is the AJAX-data coming across?
if(isset($_POST['markerLocation']))
{
echo "<p>".$_POST['markerLocation']."</p>";
}
else
{
echo "<p>It did not work..</p>";
}
?>
</body>
</html>
The Alert message "success!" does show, but the variable $_POST['markerLocation'] is still undefined. Where did I go wrong?

Related

<script>Not Getting Lat and Long from the given map address jquery or javascript

I want to find lat and lng from given address but i cant find same can you please help me to solve this query
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "patan"}, function(results, status) {
alert(status)
if (status == google.maps.GeocoderStatus.OK) {
alert(results[0].geometry.location.lat());
//$('.push-down').text("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng());
} else {
$('.push-down').text("Something got wrong " + status);
}
});
</script>
Kindly try below code :-
<div class="push-down"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "patan"}, function(results, status) {
//alert(status)
if (status == google.maps.GeocoderStatus.OK) {
var Lat = results[0].geometry.location.lat();
var Lng = results[0].geometry.location.lng();
$('.push-down').html("latitude: " + Lat + " <br/>longitude: " +Lng);
} else {
$('.push-down').text("Something got wrong " + status);
}
});
</script>
Hope it helps :)
Since your question is marked php as well, I would recommend using the Google Geocode API Web Service. I find it much easier to use, than the js API.
Here is an example code:
<?php
// Request URL for Google Geocode API, result type = json, language = hu-HU, region = hu-HU
// Change result type, language, region to your needs
define('REQ_URL', 'https://maps.googleapis.com/maps/api/geocode/json?language=hu&region=hu');
// Your Google API key goes here
define('API_KEY', 'your-google-api-key-goes-here');
// Address you want to geocode
// Needs to be url encoded
$address = 'address-you-want-to-geocode-goes-here';
$address = urlencode($address);
// Parsing full request url
$request_url = REQ_URL . '&address=' . $address . '&key=' . API_KEY;
// Query Google API for result
$response = file_get_contents($request_url);
$resp = json_decode($response, true);
// Result array
print '<pre>';
print_r($resp);
print '</pre>';
I hope, I could be of any help.

Geocoding displaying "ZERO_RESULTS" to every input

A form in an html file passes an input called "address" to a php file "registerEvent.php" where it is to be geocoded. No matter what address is inputted, the function still outputs ZERO_RESULTS status in an alert which can happen if the inputted address is invalid(i.e. NULL or an impossible address). I have tested, that recieving the address value from the html form works correctly both in php and at the start of the codeAddress() function.
<?php
$geoadrese = $_POST['address'];
?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
geocoder = new google.maps.Geocoder();
var inputLat;
var inputLng;
function codeAddress() {
var address = '<?php echo $geoadrese; ?>';
// everything works fine up until this point
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
inputLat = results[0].geometry.location.lat();
inputLng = results[0].geometry.location.lng();
window.location.href = "registerEvent.php?inputLat=" + inputLat + "&inputLng=" + inputLng;
} else {
alert('Geocode was not successful for the following reason: ' + status);
};
});
}
codeAddress();
</script>

Execute JavaScript code after $_POST request in php

I want to place a marker on a map with geocoding. I got a working code for that:
$(document).ready(function(){
$('#submit').click(function(){
var address = document.getElementById("address").value + ", CH";
geocoder.geocode(
{'address': address},
function(results, status){
if(status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.location,
title: 'Sie suchten nach:' + ' ' + address
});
}
else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
}
else
{
alert("An unknown error occured. Refresh the page or contact the IT team! Error: '" + status + "'");
}
});
});
And I got this HTML form:
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" id="address" name="address" placeholder="Enter a zip code" style="width:250px;" onkeypress='filterTextbox(event)' />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
If I hit submit it should send my request to the server with $_POST and then send me an answer. After that, I want to execute the JavaScript code. So I've done this:
<?php
if(isset($_POST['submit'])){
echo "<script>
$(document).ready(function(){
var address = document.getElementById('address').value + ', CH';
geocoder.geocode(
{'address': address},
function(results, status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'Sie suchten nach:' + ' ' + address
});
}
else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
}
else{
alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
}
});
});
</script>";
}
}
?>
It sends me an answer (the page refresh because of the action) but then it does not execute the JavaScript code. The JavaScript code is for placing a marker at the place of what the users typed in the textbox. And it's working fine if I execute it "normal".
Hope you know what I mean
You have syntax errors
alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
should be
alert('An unknown error occured. Refresh the page or contact the IT team! Error: \'' + status + '\'');
Another likely cause is that the geocoder function has not yet been initialised by the time the document is ready.
Somewhere earlier on the page you should have code that looks similar to this:
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
geocoder = new google.maps.Geocoder();
}
You need to run your script at that point.
A way you can ensure that your script will be run is this:
// Where you load geocoder
var race_won = false;
var load_php_script = function() {
race_won = true;
};
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
geocoder = new google.maps.Geocoder();
load_php_script();
}
// Replace document.ready with this:
var php_script = function() {
// .. your old document ready code here ..
}
if (race_won) {
php_script();
}
else {
load_php_script = php_script;
}
Are you sure you have included jquery in the response? Are you sure that the element id="address" exists? Does browser's developer console report some error? Use breakpoints in it and see what's going on.
I understood that you try to update google maps when you push submit button. I don't see the neccessity of the form unless you want to save the addres in your database but then you should use ajax also.
If i'm right you should have this:
Explanation: when you press submit button will not refresh anymore the page and the address from input field will be send to the geocode function which will make an ajax call and at succes status == google.maps.GeocoderStatus.OK will execute the code from that if.
<div>
<input type="text" id="address" placeholder="Enter a zip code" style="width:250px;" onkeypress='filterTextbox(event)' />
<input type="button" id="submit" value="Submit" />
</div>
$('#submit').click(function(){
var address = document.getElementById('address').value + ', CH';
geocoder.geocode(
{'address': address},
function(results, status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'Sie suchten nach:' + ' ' + address
});
// save the address in database
$.ajax ({
url: "saveAddress.php",
data: {'address': address},
success: function() { //
alert("Should be saved in database");
}
});
}
else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
}
else{
alert('An unknown error occured. ');
}
});
});
Use an ajax request and run your JS code after success of this request.
You are using jQuery so you can use:
$('#yourform-id').on('submit', function(event) {
$.ajax('/your/url/here', {
type: 'post',
data: { zipcode: $('#address').val() }
}).done(function() {
/* your JS code after successful request goes here */
});
event.stopPropagation();
}
EDIT: You can do this also without the ajax request. But the important thing is to register the .on('submit', function(event) { /* your geocode JS code here */ event.stopPropagation(); } event to your form so the form doesn't get sent.
The event.stopPropagation() stops your form from reloading the page and send the form data via HTTP. In earlier jQuery versions you returned false but this is deprecated now.
So add this code to the HTML file where your form is too:
$(function() { // on ready
$('#yourform-id').on('submit', function(event) {
var address = document.getElementById('address').value + ', CH';
geocoder.geocode({'address': address}, function(results, status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'Sie suchten nach:' + ' ' + address
});
} else if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
window.alert = function(){}
} else{
alert('An unknown error occured. Refresh the page or contact the IT team! Error: '' + status + ''');
}
});
event.stopPropagation();
});
});

Google map v2 to v3 code

I am working on a migration project from google maps V2 to V3 and wrote the bellow code but
getting error and unable to solve the problem.
Am i using wrong method of google maps?
What is wrong in this code?
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='. $mapKey .'&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( $_ADDRESS );
// initialize map
function initialize()
{
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.getPosition( address, function(point)
{
if (!point)
{
alert(address + " not found");
}
else
{
map.setCenter(point, 13);
var marker = new google.maps.Marker(point);
map.addOverlay(marker);
//marker.openInfoWindowHtml(address);
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Any idesa?
Thanks
I have split these answers as the first deals with the fundamentals of the javascript, this then deals with using the Google Maps API.
As I've never used the maps API, I can't comment on V2, but looking at how you do things in V3, I think this does what you're looking for...
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( "$_ADDRESS" );
// initialize map
function initialize( address )
{
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.geocode( { "address": address }, function( results, status )
{
if ( status == google.maps.GeocoderStatus.OK )
{
position = results[0].geometry.location;
map.setCenter(position, 13);
var marker = new google.maps.Marker({ map: map, position: position });
}
else
{
alert(address + " not found");
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Having said that, I'd question the str_replace straight into the javascript - can you trust the source of that data? If not, then you should look up how to sanitise that string before you put it into your javascript or you may allow people to inject code into your site.
Looking at the fundamental javascript issues you have...
Try adding quotes around the string that you're replacing into the javascript
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
Becomes:
echo $map = str_replace('$_ADDRESS', "'MYADDRESS'", $map );
That way the string that contains the address in javascript is properly quoted.
Also, ensure that you can receive the address in your initialize function:
function initialize()
Becomes:
function initialize( address )
Finally, do not redeclare "map" when you assign it a value in "initialize", otherwise you are referencing a different variable that only exists in that function:
var map = new google.maps.Map(document.getElementById("map_canvas"), {
Becomes:
map = new google.maps.Map(document.getElementById("map_canvas"), {

Save Google Maps Markers onClick To Database

I want your guys' help on this. I wrote the code for allowing users to create markers(with infowindow) with a 'click' function that will save the lat/lan and other info to a MySQL database that will then be called to show the markers on the map. When you click on the map, it creates a marker but it will not save the info in the infowindow to the database. I followed the guide from the google maps developer's guide but I still can't get it to work. I even triple checked to make sure my MySQL login details work correct and still nothing.
Here is the code to the map itself:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js? sensor=false"></script>
<script type="text/javascript">
var marker;
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng(37.4419, -122.1419);
var options = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
var html = "<table>" +
"<tr><td>Name:</td> <td><input type='text' id='name'/> </td> </tr>" +
"<tr><td>Address:</td> <td><input type='text' id='address'/></td> </tr>" +
"<tr><td>Type:</td> <td><select id='type'>" +
"<option value='bar' SELECTED>bar</option>" +
"<option value='restaurant'>restaurant</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Save & Close' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}
function saveData() {
var name = escape(document.getElementById("name").value);
var address = escape(document.getElementById("address").value);
var type = document.getElementById("type").value;
var latlng = marker.getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
"&type=" + type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Location added.";
}
});
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map-canvas" style="width: 500px; height: 300px"></div>
<div id="message"></div>
</body>
</html>
This is what is supposed to save info to the database(phpsqlinfo_addrow.php):
<?php
require("phpsqlinfo_dbinfo.php");
// Gets data from URL parameters
$name = $_GET['name'];
$address = $_GET['address'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$type = $_GET['type'];
// Opens a connection to a MySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO markers " .
" (id, name, address, lat, lng, type ) " .
" VALUES (NULL, '%s', '%s', '%s', '%s', '%s');",
mysql_real_escape_string($name),
mysql_real_escape_string($address),
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($type));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
hi i have same issue with my project to save customer location,
which they click on there browser,
what i did was i save location in latitude and longitude in two input box as{you may take it hidden so it will not seen} in and give submit button and submit form i have given code you can also change it to submit form on click on map by submitting form on click by this and you can also store latitude and longitude in same column if you want
and you will need to insert you key
document.getElementById("yourform").submit();
<html>
<head>
<style type="text/css">
#map_canvas {height:300px;width:500px}
</style>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=""""youerapikeyhere""""&language=mr"></script>
<script type="text/javascript">
var map;
var marker;
var markersArray = [];
function initialize()
{
var latlng = new google.maps.LatLng(18.5236, 73.8478);
var mapOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) {
marker.setMap(null); //code
}
//adding marker
document.getElementById('txtLat').value=event.latLng.lat();
document.getElementById('txtLng').value=event.latLng.lng();
marker= new google.maps.Marker({
position: event.latLng,
map: map,
title: 'pune'
});
//creting info window instance
var infowindow = new google.maps.InfoWindow({
content: 'selected location'
});
//adding pointer click event to open infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<table cellpadding="0" cellspacing="0">
<tr><td colspan=3><div id="map_canvas" style="background-color: #ffffff"></div></td></tr>
<tr><td><input type="text" id="txtLat" name="txtLat"style="width:150px"></td>
<td><input type="text" id="txtLng" name="txtLng"style="width:150px"></td></tr>
</table></form>
</html>`
Try to narrow down the possibilities, or at least find out "where" it went wrong; meaning, is the issue caused from the front end or in the backend!?
If you use Webkit UA (browser) or its variants, use its Developer tools; if using Firefox, install an AddOn called FireBug. In the marker's click handler, try to output the coordinates using alert() or console.log() and see if the results are accurately fetched. Next check whether the AJAX call is passed as it should be to the backend.
In your PHP, try to examine the incoming values (from request parameters). Also turn on the debug output in php.ini so you'll know if the DB connections are successfully made by checking stderr or system logs.
There's a lot of things that could go wrong. It's hard to tell given by the lack of details you provided, but I hope my reply helps you to get a good start.
Oh, BTW, I'd strongly suggest you switch to PDO over mysql_, the mysql_ are to be deprecated in the future.

Categories