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>");
}
}
}
}
}
});
}
});
});
Related
This is my alert output result:
The above picture array is my result that is get from table using ajax request.but i don't know how to use in for loop and i have tired in for loop the value is splitted one by one like
My code
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
alert(data);
var result = data;
var arr = result;
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
}
});
});
</script>
You can modify your script like this and then do whatever Logic you want for the response
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
myGoodFunctionToHandleResponse(data);
}
});
});
function myGoodFunctionToHandleResponse(data){
for(let i in data){
console.log(data[i]);
}
}
I have forgot to put JSON.parse() this function after success function and so i didn't get the correct result so far.
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
var result = JSON.parse(data)
var mycars = result;
for (i in mycars)
{
if( mycars[i].dc == "C"){
var credit = mycars[i].Amt;
}
else{
var debit = mycars[i].Amt;
}
if(credit > debit)
{
var bal = credit - debit;
}
else{
var bal = debit - credit;
}
}
$('#bal').val(bal);
}
});
});
</script>
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]);
}
});
}
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'm using cascading drop down lists in my MVC application, and it works fine.
I have added the jQuery mobile library to make it look better in mobile devices browser and I have kind of bug.
An example:
if I choose first time Chevrolet it populate child drop down with Chevrolet models. - as expected
if I choose second time another make I still see the models from previous make, but if I select it I see the new model. It looks like it cashing the models from previous make.
Here is my code:
$(document).ready(function () {
$('select#Makes').change(function () {
getModels();
});
});
function getModels() {
var make = $('#Makes').val();
var myselect2 = $("select#Models");
myselect2[0].selectedIndex = 3;
myselect2.selectmenu("refresh");
$.ajax({
type: "POST",
url: "/Services/CarService.asmx/Models",
data: "{makeId: '" + make + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var models = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#Models').attr('disabled', false).removeOption(/./); //.addOption('', ' -- Select Model -- ');
var select = document.getElementById("Models");
for (var i = 0; i < models.length; i++) {
var val = models[i];
var text = models[i];
$('select#Models').addOption(val, text, true);
}
var myselect = $("select#Models");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
}
});
}
#Html.DropDownList("Makes", "Please select make")
#Html.DropDownListFor(x => x.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "value", "text"), "Select a Model", new { id = "Models" })
here is the code I'm using:
$(function() {
$(".fav").click(function() {
var page = $('#page').attr('value');
var user = $('#user').attr('value');
var time = $('#time').attr('value');
var info = "page="+ page +"& user="+ user +"& time="+ time;
$("#loading").html('<im g src="loader.gif" />');
$.ajax({
type: "POST",
url: "favorite.php",
data: info,
success: function() {
$("#loading").ajaxComplete(function(){}).slideUp();
$('#fav').fadeOut(200).hide();
$('#unfav').fadeIn(200).show();
}
});
return false;
});
});
</script>
<script type="text/javascript" >
$(function() {
$(".unfav").click(function(){
var page = $('#page').attr('value');
var user = $('#user').attr('value');
var info = "page="+ page +"& user="+ user;
$("#loading").html('<im g src="loader.gif" />');
$.ajax({
type: "POST",
url: "notfavorite.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#unfav').fadeOut(200).hide();
$('#fav').fadeIn(200).show();
}
});
return false;
});
});
Everything is working fine, it acts as a "like" "follow" button, the only problem is that the ajaxComplete() function only runs once.
Cheers!
$(function(){
$(".fav").click(function(){
var page = $('#page').attr('value');
var user = $('#user').attr('value');
var time = $('#time').attr('value');
var info = "page="+ page +"& user="+ user +"& time="+ time;
$("#loading").html('<im g src="loader.gif" />');
$('#follow').hide();
$.ajax({
type: "POST",
url: "favorite.php",
data: info,
success: function(){
$('#loading').empty();
$('#remove').fadeIn(200).show();
}
});
return false;
});
})();
same for .unfav