Handling AJAJ return value - javascript

I have been fiddling with Leaflet and different maps lately. I am currently trying to have the markers that are created by onClick events to show the current address that is parsed from a JSON query supplied by an API.
I am successfully parsing the address from the JSON query (console log in onMapClick(e)'s getAddress). What I want to do however is to return this value from the callbacked(?) function and make it visible as the marker's content.
function getAddress(lat, lon, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.digitransit.fi/geocoding/v1/reverse?point.lat=' + lat + '&point.lon=' + lon + '&size=1', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (typeof callback == "function") {
callback.apply(xhr);
}
}
}
xhr.send();
}
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("Address is " +
getAddress(e.latlng.lat, e.latlng.lng, function() {
var resp = JSON.parse(this.responseText);
console.log(resp.features[0].properties.label); //This gives the correct current address in console
return resp.features[0].properties.label; //This SHOULD return the correct address, verified with the console log, and replace the function call in the marker's content window, however the address appears always as undefined.
}))
.openOn(map);
}

Change the order of execution, so that you only use the value when you actually have it returned asynchronously from the API:
function onMapClick(e) {
getAddress(e.latlng.lat, e.latlng.lng, function() {
var resp = JSON.parse(this.responseText);
popup
.setLatLng(e.latlng)
.setContent("Address is " + resp.features[0].properties.label)
.openOn(map);
});
}

Related

AJAX Function Requires Double Click?

I have to click twice for the activation/deactivation of a user for some reason. Obviously I dont want that, it should be enough with one click. What am I doing wrong here?
(I am guessing that it's something wrong with the AJAX call)
C#:
var toggleUrl = "AdminListUsers.aspx?column=" + (IsClicked.FirstOrDefault().Key ?? "Name") + "&direc=" + (IsClicked.FirstOrDefault().Value) + "&a=chstat&q=" + id.ToString() + "&d=" + disabled + "&z=" + Server.UrlEncode(txtSearchFor.Text);
var hl = new HyperLink();
hl.Text = status;
hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
hl.NavigateUrl = toggleUrl;
hl.Attributes.Add("onclick", "loadDoc();return true;"); //Calling the function here
cell.Controls.Add(hl);
tr.Cells.Add(cell);
cell = new TableCell();
cell.Width = new Unit("10%");
cell.Controls.Add(new LiteralControl("<nobr>"));
var linkbtn = new HyperLink
{
NavigateUrl = toggleUrl,
Width = 16,
Height = 16,
CssClass = disabled ? "user-status-disabled" : "user-status-enabled"
};
linkbtn.Attributes.Add("id", "aButton_" + id);
linkbtn.Attributes.Add("onclick", "loadDoc();return true;"); //Calling the function here
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl(" "));
JavaScript:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
window.scrollTo(window.pageXOffset, window.pageYOffset);
window.location.reload();
}
};
xhttp.open("GET", "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+", true);
xhttp.send();
$('.TellusAlternatingRowColor').load(document.URL + ' .TellusAlternatingRowColor');
}
Image for DataRows
The object you're using to contact the server, the XMLHttpRequest is part of the Ajax concept. Ajax stands for Asynchronous JavaScript and XML. This means that as soon as the request from the URL passed resolves, the event tied to onreadystatechange will be fired. Should the readyState and status be appropriate, your window calls will be resolved, too.
Being asynchronous, the whole browser won't stop because the server hasn't responded yet, the whole program will continue. You can still press the button because of this, but nothing will happen until that request is responded to. Clicking it again is sending another request to your server, which I'm assuming is also resolved, but your calls on window have happened by this point.

How can I do update with using same id but different content?

