Create List of Items in Jquery - javascript

I am working on VS 2013 Cordova App . I want to create new list of items by jquery . here is my Html code :
<div class="body" >
<ul class="list list-messages" id="list">
</ul>
</div>
And here is my js code :
<script>
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
$("#list").empty();
for (var i = 0; i < data.length; i++) {
$("#list").append('<li class="list-message" data-ix="list-item"><a class="w-clearfix w-inline-block" href="chat.html" data-load="1"><div class="w-clearfix column-left"><div class="image-message"><img src="images/128.jpg"></div></div><div class="column-right"><div class="message-title">James White</div><div class="message-text">Hey dude! We are waiting for you at the main station, we will meet you near to....</div></div></a></li>');
}
}
});
});
</script>
But it dosen't work with me , Please advice

For starters you have two #list ids, try removing the id from the div.
You should never had two id's the same.
Furthermore, change the append and empty to the class ".list" and remove both ID's

Related

Sort list items loaded after ajax call using jquery

Consider 2 files:
File 1 - list.html
<ul>
<li>Dog</li>
<li>Ant</li>
<li>Cat</li>
</ul>
File 2 - ajax.html
<html>
<body>
<button type="button">Click</button>
<ul id="list">
</ul>
<script type="text/javascript">
$("button").click(function() {
$("#list").load("list.html ul > li");
});
</script>
</body>
</html>
Here file 1 contain list of items and file 2 load file 1's li tag list items to file 2's ul tag. After ajax call, how can we sort the loaded list alphabetically before it is displayed on the screen. I wanted to sort only after ajax call. Please help me.
To do this you can provide a function to the callback argument of load() which is executed after the AJAX request completes and the new content has been added to the DOM. Try this:
$("button").click(function() {
let $list = $("#list").load("list.html ul > li", function() {
$list.find('li').sort((a, b) => a.innerText < b.innerText ? -1 : 1).appendTo($list);
});
});
You can do this inside the ajax success callback function. Also, you can user JS .sort() for sorting the names. This is a simple ajax call. You can add more properties based on your need. let's assume the result variable contains the names which you want to add:
$('#myButton').click(function(){
$.ajax({
url : 'Your_server_url',
success: function(result){
result.sort()
for (i = 0; i < result.length; i++) {
$('#list').append("<li>" + result[i] + "</li>")
}
},
error: function (xhr, status) {
console.info("cannot update list!");
}
});
});
<html>
<body>
<button type="button" id="myButton">Click</button>
<ul id="list">
</ul>
</body>
</html>

Javascript - make a list with bootstrap media objects

What would be the best way to create a list with bootstrap media objects with javascript.
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="..." alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Media heading</h4>
...
</div>
</div>
I am fetching json data from an api endpoint and was thinking of making something like in this example, or using maybe some templating engine. So, I wonder how would I do this here and if it would look messy with creating all the elements necessary for bootstrap media object component?
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
First of all, you need to clarify how you are planning to handle the data inside media object. What i mean is,
Are you going to get the data from a database or a JSON file or sth?
Which proggramming language are you using? PHP, ASP, Python... or None
Do you have to do this with JavaScript, because it can be achieved with any other languages
In order to create an array of something, you should define that something first.
Here is a starting point for you:
First create an empty div with an id eg: #yourContainerID
Then create a new js file, and don't forget to give referance to that file.
And put these code inside that JS file
$( document ).ready(function() {
$.ajax({
type : 'post',
url: 'yourFile.json', //Here you will fetch records
dataType: 'json',
success: function(data) {
var mediaData; // Here you create data to put into container
mediaData = '';
for(var i = 0; i < data.length; i++){
mediaData += '<div class="media">';
mediaData += '<div class="media-left">';
...
mediaData += data.yourData // Your data
...
mediaData += '</div>' // You close divs
}
$('#yourContainerID').html(mediaData);
}
});
});
Since I don't have a clue on your data structure, this is just for demo. You have to edit the code for your needs.

Jquery AJAX id selector and post with change class

