Reduce Repetitiion with AJAX JSON Calls to an API - ajax

I have about 15 copies of the following code on my site. The only things changing are the url, longitude, latitude, and the marker variable title. How can I chop this up and reduce the repetition?
$.ajax({
url: "http://api.wunderground.com/api/<api_key>/conditions/q/pws:KCASANFR128.json",
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['current_observation']['observation_location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather = parsed_json['current_observation']['weather'].toLowerCase();
var iconUrl = parsed_json['current_observation']['icon_url'];
var iconPic = new MyIcon(iconUrl);
var markerRichmond = new L.Marker(new L.LatLng(37.779806, -122.471895), {icon: iconPic});
markerRichmond.bindPopup("Current temperature in " +location+ " is: " +temp_f+ " and it is " + weather);
map.addLayer(markerRichmond);
}});

You could make a function which takes in those variables and feeds them to the ajax call. Then you would only need one copy of this ajax block, which you could call by calling the getWeather function
function getWeather(url, lat, long, title){
$.ajax({
url: url,
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['current_observation']['observation_location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather = parsed_json['current_observation']['weather'].toLowerCase();
var iconUrl = parsed_json['current_observation']['icon_url'];
var iconPic = new MyIcon(iconUrl);
var markerRichmond = new L.Marker(new L.LatLng(lat, long), {icon: iconPic});
markerRichmond.bindPopup(title);
map.addLayer(markerRichmond);
}
});
}
I am not sure if I handled the title correctly here, but you get the idea. If you give an idea of how the title may change, I can fix the code accordingly.
Hope this helps.

var current_observation = parsed_json['current_observation'];
This also shortens amount of times parsed. Then you can refer to your variable as
current_observation['observation_location']['city'];

Related

Ajax inside ajax not working

I have a function that calls an ajax, inside that ajax another ajax needs to be executed. In the below code I gave my full function. Just to ensure that everything but the 2nd ajax works perfectly, I should point you out that before the 2nd ajax call there is an alert() function which works. That means everything works if I comment the 2nd ajax call. If I uncomment it then after the first alert a second alert should appear saying 'inside 2nd call', but nothing happens. Got any suggestions?
function get_employee_list(Parameter){
$.ajax({
url: 'resource/php/search_profile.php',
type: 'POST',
data: { var1 : Parameter},
async: false,
success: function (response) {
//alert(response);
reset_search_table();
$(response).find('employee').each(function() {
var ebasp_id = $(this).find('ebasp_id').text();
var ebasp_name = $(this).find('ebasp_name').text();
var ebasp_gender = $(this).find('ebasp_gender').text();
var ebasp_category = $(this).find('ebasp_category').text();
//var ebasp_region_type = $(this).find('ebasp_region_type').text();
//var ebasp_region_name = $(this).find('ebasp_region_name').text();
var code_sub_region = $(this).find('ebasp_sub_region').text();
var code_location = $(this).find('ebasp_location').text();
var code_office = '';
if (code_location === '0')
code_office = code_sub_region;
else
code_office = code_location;
var office = '';
//alert('before 2nd call -- '+code_office);
$.ajax({
url: 'resource/php/show_cost_center_name.php',
type: POST,
data: { var1 : code_office},
success: function(response){
office = response;
alert('inside 2nd call');
}
});
var ebasp_designation = $(this).find('ebasp_designation').text();
var ebasp_date_of_joining = $(this).find('ebasp_date_of_joining').text();
var ebasp_grade = $(this).find('ebasp_grade').text();
var ebasp_slab = $(this).find('ebasp_slab').text();
var ebasp_basic = $(this).find('ebasp_basic').text();
var ebasp_photo_upload = $(this).find('ebasp_photo_upload').text();
var ebasp_created_on = $(this).find('ebasp_created_on').text();
var ebasp_created_by = $(this).find('ebasp_created_by').text();
$("#search_table").show();
$('<tr></tr>').html('<td>'+ebasp_id+'</td>'+
'<td>'+ebasp_name+'</td>'+
'<td>'+ebasp_gender+'</td>'+
'<td>'+ebasp_category+'</td>'+
'<td>'+office+'</td>'+
'<td>'+ebasp_designation+'</td>'+
'<td>'+ebasp_date_of_joining+'</td>'+
'<td>'+ebasp_grade+'</td>'+
'<td>'+ebasp_slab+'</td>'+
'<td>'+ebasp_basic+'</td>'+
'<td>'+ebasp_created_on+'</td>'+
'<td>'+ebasp_created_by+'</td>').appendTo("#search_table");
});
},
cache: false,
});return false;
}

Store data to array coming from XML file in ajax request

I have one XML file from which I need to get data & store them in an array. Somehow array is not being created expectedly. I've used each function to loop through the xml file.
Here's my code:
AJAX Request
$.ajax({
type: "POST",
url: "products.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Products').each(function(){
var proid = $(this).find('ProductID').text();
var proname = $(this).find('ProductName').text();
var catid = $(this).find('CategoryID').text();
var qua=$(this).find('QuantityPerUnit').text();
var price=$(this).find('UnitPrice').text();
var products = new Array();
for(i=0;i<=20;i++){
products[i]=new Array();
products[i][0]= proid;
products[i][1]= proname;
products[i][2]= catid;
products[i][3]= qua;
products[i][4]= price;
}
});
}
alert(products[0][2]); // Nothing happens
});
Sample of XML File
<ProductsRoot>
<Products>
<ProductID>1</ProductID>
<ProductName>Chai</ProductName>
<CategoryID>1</CategoryID>
<QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit>
<UnitPrice>18</UnitPrice>
</Products>
</ProductsRoot>
When I loop through each function, I expect it to work like for loop but something's that I can not see. Can anyone spot the mistake? Your help will be greatly appreciated.
Try this:
$.ajax({
type: "POST",
url: "products.xml",
dataType: "xml",
success: function(xml) {
var products = new Array();
$(xml).find('Products').each(function(){
var proid = $(this).find('ProductID').text();
var proname = $(this).find('ProductName').text();
var catid = $(this).find('CategoryID').text();
var qua=$(this).find('QuantityPerUnit').text();
var price=$(this).find('UnitPrice').text();
for(i=0;i<=20;i++){
products[i]=new Array();
products[i][0]= proid;
products[i][1]= proname;
products[i][2]= catid;
products[i][3]= qua;
products[i][4]= price;
}
});
alert(products[0][2]);
}
});
}

