Data is duplicated when click again in button in javascript - javascript

I'm able to display all data, but when I click again in My team the data is displayed twice. Clicking again and again means more times the data is displayed. How can I display data once? I mean just the 6 team members and no 6 team members repeated.
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
var data1 = "TEAMSEARCH";
$.ajax({
url: 'TeamAssignment',
type: 'POST',
data: {
data1: data1
},
success: function(result) {
var memberList = $.parseJSON(result);
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName);
document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
}
}
});
}
<div class="col-lg-3 mb-0" style="display: flex;align-items: center;">
<div class="popup" onclick="myFunction()">
<h6>My team</h6>
<span class="popuptext" id="myPopup">My team members:<br><h7 id="demo"></h7><br></span>
</div>
</div>
</div>
<ol class="breadcrumb"></ol>

You need to clear demo element, before starting the for loop:
success: function(result) {
var memberList = $.parseJSON(result);
document.getElementById("demo").innerHTML = '';
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName);
document.getElementById("demo").innerHTML += '<li style="list-style:none;">' + memberList[i].fullName + '</li>';
}
}
Personally, i prefer following code instead, when working with jquery:
$.ajax({
url: 'TeamAssignment',
type: 'POST',
data: {
data1: data1
},
dataType: "json",
success: function(memberList) {
$("#demo").html('');
for (var i = 0; i < memberList.length; i++) {
console.log(memberList[i].fullName);
$("#demo").append('<li style="list-style:none;">' + memberList[i].fullName + '</li>');
}
}
});

Related

Display value in dropdown based on first dropdown

I have a working form here which populating dropdown from the database, i want to do here is display the value of 2nd dropdown based on the selected value on the 1st dropdown, but how i'm gonna do it. My Class will only display on the 2nd drowpdown if error is selected which the 1st dropdown
//my screenshot, my only sample data
enter image description here
Backend code:
public JsonResult GetErrorCategory()
{
List<ErrorCategory> error = errorDataAccessLayer.GetAllError(Action);
return Json(error.Select(x => new
{
errorCode = x.ErrorCode,
errorDescription = x.ErrorDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetClassCategory()
{
List<ErrorClass> error = errorDataAccessLayer.GetAllClass(Action);
return Json(error.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
View:
<form id="ticket_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label><strong>Error Type</strong></label>
<select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label><strong>Class Type</strong></label>
<select name="ClassType" id="ClassDropdown" class="form-control ClassType" >
</select>
</div>
</div>
<div class="form-group">
<input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
</div>
</form>
Javascript code:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
}
});
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
});
</script>
First, in script section you need split functions like as following. You see I added code parameter to the second GetClassCategory method:
function GetErrorCategory() {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
// This line applies onchange event for errorcategory dropdown
ApplyErrorCategoryDropDownOnChange();
}
}
}
function GetClassCategory(code) {
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: JSON.stringify({ code: code }),
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
}
Second, you need handle onchange() event, because when another item of the first dropwdown selected then you need get it's value.
function ApplyErrorCategoryDropDownOnChange() {
$("#ErrorDropdown").change(function (data) {
GetClassCategory(this.value)
});
}
Third, you must call GetErrorCategory() method from document ready function.
$(function () {
GetErrorCategory();
});
Fourth, you need add code parameter in the backend section, and apply this parameter to your db query:
public JsonResult GetClassCategory(string code) // I added parameter
{
List < ErrorClass > error = errorDataAccessLayer.GetAllClass(Action);
return Json(
error
.Where(x => x.ClassCode = code) // I added this section
.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
You have to change your code in your second ajax call, i mean it should be some dependent conditional to the first dropdown, For that you just need to get the value of the first dropdown to the second dropdown ajax call while it is selected. Just i mention below :
var error=document.getElementById("ErrorDropdown").value;
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{error:error}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
Here i have the value of the first dropdown in variable named as error and i have passed it through the ajax call and use it in my database query with where clause.

Set JSON values to HTML Table in Java Script?

function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert(response);
},
});
}
Im still working on it,
I print alert for output and got as below
[{
"userId":1,
"email":"santosh.jadi95#gmail.com",
"mobile":"9900082195",
"gender":"male",
"qualification":"1",
"dob":"2016-01-01",
"login":{
"loginId":1,
"userName":"santosh",
"password":"santosh",
"userType":"admin"
}
}]
I want the above JSON values in an HTML Table, is it Possible?
If yes, then i just want to know that, how it can be done?
Got the Solution,, Thank u all for the kind support
function loadUserTable(userType){
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
var obj = JSON.parse(response);
$("#tableId").html("");
var tr+="<tr><th>User ID</th><th>User Name</th></tr>";
for (var i = 0; i < obj.length; i++){
tr+="<tr>";
tr+="<td>" + obj[i].userId + "</td>";
tr+="<td>" + obj[i].login.userName + "</td>";
tr+="</tr>";
}
$("#tableId").append(tr);
}
});
}
Yes it is possible. if you want to print json data in simple html table then just iterate (use loop) till your json length and construct your table inside loop.
But i will suggest you to use dataTable / bootstrap table plugin there you just need to pass json at the initialization time.
for Example,
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
}
});
});
You'd simple just create a for loop inside success as following:
the obj[i] down below is just a placeholder. You'd have to get the correct value you want to place there.
HTML table container:
<div id="tableContainer">
<table>
<tbody class="tableBody">
<tbody>
</table>
</div>
JSON to append to table:
function loadUserTable(userType)
{
var TableHTML = '';
$.ajax({
type: "POST",
url: "loadUserTable.html",
data: "userType=" + userType,
success: function(response){
alert("eeee: "+response);
var obj = JSON.parse(response);
for (i = 0; i < obj.length; i++)
{
TableHTML += '<tr><td>' + obj[i].userId + '</td></tr>';
}
},
});
$(".tableBody").append(TableHTML);
}

