Ajax create new DIV instead of refresh - javascript

I have a problem with this code :
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
(function update() {
$.ajax({
type: 'GET',
url: "http://192.168.4.2/home/api/stato/ambiente/living",
dataType: "json",
success: renderList
}).then(function() {
setTimeout(update, 200);
});
})();
function renderList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$.each(list, function(index, data) {
if (data.stato ==1) {
$('#statoList').append('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_on.png " + '</div>');
$('#Switch').append('<button type="button">' + " OFF " + '</button>');
}
else {
$('#statoList').append('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_off.png " + '</div>');
$('#Switch').append('<button type="button">' + " ON " + '</button>');
}
});
}
</script>
</head>
<body>
<div id="statoList"></div>
<div id="Switch"></div>
</body>
</html>
I wish to execute a DIV refresh every 200 ms but the problem is that each time creates a new DIV below the previous one.
How can I solve this?
Thank you.

the append function is not the right one for what you are expecting i suggest you to use .html() so it will translate all your code (new div) to an html code
function renderList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$.each(list, function(index, data) {
if (data.stato ==1) {
$('#statoList').html('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_on.png " + '</div>');
$('#Switch').html('<button type="button">' + " OFF " + '</button>');
}
else {
$('#statoList').html('<div>'+ data.ID + " " + data.descrizione + " <img src=img/lamp_off.png " + '</div>');
$('#Switch').html('<button type="button">' + " ON " + '</button>');
}
});
}

If there are more than one of each type empty() the containers before appending
$('#statoList').empty();
$.each(list, function(index, data) {
if (data.stato ==1) {...

Related

Ajax Request problem, returns undefined 2 out of 3 times

This might be a silly question, but I'm working on a homework project. Most of it is already working, but when I try to write some html with jquery inside an ajax request, two out of three return undefined.
$.ajax({
url: "myurl",
type: "Get",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + userpass));
},
dataType: "json",
}).
done(function (data) {
$('#uebersicht').children(".item").remove();
for (var i = 0; i < data.length; i++) {
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + data[i].id + ")'>" +
data[i].datum + ", " + data[i].Stunden + " Stunden - " + data[i].Anmerkungen + "</p>");
}
});
I tried searching around, but I wasn't very lucky. Probably my searching is just off, but if someone could point me in the right direction I would be very glad.
Any help is appreciated. Thank you in advance.
You'll need to Parse the string data to json after it is received.
.done(function (data) {
var data = JSON.parse(data); // Parse it here
$('#uebersicht').children(".item").remove();
for (var i = 0; i < data.length; i++) {
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + data[i].id + ")'>" +
data[i].datum + ", " + data[i].Stunden + " Stunden - " + data[i].Anmerkungen + "</p>");
}
});
});
// Or you could use the `$.each()` function to loop through the data:
.done(function (data) {
$('#uebersicht').children(".item").remove();
$.each(data, function(item, element){
$('#uebersicht').append("<p class='item' onclick='deleteitem(" + element.id + ")'>" +
element.datum + ", " + element.Stunden + " Stunden - " + element.Anmerkungen + "</p>");
})
});

JavaScript $.each json is not defined