I have one question. I am trying to make a ajax post with id and also trying to change the class which data-id selected.
I have created this DEMO from codepen.io
In this demo you can see there is a two container div and the container divs inside some different color div.
So what i am trying to do. When i click .change_pri then that clicked (.style, style1, style2) will automatically change .type style like:
<div class="test" id="1">
<div class="type style">selected color</div> <-- class is style
<div class="select_types">
<div class="type_s"><div class="change_pri style" data-id="0">0</div></div>
<div class="type_s"><div class="change_pri style1" data-id="1">1</div></div>
<div class="type_s"><div class="change_pri style2" data-id="2">2</div></div>
</div>
</div>
after clicking change_pri style2 then it need to looks like this:
<div class="test" id="1">
<div class="type style2">selected color</div> <-- after clicking class is style2
<div class="select_types">
<div class="type_s"><div class="change_pri style" data-id="0">0</div></div>
<div class="type_s"><div class="change_pri style1" data-id="1">1</div></div>
<div class="type_s"><div class="change_pri style2" data-id="2">2</div></div>
</div>
</div>
and post the data-id with ajax.
I do not know how the rest of that section, but I was able to do so. Anyone can help me in this regard ?
$(function() {
var i;
i = $(this).attr('id');
});
$('.change_pri').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "chage_number.php",
data: {
id: i,
},
});
});
The Javascript with the AJAX request should probably look something like this:
$('.change_pri').click(function(){
var dataid = $(this).attr('data-id');
var id = $(this).closest('.test').attr('id');
$.ajax({
type: "POST",
url: "chage_number.php",
data: { dataid : dataid, id: id }
}).success(function(result){
alert(result);
});
});
And then depending on what you want to do back-end, you can access that variable in chage_number.php via $_POST['id'].
So a simple example would be
chage_number.php
echo $_POST['id'] . ", ". $_POST['dataid'];
This should alert() both ids.
you can try this..
$('.change_pri').on('click', function(e) {
var styletype = $(this).attr('class').split(' ')[1];
var ctoremove = $('.type').attr('class').split(' ')[1];
$('.type').removeClass(ctoremove).addClass(styletype);
$.ajax({
type: "POST",
url: "chage_number.php",
data: { id: i }
}).success(function(result){
alert(result);
});
});
and here is the FIDDLE
I take it as the second container should be an example of what happens clicking the div's of the first one.
See this working example, it should do what you asked for: http://codepen.io/anon/pen/qdxVzW
This is where you get an alert telling you which data-id you clicked and then it changes the class of the .type element
alert($(this).attr('data-id')); //this can be removed, it's just a test
$('#test-1 > .type') //remove styleN and add the needed one
.removeClass('style0')
.removeClass('style1')
.removeClass('style2')
.addClass('style'+$(this).attr('data-id'))
The part about the ajax call remains almost the same, with a little modification when it comes to setting the id to be sent:
$('.change_pri').on('click', function(e) {
//As suggested by #Mackan, a little modification: store data-id
var dataId = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "chage_number.php",
data: {
id: dataId //send the correct id
}
});
});
The function at the beginning of the script can be safely removed, it doesn't affect the rest of the code :)
I was almost forgetting: add a 0 to the style which doesn't have a number, like:
<div class="change_pri style0" data-id="0">0</div></div>
Otherwise when it come's to data-id=0 the script doesn't know what to do. Of course, same thing should be done into css code:
.style0{
background-color:red;
color:#ffffff;
margin:5px;
}

too much HTML in an ajax script?