How to get data from webservice in jquery?

I have a web service with link: http://41.128.183.109:9090/api/data/getalllocations
I recived this data in dropdown using jquery .this data contains 2 objects LocationName and LocID. I want to display an alert with LocID in dropdown change function in jQuery. Here is my code:
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value?' + i + '?="">' + data[i].LocationName + '</option>');
}
}
});
});
$("#countries").change(function () {
alert();
});
Here is my HTML code :
<select tabindex="-1" class="select2_group form-control" style="display: normal; width: 290px;" name="countries" id="countries">
<optgroup label="Select Your City" id="main"></optgroup>
</select>
please try following
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value="' + data[i].LocID + '">' + data[i].LocationName + '</option>');
}
}
});
$("#countries").change(function () {
alert($("#countries").val());
});
});

Display JSON result in Table Format

$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[i].die_no && data[i].status && data[i].location) {
txt += "<tr><td>"+data[i].die_no+"</td><td>"+data[i].status+"</td><td>"+data[i].location+"</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
Controller page
$die_no = array();
$status = array();
$location = array();
while ($row = mysql_fetch_array($query)) {
$die_no[] = $row["die_no"]; // or smth like $row["video_title"] for title
$status[] = $row["status"];
$location[] = $row["location"];
}
$res = array($die_no, $status, $location);
echo json_encode($res);
HTML page
<p>
<table id="table" class="hidden">
<tr>
<th>die_no</th>
<th>Status</th>
<th>Location</th>
</tr>
I would like to display result in HTML table format, so I have passed my result in array format to Json but the results are not displayed in HTML page.
I could see the response by using chrome Inspect element under network option . Please help me to display the retrieved results in HTML tabular format.
If you add console.log(data) in your succes response,you can see how the object is structured.
To access the desired json value you should try data['die_no'][i],data['status'][i],data['location'][i].
You can insert the response like this:
<table id="tbl">
</table>
Javascript:
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
$('$tbl').append("<tr><td>"+data['die_no'][i]+"</td><td>"+data['status'][i]+"</td><td>"+data['location'][i]+"</td></tr>");
}
}
}
}
}); //you missed this in your question
Use this
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[0][i] || data[1][i] || data[2][i]) {
txt += "<tr><td>" + data[0][i] + "</td><td>" + data[1][i] + "</td><td>" + data[2][i] + "</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
});
Actually your php code is not returning key value pair. So in your js you cannot use data.die_no etc
Use this like just I did:
data[0][i]
You have syntax error:
use
txt += <tr><td>
instead of
txt += tr><td>
after if condition

json data does not load after first time page load

I want to read JSON data into JavaScript, but the data does not display on initial page load, only after the page is refreshed.
Here is my code:
$(document).ready(function () {
$.ajax({
url:"http://192.168.0.105/stratagic-json/project_json.php",
type:"GET",
dataType:"json",
beforeSend: function(){
success:function(jsonData){
var projctList = '';
for (var i = 0; i < jsonData.length; i++) {
projctList += ' <li><div class="proj-details-wrap"> <img src="images/project-img.jpg" /><div class="proj-badge">Upcoming Projects</div><div class="proj-name">'+ jsonData[i].name +'<span>'+ jsonData[i].location +'</span> </div><div class="proj-status">'+ jsonData[i].percentage +'% <span>completed</span> </div></div><div class="container proj-desc">'+ jsonData[i].description +' </div> </li>';
}
$("#projctLists").html(projctList);
}
});
});
<ul class="slides" id="projctLists">
</ul>
Found one error, success is inside beforeSend, Corrected and shown below
$(document).ready(function () {
$.ajax({
url:"http://192.168.0.105/stratagic-json/project_json.php",
type:"GET",
dataType:"json",
beforeSend: function(){ },
success:function(jsonData){
var projctList = '';
for (var i = 0; i Upcoming Projects'+ jsonData[i].name +''+ jsonData[i].location +' '+ jsonData[i].percentage +'% completed '+ jsonData[i].description +' ';
}
$("#projctLists").html(projctList);
}
});
});
You need to remove following line from code
beforeSend: function() {
You have syntax error near beforeSend: function() {
Use your code like
$(document).ready(function () {
$.ajax({
url:"http://192.168.0.105/stratagic-json/project_json.php",
type:"GET",
dataType:"json",
beforeSend: function(){ },
success:function(jsonData){
var projctList = '';
for (var i = 0; i < jsonData.length; i++) {
projctList += ' <li><div class="proj-details-wrap"> <img src="images/project-img.jpg" /><div class="proj-badge">Upcoming Projects</div><div class="proj-name">'+ jsonData[i].name +'<span>'+ jsonData[i].location +'</span> </div><div class="proj-status">'+ jsonData[i].percentage +'% <span>completed</span> </div></div><div class="container proj-desc">'+ jsonData[i].description +' </div> </li>';
}
$("#projctLists").html(projctList);
}
});
});

Categories

Resources