Currently, I working on form that got an input for image file. After browse image then upload it I will get the id for the image. Here is my code for POST.
$("#smallpicture_id").change(function () {
displayAndShowImage(this,'#smallimg','#smallimg');
});
$("#largepicture_id").change(function () {
displayAndShowImage(this,'#largeimg','#largeimg');
});
function displayAndShowImage(input,targetHtmlElementName) {
if (input.files && input.files[0]) {
var files = input.files;
var reader = new FileReader();
reader.onload = function (e) {
$(targetHtmlElementName).attr('src', 'images/uploading.gif');
var formData = new FormData();
formData.append('userfile',files[0],files[0].name);
createImage(
config,
formData,
{
onSuccess : function(data) {
$(targetHtmlElementName).attr('src', e.target.result);
$.cookie(input.id, data);
console.log("Image has been save - Received ID: " + data + " saved in the cookie " + input.id);
},
onError : function(jqXHR, status) {
$(targetHtmlElementName).attr('src', 'images/img-error.png');
console.log("ERROR " + jqXHR.responseText + "\r\nstatus = " + status);
}
}
);
}
reader.readAsDataURL(files[0]);
}
}
Ajax
function createImage(cfg,formData,callbacks) {
var xhr = new XMLHttpRequest();
xhr.open('POST', cfg.url + "/image/", true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
callbacks.onSuccess(xhr.responseText.trim());
} else {
callbacks.onError(xhr);
}
};
xhr.send(formData);
}
My question is how can I update / delete for my image with using the same id that given to the image. I already can do POST and GET but I still don't get any idea how to update and delete.
You can append two string in FormData query identifier and ID (only in case of update & delete), like
formData.append('queryType', 'DELETE')
formData.append('imageID', input.id)
On server side code (where you have added code for saving new Image) you have to add condintion like this
<?php
$identifier=$_POST['queryType'];
if($identifier=="NEW") {
//save file with new ID and return ID
} elseif ($identifier=="UPDATE")
//update Image Data ($_FILE) with ID appended in formdata
} elseif ($identifier=="DELETE")
//Delete existing image at ID specified
}
?>
hope this may help.
You can give your elements specific classname for each upload process, which have same id, then run displayAndShowImage function for only elements has "update-this" classname.
$("#smallpicture_id").change(function () {
$(this).addClass("update-this"); // add update-this class
$(".update-this").not($(this)).removeClass("update-this"); // remove all update-this classnames from all other ones
// then run your function for only element which has update-this classname
displayAndShowImage(this,'.update-this');
});

XMLHttpRequest - get value from URL and write it in a div

I have a div called totalvalue.
<div id="totalvalue"></div>
I wrote a function to get value from my PHP script (on the same server).
function totalvalue() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
totalvalue = (ajax5.responseText);
console.log(totalvalue);
document.getElementById("totalvalue").innerHTML = ajax5.responseText;
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
The php script does output a value.
Neither my console nor the div display the output.
This worked for me.
function test5() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
xxx5 = (ajax5.responseText);
console.log("this is the total value: "+xxx5);
if (xxx5 == 0) {
document.getElementById("totalvalue").innerHTML="Loading...";
} else {
document.getElementById("totalvalue").innerHTML="Total: "+xxx5;
}
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
I presume that where I write the div matter + there could have been an issue with the cache. I cannot tell for sure why the above just started working.
For simpler code, and better cross browser support, i would use jQuery.ajax like so:
$.ajax({
url: 'totalvalue.php',
success: function(data){
$('#totalvalue').html(data);
}
});
Read more about it in the documentation

get latitude and longitudefrom city name using HTML,js in bing map