I read from this page that appending a lot of elements is bad practice and I should build up a string during each iteration of the loop and then set the HTML of the DOM element to that string. Does the same go for using too much HTML in the loop?
I have an AJAX script that parses JSON data. It requires adding data to different existing elements, like this:
$.ajax({
url: "url",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(''+ingredient+'')
$('.'+ title+'_age').html(''+age+'')
$('.'+ title+'_background').html(''+background+'')
});
},
error: function () {}
});
HTML:
<div class="A_ingredient"></div>
<div class="B_ingredient"></div>
<div class="C_ingredient"></div>
<div class="D_ingredient"></div>
<div class="A_age"></div>
<div class="B_age"></div>
<div class="C_age"></div>
<div class="D_age"></div>
<div class="A_background"></div>
<div class="B_background"></div>
<div class="C_background"></div>
<div class="D_background"></div>
Is it necessary to build up a string first? If so, can you show me how to do that?
It is purely about the time it takes to process calls to html() so they simply recommend you reduce the number of calls. In this case you could build them once in a loop then sets the div html once for each.
Update:
Based on your update, aside from all the extra trailing quotes you don't need to add (a string is a string is a string), your code is fine as is. You only hit each item once.
e.g.
$.ajax({
url: "url",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title, // A,B,C or D
age = item.age,
background = item.background,
ingredient = item.Ingredient;
$('.'+ title+'_ingredient').html(ingredient);
$('.'+ title+'_age').html(age);
$('.'+ title+'_background').html(background);
});
},
error: function () {}
});
Note: If your item properties (Age, Background, Ingredient) are simple values (not objects or arrays), yo do not need the leading ''+s either.
Previous
Assuming you actually want to concatenate the results (you are only keeping the last ingredient at the moment), you could do something like this:
e.g.
$.ajax({
url: "url",
success: function (data) {
var ingredients = '';
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var ingredient = item.Ingredient;
ingredients += ingredient;
});
$('.aclass').html(ingredients);
$('.bclass').html(ingredients);
$('.cclass').html(ingredients);
$('.dclass').html(ingredients);
},
error: function () {}
});
Which can be reduced to:
$('.aclass,.bclass,.cclass,.dclass').html(ingredients);
The contents of each div are identical in your example, so you only need a single string.
In this instance you would probably need some form of delimiter between ingredients, but your example is too vague.
e.g.
ingredients += ingredient + '<br/>';
In your example, you're setting the HTML on many different document elements.
If they're grouped in some way, for example all in a Div with ID #Container, you could build a string of the HTML and set the content of the whole Div at the end of it, something like this:
$.ajax({
url: "url",
success: function (data) {
var sHTML="";
$(data.query.results.json.json).each(function (index, item) {
var title = item.title,
background = item.background,
ingredient = item.Ingredient;
// not sure what your actual HTML is (div/span/td etc) but somethign like this?
sHTML+="<div>"; // an opening container for this item
sHTML+='<div class="'+title+'_ingredient">'+ingredient+'</div>')
sHTML+='<div class="'+title+'_age">'+title+'</div>')
sHTML+='<div class="'+title+'_background">'+background+'</div>')
sHTML+="</div>";
});
$("#Container").html(sHTML);
},
error: function () {}
});
Note I haven't tested this code, but you see the principal hopefully.
That is, build a string of the HTML then set one element at the end with the content.
I have done this a lot in a recent project and haven't seen any speed issues (maybe 50 'items' to set in my case).
HTML will initially look like this :
<div id="container">
</div>
Then end up like this (2 x items in this example) :
<div id="container">
<div>
<div class="<sometitle1>_ingredient">ingredient 1</div>
<div class="<sometitle1>_age">age 1</div>
<div class="<sometitle1>_background">background 1</div>
</div>
<div>
<div class="<sometitle2>_ingredient">ingredient 2</div>
<div class="<sometitle2>_age">age 2</div>
<div class="<sometitle2>_background">background 2</div>
</div>
</div>
subsequent calls will replace the element's content with new values, replacing the old items.
Building a string is, I would imagine, less processor-heavy than setting the html() on lots of elements individually. Each time you use html() I'm guessing that the browser has to go some way towards working out any knock-on effects like expanding the width of an element to accomodate it or whether events will still work as they did, etc - even if actual rendering is only run at the end of the process. This way you use html() once, although what you're setting is more complex.
Hope this helps.

parse output and style xml data

I have xml located on a remote server with the following format:
<query_results>
<row id="1">
<distance>...</distance>
<post_title>...</post_title>
<post_excerpt>...</post_excerpt>
<ID>...</ID>
</row
<row id="2">
.........................etc
</query_results>
I need my javascript to go through each of these rows in a way so that I can append each to a div on my html document with a class for styling without the script caring too much what the individual names are for each element in each row. I have used Jquery's parse XML function, however i am lost after that. Anybody got a good idea how to do this? Any help is appreciated a lot.
I made a JSFiddle with a possible solution to your problem. It loads your sample XML from this Gist.
In the HTML there is a placeholder:
<div id="query_results"/>
You can load the file using JQuery ajax:
$.ajax({
type: "GET",
url: "/url/to/your/file.xml",
dataType: "xml",
success: parser
});
In the parser function you can use .find() and .children() to navigate the XML:
function parser(xml) {
$(xml).find('query_results').children().each(function() {
var row = $(this);
var id = row.attr("id");
var rowContents = "";
row.children().each(function() {
var tag = $(this);
var tagName = tag[0].tagName;
rowContents += "<div class='"+tagName+"'>"+tag.text()+"</div>";
});
var newRow = "<div id='row"+id+"'>"+rowContents+"</div>";
$("#query_results").append(newRow);
});
}
I used the row IDs and names to create and ID for each row DIV, for example:
<div id="row1"> ... </div>
And then used the tag names inside each row as classes:
<div class="distance"> ... </div>
<div class="post_title"> ... </div>
The parser() function above builds the divs and adds them to the placeholder div. The final result will be:
<div id="query_results">
<div id="row1">
<div class="distance">...</div>
<div class="post_title">...</div>
<div class="post_excerpt">...</div>
<div class="ID">...</div>
</div>
<div id="row2">...</div>
</div>
Then you can style the result in CSS using selectors such as:
#query_results div { ... }
#query_results div div { ... }
#row1 .distance { ... }
#row2 .ID { ... }

Categories