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]);
}
});
}
Related
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;
}
I've two xml files, one category & second products. I need to print a Tree Structure where products within same category should be printed together.
Like this:
1. Food
a. Milk
b. Cheese
I've following code in my file which doesn't work; it doesn't print anything.
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "categories.xml",
dataType: "xml",
success: function(xml) {
var categories= new Array();;
$(xml).find('Categories').each(function(){
var id = $(this).find('CategoryID').text();
var title = $(this).find('CategoryName').text();
var desc = $(this).find('Description').text();
for(i=0;i<=20;i++){
categories[i]=new Array();
categories[i][0]= id;
categories[i][1]= title;
categories[i][2]= desc;
}
});
}
});
$.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;
}
});
}
});
});
for(k=0;k<20;k++){
if(categories[k][0]!=""){
$('#category').append("<div>"+categories[k][1]+"</div>");
for(l=0;l<20;l++){
if(categories[k][0]==products[l][2]){
$('#category').append("<div style='margin-left:10px;'>"+products[l][1]+"</div>");
}
}
}
}
</script>
What I do is store the array for categories & for products, then loop through all arrays, find products through category id. But it doesn't work, it doesn't print anything. Can anyone help?
XML Files
categories.xml
<CategoriesRoot>
<Categories>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beer, and ale</Description>
</Categories>
<Categories>
<CategoryID>2</CategoryID>
<CategoryName>Condiments</CategoryName>
<Description>
Sweet and savory sauces, relishes, spreads, and seasonings
</Description>
</Categories>
<Categories>
<CategoryID>3</CategoryID>
<CategoryName>Confections</CategoryName>
<Description>Desserts, candies, sweetbreads</Description>
</Categories>
<Categories>
<CategoryID>4</CategoryID>
<CategoryName>Dairy Products</CategoryName>
<Description>Cheeses</Description>
</Categories>
<Categories>
<CategoryID>5</CategoryID>
<CategoryName>Grains/Cereals</CategoryName>
<Description>Breads, crackers, pasta, and cereal</Description>
</Categories>
<Categories>
<CategoryID>6</CategoryID>
<CategoryName>Meat/Poultry</CategoryName>
<Description>Prepared meats</Description>
</Categories>
<Categories>
<CategoryID>7</CategoryID>
<CategoryName>Produce</CategoryName>
<Description>Dried fruit and bean curd</Description>
</Categories>
<Categories>
<CategoryID>8</CategoryID>
<CategoryName>Seafood</CategoryName>
<Description>Seaweed and fish</Description>
</Categories>
</CategoriesRoot>
products.xml
<ProductsRoot>
<Products>
<ProductID>1</ProductID>
<ProductName>Chai</ProductName>
<CategoryID>1</CategoryID>
<QuantityPerUnit>10 boxes x 20 bags</QuantityPerUnit>
<UnitPrice>18</UnitPrice>
</Products>
<Products>
<ProductID>2</ProductID>
<ProductName>Chang</ProductName>
<CategoryID>1</CategoryID>
<QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit>
<UnitPrice>19</UnitPrice>
</Products>
<Products>
<ProductID>3</ProductID>
<ProductName>Aniseed Syrup</ProductName>
<CategoryID>2</CategoryID>
<QuantityPerUnit>12 - 550 ml bottles</QuantityPerUnit>
<UnitPrice>10</UnitPrice>
</Products>
</ProductsRoot>
Your variables are scoped within your ajax success calls. Are you not getting errors? And since the ajax calls are asynchronous, you have to make sure both categories and products have returned.
As soon as each success function of the ajax requests ends, the categories and products variables die. They are undefined in the for loop where you access them. We need to scope them outside the ajax calls, and then ensure both ajax requests have returned before we run our loop.
$(document).ready(function(){
var categories = [];
var products = [];
var callbacks = 0;
$.ajax({
type: "POST",
url: "categories.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Categories').each(function(){
var id = $(this).find('CategoryID').text();
var title = $(this).find('CategoryName').text();
var desc = $(this).find('Description').text();
var category = new Array();
category.push(id);
category.push(title);
category.push(desc);
categories.push(category);
});
callback();
}
});
$.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 product = new Array();
product.push(proid);
product.push(proname);
product.push(catid);
product.push(qua);
product.push(price);
products.push(product);
});
callback();
}
});
function callback() {
if(++callbacks < 2) return;
for(var k=0;k<categories.length;k++){
if(categories[k][0]!=""){
$('#category').append("<div>"+categories[k][1]+"</div>");
for(var l=0;l<products.length;l++){
if(categories[k][0]==products[l][2]){
$('#category').append("<div style='margin-left:10px;'>"+products[l][1]+"</div>");
}
}
}
}
}
});
Ajax are asynchronous and you can not wait javascript to get response. so you will need to perform rest of operation in the response callback function. pl check the below code.
Action method should be GET as you not posting anything to xml file.
You dont need to iterate for loop in jQuery each method as each itself is a loop
use .length property of Array instead of hard coded 20 in forloop
$(document).ready(function(){
$.ajax({
type: "GET",
url: "categories.xml",
dataType: "xml",
success: function(xml) {
var categories= new Array();
$(xml).find('Categories').each(function(i){
var id = $(this).find('CategoryID').text();
var title = $(this).find('CategoryName').text();
var desc = $(this).find('Description').text();
categories[i]=new Array();
categories[i][0]= id;
categories[i][1]= title;
categories[i][2]= desc;
});
$.ajax({
type: "GET",
url: "products.xml",
dataType: "xml",
success: function(xml) {
var products = new Array();
$(xml).find('Products').each(function(j){
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();
products[j]=new Array();
products[j][0]= proid;
products[j][1]= proname;
products[j][2]= catid;
products[j][3]= qua;
products[j][4]= price;
});
for(k=0;k<categories.length;k++){
if(categories[k][0]!=""){
$('#category').append("<div>"+categories[k][1]+"</div>");
for(l=0;l<products.length;l++){
if(categories[k][0]==products[l][2]){
$('#category').append("<div style='margin-left:10px;'>"+products[l][1]+"</div>");
}
}
}
}
}
});
}
});
});
folks
we are facing a strange issue with jquery ( 1.8.3) and we are using cakePHP
as per the image
Our assumption is we are sending the data( about 500 +) with ajax call in POST method.
we are having this issue in all the major browsers.
as above( in chrome) , we are getting this error in console we passed 618 destinations in ajax call.
let us know the work around to solve this problem.
My ajax call is as below
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/" + ele +"/"+ ele2 +"/"+ $("#destination").val();
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
In your JQuery Ajax method instead of posting all those details as url query para meter send by wrapping those details in a object.
function validate_test() {
$("#btn1").empty();
var ele = document.getElementById('frm_searchDateFrom').value;
var ele2 = document.getElementById('frm_searchDateTo').value;
var sub_url = '<?php echo $this->Html->url('/', true); ?>';
var url = sub_url + "admin/reports/check_originator/";
var formdata=ele +"/"+ ele2 +"/"+ $("#destination").val();//put form data's in an object
alert(url);
jQuery.ajax({
type: "POST",
datatype: "json",
data:formdata,//send the form data object in post
url: url,
success: function(data)
{
var el = $("select#btn1").multiselect();
var d;
var results=data.split(",");
for(d=0;d<results.length;d++) {
var d;
var v = results[d], opt = $('<option />', {
value: v,
text: v
});
opt.appendTo( el );
el.multiselect('refresh');
}
}
})
}
Also refer this fiddle(not mine):
http://jsfiddle.net/clickthelink/Uwcuz/1/
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);
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'];