Unable to extract result from geocode callback/function - javascript

I am having trouble extracting data from the following function which only works with an alert(content) as the next line but obviously this has to be removed! What am I doing wrong please?
var address = [];
var content;
geocoder.geocode({'latLng': Marker.getPosition()}, function(responses, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (responses && responses.length > 0) {
address = (responses[0].formatted_address).split(',');
for (i =0; i < address.length; i++) {
content += '<div>' + address[i] + '</div>';
}
}
}
});
content += content '<br>Last line</div>';
The above line does not include the above geocode content at all.

Callback is async, you can use the value only inside the callback.
content += content '<br>Last line</div>';
Will execute BEFORE the callback fires.
Please read this regarding handling server data got by AJAX.

Related

special character % is transmitted to % at server side through jquery AJAX call: Updated

I have a HTML form as the output of a java that gets a text from database and fill an input of that form with it. In form I can edit the text that on submit
Is sent back to java via a jquery AJAX call. Through java the text is saved in the database.
If I enter test% in text area it is coming as test% at server side.
Let’s say the HTML form looks like this :
<form id="form_used_0" action="#" method="post" onclick="hideAjaxList();">
<textarea name="summary" id=" summary " data-mini="true"><%=HtmlWriter.preformat(summary)%></textarea>
<a id="saveBtn" class="actionBtn" href="#" data-theme="b" onclick="onSave (this);">Save</a>
</form>
On saveBtn click this AJAX call is made:
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var params = $("#form_used").serialize()+"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
I tried using the serializeArray method but now getting 400 Bad request error. I checked the form data in network tab and found that it is showing as unable to decode value beside input field .
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var x = $("#form_used_0").serializeArray();
var paramsArr = "";
$.each(x, function(i, field){
if(i == x.length - 1){
paramsArr = paramsArr + field.name + "=" + field.value;
} else {
paramsArr = paramsArr + field.name + "=" + field.value + "&";
}
});
var params paramsArr +"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
Would it be possible for anyone to help me on the same.
As per jQuery documentation, The .serialize() method creates a text string in standard URL-encoded notation.
You can use Apache Commons StringEscapeUtils.unescapeHtml() to decode the string at server level.
Alternatively, if required you can pass the text from textarea as an additional param, which you can use it.
Thanks.

Passing generated id from one page to another

I really really need your help pls. I have been battling with these for days and my project is stucked. Your help will really be appreciated.
I have 3 pages.
Page one receives my data, and html formatted version is created. it is a loop and it returns 10 posts.
===
page 2 is the html page that displays the 10 post
====
page 3. the posts at page 2 are just featured image and excerpt and title with url... to read full, click it and go to page 3 ...
Page 3 uses the unique id of each posts to display the full post:
my question: how do i pass each post id to page 3 for full content view.
i tried to store the id generated in page 1 to localstorage, but bcos its a loop ... ONLY THE LAST ONE IS STORED..
my code..
Page 1 - script page receives data
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
Page 1 still: CreateHTMl create thru a loop
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < 1; i++)
{
var posturl = postsData.link
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + ''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + localStorage.setItem("postid",postsData[i].id)+'</td>';
//i tried to store each id in a localstorage but only the last one remains
ourHTMLString+= '</tr>';
} portfolioPostsContainer.innerHTML = ourHTMLString;
}
page two uses this to display ourHTMLString
<div id="portfolio-posts-container"></div>
page 3 Need each post id.
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts/'+mypostid+'?_embed=true')
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
// createHTML(data); '+mypostid)
console.log(data);
var ourHTMLString = '';
Each post has its generated id from the api, how do i pass it to page 3 for displaying individual post
Although I'm a little confused as re the overall structure of this system, you could pass the id as a query string parameter.
View post 123
This can be parsed using location.search within JavaScript:
var postMatch = /id=(\d+)/.exec(location.search);
if(postMatch) {
var postId = postMatch[1];
// Load post postId...
} else {
// No post was passed
}