I need to get latitude and longitude by city name using bing map. Here is my code.
function Geocode() {
//Create Bing Maps REST Services request to geocode the address provided by the user
var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
+ "Colombo"
+ "?output=json"
//Set the callback function
+ "&jsonp=GetLocationCoordinates"
+ "&key=Ai5r7K1Jy95BfrDbOV9PPvoBqYicNNe3Bapi7PczGda-l30CjbpHeLnK8XQmYcKl";
//Submit the request
MakeServiceRequest(geocodeRequest);
}
function MakeServiceRequest(request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
GetLocationCoordinates();
}
function GetLocationCoordinates(geocodeResponse) {
if(geocodeResponse==null) document.getElementById("txt").innerText = "This is null";
if (geocodeResponse &&
geocodeResponse.resourceSets &&
geocodeResponse.resourceSets.length > 0 &&
geocodeResponse.resourceSets[0].resources &&
geocodeResponse.resourceSets[0].resources.length > 0) {
setLoc(geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[0], geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[1], 10);
}
else {//The location could not be geocoded
var md = new Windows.UI.Popups.MessageDialog("The location could not be geocoded");
md.showAsync();
}
}
But in here it never called function GetLocationCoordinates(geocodeResponse). How can I make to call it.?
Probably because you are running this from the local context. Create an iframe and add the code in that resulting html file.
I've wrapped the code in a namespace. This way you can define where the function will be called rather than sticking your functions in the global namespace. Note I commented out your direct call of the function, its not needed.
Create a /pages/map/map.html, map.js, map.css (in other words, create a /pages/map and right click on it and select add new item and choose 'page' type named map)
In map.js include the following after 'use strict', or include in another javascript file. It's up to you.
WinJS.Namespace.define("LocationServices", {
GetLocationCoordinates: function (geocodeResponse) {
if (geocodeResponse == null) document.getElementById("txt").innerText = "This is null";
if (geocodeResponse &&
geocodeResponse.resourceSets &&
geocodeResponse.resourceSets.length > 0 &&
geocodeResponse.resourceSets[0].resources &&
geocodeResponse.resourceSets[0].resources.length > 0) {
setLoc(geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[0], geocodeResponse.resourceSets[0].resources[0].geocodePoints.coordinates[1], 10);
}
else {//The location could not be geocoded
var md = new Windows.UI.Popups.MessageDialog("The location could not be geocoded");
md.showAsync();
}
},
Geocode: function () {
//Create Bing Maps REST Services request to geocode the address provided by the user
var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
+ "Colombo"
+ "?output=json"
//Set the callback function
+ "&jsonp=LocationServices.GetLocationCoordinates"
+ "&key=Ai5r7K1Jy95BfrDbOV9PPvoBqYicNNe3Bapi7PczGda-l30CjbpHeLnK8XQmYcKl";
//Submit the request
this.MakeServiceRequest(geocodeRequest);
},
MakeServiceRequest: function (request) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request);
document.body.appendChild(script);
// GetLocationCoordinates();
}
});
In turn load map.html (which includes a reference to map.js and has your input id='txt')
<iframe src="ms-appx-web:///pages/map/map.html"></iframe>

xhr response: connection closed

I wrote a Flickr search engine that makes a call to either a public feed or a FlickrApi depending on a selected drop down box.
examples of the JSONP function calls that are returned:
a) jsonFlickrApi({"photos":{"page":1, "pages":201, "perpage":100, "total":"20042", "photo":[{"id":"5101738723"...
b) jsonFlickrFeed({ "title": "Recent Uploads tagged red","link": "http://www.flickr.com/photos/tags/red/","description": "", ....
the strange thing is that in my local install (xampp) both work fine and i get images back BUT when i host the exact same code on the above domain then the jsonFlickrApi doesn't work. What i notice (by looking at Firebug) is that for the jsonFlickrApi the response Header says Connection close
Also, Firebug doesn't show me a Response tab when i submit a request to the jsonFlickrApi
here is the code:
function makeCall(uri)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "jsonget.php?url="+uri, true);
xmlhttp.send();
}
function jsonFlickrApi(response)
{
var data= response.photos.photo ;
var output = "";
output += "<img src=http://farm" + data[4].farm + ".static.flickr.com/" + data[1].server + "/" + data[4].id + "_" + data[4].secret + ".jpg>";
document.getElementById("cell-0").innerHTML = output ;
}
//Public Feed
function jsonFlickrFeed(response)
{
var data= response.items[0].media.m ;
alert(data);
var output = "";
output += "<img src=" + data+ ">";
document.getElementById("cell-0").innerHTML = output ;
}
function callback()
{
//console.log("Ready State: " + xmlhttp.readyState + "\nStatus" + xmlhttp.status);
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonResponse = xmlhttp.responseText;
jsonResponse = eval(jsonResponse);
}
}
examples of calls:
a)
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
b)
http://api.flickr.com/services/feeds/photos_public.gne?tags=red&format=json&timestamp=1339190039407
Question: why does my connection close? why is it working on localhost and not on the actual domain?
Looking at the HTTP response headers of
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
I get a 302 with location
http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
So, what flicker wants to tell you is "use www.flicker.com instead of flicker.com!". With this URL I get content.

Categories

Resources