Alert an array value that results from an AJAX call

I am having some difficulty trying to alert a value which is the result of an ajax call. The code below is working to the extent that grid.onClick will alert the value of row, but for the life of me I cannot figure out how to alert the value of latitude and/or longitude.
function showGridSalesResult(){
var data = [];
var r_from = $('#min_val').val();
var r_to = $('#max_val').val();
var p_from = $('#from_year').val();
var p_to = $('#to_year').val();
var type = $('#sf3').val();
var municipality = $('#SaleCity').val();
$(document).ready(function(){
jqXHR = $.ajax({
url: sURL + "search/ajaxSearchResult",
type: "POST",
data: 'r_from='+r_from+'&r_to='+r_to+'&p_from='+p_from+'&p_to='+p_to+'&type='+type+'&up_limit='+up_limit+'&low_limit='+low_limit+'&municipality='+municipality,
dataType: 'json',
success: function(json){
$.each(json, function(i,row){
data[i] = {
address: row.Address,
municipality: row.Municipality,
geoencoded: row.geoencoded,
latitude: parseFloat(row.geolat),
longitude: parseFloat(row.geolong)
};
});
grid = new Slick.Grid("#myGridMap", data, columns, options);
grid.invalidate();
grid.render();
grid.resizeCanvas();
grid.onClick = function (e, row, cell){
alert(row); // THIS WORKS
alert(data[row].latitude); // THIS DOES NOT WORK
}
setMarkers(map, data);
}
});
});
}
Can someone please help me to figure out how I can alert the latitude and longitude values?
Checking the documentation :
https://github.com/mleibman/SlickGrid/wiki/Slick.Grid#wiki-getCellFromEvent
you should use :
var cell = grid.getCellFromEvent(e);
var latitude = data[cell.row].latitude;
alert(latitude);

Ajax response and anonymous function scope

In the following code
var entryTemplate = document.getElementById('entryTemplate');
entryTemplate = entryTemplate.firstChild;
for (var ipost in posts)
{
var post = posts[ipost];
var clone = entryTemplate.cloneNode(true);
clone = $(clone);
if (post.imageURL)
{
var imgElement = document.createElement('img');
var largeImageURL = post.largeImageURL ? post.largeImageURL : post.imageURL;
imgElement.src = post.thumbPresent ? POST_THUMB_URL + '/' + post.postID : largeImageURL;
imgElement.alt = '';
clone.find('div.BlogImageURL a').attr('href', largeImageURL).text(largeImageURL);
clone.find('div.BlogImage a').attr('href', imgElement.src).append(imgElement);
// get bytesize
var postdata = 'inline_image_url=' + encodeURIComponent(post.imageURL);
postdata += '&linked_image_url=' + encodeURIComponent(post.largeImageURL);
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
success: function(bytesize) {
clone.find('.BlogImageBytesize').html(bytesize);
}
});
}
else
{
clone.find('div.BlogImageURL').text('(This post contains no images)');
clone.find('div.BlogImage').remove();
}
$('#outputDiv').append(clone);
}
clone.find('.BlogImageBytesize').html(bytesize);
All ajax responses (bold line) modify the last clone, probably because the loop is finished when the first response arrives and clone points to the last clone.
How can I fix this?
Thanks.
Perhaps you could set clone as the context of your ajax call. (See docs here.) Then, I think it would work something like this:
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
context: clone,
success: function(bytesize) {
$(this).find('.BlogImageBytesize').html(bytesize);
}
});
I don't know for sure if the context has to be a plain DOM element or if it can be a jQuery object, but hopefully this gets you on the right track.

google maps call within a For Loop not returning distance

I am calling google maps within a for loop in my javascript as I have mulitple routes that need to be costed separately based on distances.
Everything works great except that the distance is only returned for one of the routes.
I have a feeling that it is something to do with the way I have the items declared within the ajax call for the maps. Any ideas what could be the issue from the code below?
for (var i = 1; i <= numJourneys; i++) {
var mapContainer = 'directionsMap' + i;
var directionContainer = $('#getDistance' + i);
$.ajax({
async: false,
type: "POST",
url: "Journey/LoadWayPoints",
data: "{'args': '" + i + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '[]') {
var map = new GMap2(document.getElementById(mapContainer));
var distance = directionContainer;
var wp = new Array();
//routes
var counter = 0;
$.each(content, function () {
wp[counter] = new GLatLng(this['Lat'], this['Long']);
counter = counter + 1;
});
map.clearOverlays();
map.setCenter(wp[0], 14);
// load directions
directions = new GDirections(map);
GEvent.addListener(directions, "load", function () {
alert(directions.getDistance());
//directionContainer.html(directions.getDistance().html);
});
directions.loadFromWaypoints(wp, { getSteps: true });
}
}
});
}
The issue was down to a non declared variable. Just before the GEvent call there is a variable called 'directions' but this was never actually declared with a var so it wasn't being cleared out.
var directions = new GDirections(map);
Doing the above worked for me.

Resources