JS variable "disappear" with no reason and gets empty

I am trying to get lat and long info from Google Geocoder, but although the information is properly extracted on the call that is being done, for some reason the js variable gets empty imediately after getting to my second alert on this piece of code (the one outside "if" condition):
var map, marker, latLong;
var geocoderlat = new google.maps.Geocoder();
var addresslat = '<?php echo str_replace(" ","+",$address);?>';
function initMap() {
geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLong = results[0].geometry.location;
alert("Inside IF: "+latLong);
} else {
latLong = '<?php echo $latitude.",".$longitude;?>';
}
})
alert("Outside: "+latLong);
var isDraggable = !('ontouchstart' in document.documentElement);
var mapOptions = {
center: new google.maps.LatLng(latLong),
zoom: 12,
(...)
Obviously there's a lot of code besides this part, but the rest of the code doesn't matter in this case because this variable is never again used anywhere in my code (I even searched with Agent Ransack all over the files so be sure that this variable was not being used anywhere else).
EDIT:
Ok, this is really, really weird...
function getGeoLatLong(addresslat) {
geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
return results[0].geometry.location;
} else {
return '<?php echo $latitude.",".$longitude;?>';
}
})
}
alert("Outside function: "+getGeoLatLong(addresslat));
This still returns "undefined" in the alert.
geocoderlat.geocode is taking more time to execute while the code execution has already reached your second alert. you need to use setTimeout to check the results or try this.
function initMap() {
geocoderlat.geocode( { 'address': addresslat}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLong = results[0].geometry.location;
alert("Inside IF: "+latLong);
alert("Outside: "+latLong);
var isDraggable = !('ontouchstart' in document.documentElement);
var mapOptions = {
center: new google.maps.LatLng(latLong),
zoom: 12,
(...)
} else {
latLong = '<?php echo $latitude.",".$longitude;?>';
}
})
Also, if you want to use latLong = '<?php echo $latitude.",".$longitude;?>'; as the default latLong you need to declare it at the top. then it will be anyways overridden when geocode finishes loading
EDIT
Try this.
function getGeoLatLong(addresslat) {
geocoderlat.geocode( { 'address': addresslat}, checkresults)
}
function checkresults(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Outside function: " + results[0].geometry.location);
//declare the big chunk of code as a function and make a call to it.
} else {
alert("Outside function: <?php echo $latitude.','.$longitude;?>");
//declare the big chunk of code as a function and make a call to it.
}
}
getGeoLatLong(addresslat);

How to fashion callback for results of JQuery/AJAX 'get' routine