I have a string of JSON
msg = {d: "[{"ID":1,"IndentDate":"30/07/2018","EmpCode":"4000…er":"sef"}]
I wish to append my table but its showing row is undefined
$.each(msg, function(i, row) {
$("#autoTable").append("<tr><td>" + row['IndentDate'] + "</td><td>" + row['EmpCode'] + "</td></tr>");
})
I tried
$.each(json, function (i, msg) {
$("#autoTable").append("<tr><td>" + msg.IndentDate + "</td><td>" + msg.EmpCode + "</td></tr>");
})
too.please help
this thing worked..hope it helps others too..thanks for the help guys
var jsonString = JSON.parse(msg.d);
jsonString.forEach(function (row) {
$("#autoTable").append("" + row.IndentDate + "" + row.EmpCode + " ");
});

control entering in loop but not appending and displaying data in html div

i have json data which i want to display in html div using for loop. my control in entering in loop but not appending and displaying data in html div.
json data;
[{"id":"15","FirstName":"ranjan","MiddleName":"","LastName":"","Gender":"","Location":"r","Email":"ranjan.gupta.1994#gmail.com","Mobile":""},{"BookTitle":"","BookGenre":"","BookWriter":"","BookDescription":""}]
code;
$.getJSON(url, function(data) {
console.log(data);
if (data) {
alert("hey got the data" + JSON.stringify(data));
for (var i = 0; i < data.length; i++) {
alert("entered");
alert("hey got the data" + JSON.stringify(data[1]));
var $appendData =
$('<div id="' + data[i].id + '">' + '<p>'
+ 'FirstName:' + data[i].data.FirstName + '<br/>'
+ 'MiddleName:' + data[i].data.MiddleName + '<br/>'
+ 'LastName:' + data[i].data.LastName + '<br/>'
+ 'Gender:' + data[i].data.Gender + '<br/>'
+ 'Location:' + data[i].data.Location + '<br/>'
+ 'Email:' + data[i].data.Email + '<br/>'
+ 'Mobile:' + data[i].data.Mobile + '<br/>'
+ '</p>' + '</div>').appendTo('#postjson');
}
} else {
return;
}
// this is my div
</script>
<div class="grid" id="postjson"></div>
</div>
</div>
You got typo on your loop, just replace all your data[i].data.property with data[i].property
Javascript
$.getJSON(url,function(data) {
console.log(data);
if(data){
alert("hey got the data"+JSON.stringify(data));
for(var i=0; i<data.length; i++) {
alert("entered");
alert("hey got the data"+JSON.stringify(data[1]));
$('<div id="'+data[i].id+'">'
+'<p>'
+'FirstName:'+data[i].FirstName+'<br/>'
+'MiddleName:'+data[i].MiddleName+'<br/>'
+'LastName:'+data[i].LastName+'<br/>'
+'Gender:'+data[i].Gender+'<br/>'
+'Location:'+data[i].Location+'<br/>'
+'Email:'+data[i].Email+'<br/>'
+'Mobile:'+data[i].Mobile+'<br/>'
+'</p>'
+'</div>').appendTo('#postjson');
}
}
else {
return;
}
JsFiddle

Change icon on if else statement in jQuery

I'm storing a value inside a javascript variable, now I want to run a if statement to change the data-icon on a select option.
<script type="text/javascript">
$(document).ready(function(){
$("#fds_gender").change(function () {
var gender = $(this).val();
$.ajax({
type: "POST",
data: {
"username" : "<?php echo $user->username; ?>",
"gender" : gender
},
url: "ajax/fds_categories_ajax.php",
success: function(data){
$("#fds_categories").empty();
$.each($.parseJSON(data), function(index, element) {
if(element.p == 0){
$("#fds_categories").append(
$('<option data-icon="man"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')
);
}else{
$("#fds_categories").append(
$('<option data-icon="man"></option>').val(element.id).html(element.name + ": " + element.p + ' Zcard')
);
}
});
}
});
});
});
</script>
gender does contains one of the following values: stud or babe.
What I want to create:
In case gender contains stud:
$('<option data-icon="man"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')
In case gender contains babe:
$('<option data-icon="babe"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')
What I have tested:
$('<option data-icon="' + if(gender == 'stud'){}else{} + '"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')
Just got no clue how to echo out a value such as man or woman. Is there such a Javascript echo function as in PHP?
You can use ternary operator.
$('<option data-icon="' +( (gender == 'stud')?'man':'babe')+ '"></option>').val(element.id).html(element.name + ": " + element.pb + ' Zbucks')

Clearing list from partial view with javascript

I have a list that is created by a javascript function. I have a separate function to reset the page, but it will not clear the list that was created. Any thoughts?
Javascript call to create the list:
$(function submit() {
$('form').submit(function (e) {
e.preventDefault();
$("#searchResults").show();
$.ajax({
url: 'Home/TAPost',
data: $('form').serialize(),
dataType: "json",
type: 'POST',
success: function (accts) {
$("#rowHeaders").append('<tr><td>' + "Customer Name" + '</td><td>' + " Customer SSN" + '</td><td>' + " FHBOAT Account Number" + '</td><td>' +
" Original Account Number" + '</td><td>' + " Product Type" + '</td><tr>');
$.each(accts, function (index, acct) {
$("#resultsTable").append('<tr><td>' + acct.CustomerName + '</td><td>' + " " + acct.SSN + '</td><td>' + " " + acct.FHAcctNumber + '</td><td>'
+ " " + acct.OriginalAcctNumber + '</td><td>' + " " + acct.ProductType + '</td></tr>');
});
}
});
return false;
});
});
Call to reset:
function resetForm() {
document.getElementById("LOB").style.borderColor = "";
document.getElementById("LOB").style.borderColor = "";
$('#resultsTable').empty();
return false;
};
HTML:
<section id="searchResults">
<h2>Search Results</h2>
<table id="resultsTable" cellpadding="2" cellspacing="50">
<thead id="rowHeaders"></thead>
</table>
</section>
Instead of:
$('#resultsTable').empty();
You can use:
$('#resultsTable').html('');

Categories