I've read and re-read every first-page Google result on JQuery/AJAX callbacks using every permutation of terms I can think of, and no re-write I've tried for the code below is successful.
I simply need to construct a callback for this function—which is part of a larger self-calling JQuery function—so that the 'message' variable holds the results of the integrity_check.php routine before proceding to the evaluation routine of 'message' at the end.
(Yes, this is yet another attempt to make JQuery synchronous, and I understand that callbacks are the answer, but I can't find it.) May success and happiness befall you if you can help me with this:
// If the integrity check passed, message will be empty.
// If the integrity check fails, message will hold text for an alert box.
var message;
$.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
if (data != 0) {
message = data;
}
});
[...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]
if (message != '') {
alert(message);
} else {
[...proceed with using new_variable in HTML...]
}
UPDATE
The suggestion by Guest271314 pointed in the right direction, although I had to make modifications to make it work; see CAPS commentary in code solution that follows:
var request = $.get('integrity_check.php', { add_new_variable: $('#new_variable').val() }, function(data) {
if (data != 0) {
message = data;
}
return message;
});
// HERE I HAD TO SAVE THIS VALUE TO A NEW VARIABLE;
// $('#new_variable').val(); WAS NOT ACCESSIBLE OTHERWISE IN THE ROUTINE THAT FOLLOWED:
var nv = $('#new_variable').val();
// HERE IT WAS IRRELEVANT WHAT ARGUMENT WENT INTO function(),
// EXCEPT IT COULD *NOT* BE message; YOU HAD SUGGESTED msg, WHICH WAS IMMATERIAL, IT TURNED OUT
request.then(function() {
// HERE I *HAD* TO USE message, NOT THE GENERIC msg THAT YOU HAD PASSED INTO THE FUNCTION:
if (message != '') {
alert(message);
} else {
// THE ORIGINAL FORM HERE WOULDN'T WORK, AS $('#new_variable').val() WAS INACCESSIBLE IN THE FUNCTION:
//var newKeyword = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + $('#new_variable').val() + '" checked /> ' + $('#new_variable').val() + '</label>';
// THIS, HOWEVER, WORKED...USING nv IN PLACE OF $('#new_variable').val();
var newVariable = '<label><input name="new_variable[]" type="checkbox" tabindex="-1" value="' + nv + '" checked /> ' + nv + '</label>';
$('#checkboxes').append(newVariable);
}
});
I'm grateful to guest271314 for what s/he posted, although I'm unclear on why I had to make the changes that I did in order for the code to work. Elucidation, anyone?
Try utilizing deferred.then()
// If the integrity check passed, message will be empty.
// If the integrity check fails, message will hold text for an alert box.
var message;
var request = $.get('integrity_check.php'
, { add_new_variable: $('#new_variable').val() }
, function(data) {
if (data != 0) {
message = data;
}
return message
});
/*
[...some other code follows that may or may not set 'message' variable to a text message for alert box, so the following code must stand independently:]
*/
request.then(function(msg) {
// `msg`: `message`
if (msg != '') {
alert(msg);
} else {
// [...proceed with using new_variable in HTML...]
}
// return msg
}, function err(jqxhr, textStaus, errorThrown) {
console.log(errorThrown)
});

Calculate driving distances Google Maps API

For a website where a user enters his address, I'm trying to find the location closest to him where the user can collect the ordered goods.
Based on the user's address I can narrow down the possible pick up locations to between 2 and 5. So I'd like to calculate the distance between user's address (point A) and the possible pick up locations.
The demo here works fine with just two addresses. I've adapted the code as much as I can to work with more than two addresses. I posted my JS code here since I can't seem to properly format it in SO.
In the code are two alerts. The first alert correctly shows the different pick up locations. But the second alert always shows the LAST pickup location.
Can anyone explain why?
HTML:
<p id="hello">Hello World</p>
JavaScript:
var geocoder, location1, location2, gDir;
function initialize(counter) {
if( counter == 0 ){
geocoder = new GClientGeocoder();
gDir = new GDirections();
}
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
$("#results").append('<strong>Driving Distance: </strong>' + drivingDistanceKilometers + ' kilometers<br /><br />');
});
}
function getDistance(agency_add, counter) {
initialize(counter);
geocoder.getLocations(agency_add, function (response) {
if (!response || response.Status.code != 200) {
alert("Sorry, we were unable to geocode the address" + agency_add);
}
else {
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
//alert("ONE: "+location1.address);
geocoder.getLocations(document.forms[0].address1.value, function (response) {
//alert("TWO: "+location1.address);
if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");}
else {
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + ' to: ' + location2.address);
}
});
}
});
}
$(document).ready(function(){
//put each agency address in an array
var agencies = [];
$(".agency_field").each(function(index) {
agencies.push($(this).val());
});
for (var i = 0; i < agencies.length; i++){
var res = getDistance(agencies[i], i);
}
});
you are calling geocoder.getLocations inside a loop. geocoder.getLocations runs asynchronously. when it receives the 2nd request while still processing the first, it cancels the first request.
If you want to multi-thread geocoder.getLocations you need to create multiple instances of it.

Categories