I am trying to create table rows containing data from each attribute from my object response using $.each, however the Id, Purpose, and Amount are coming back undefined. I have tested the response in Fiddler and the data is all being received correctly, the problem just seems to be in the "item" part. Here is my Jquery:
$.ajax({
type: "GET",
url: "https://chad-test4.clas.uconn.edu/api/Commitments/GetCommitmentPurposes/2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
var purposes = $("#purposes tbody");
if (response.Success == true) {
purposes.empty();
var buttons = '<tr><td><button type="button" class="btn-primary">Save</button>'
+ '<button type="button" class=".btn-danger">Delete</button></td>'
var list = response.Data;
$.each(list, function (i, item) {
purposes.append(buttons + '<td><select id=' + item.Id + '>' + item.Purpose + '</select>'
+ '<td><input type="text" val =' + item.Amount + '/>')
});
}
}
});
});
Could you post a snippet of JSON aswell ?
Basically I believe what you need to do is to access the entries by an identifier:
$.each( list.items, function(i, item ) {
But posting JSON would clarify if that is true.
Related
i have this web service methode
List<object[]> List1 = new List<object[]>();
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public List<object[]> GetData(int ID)
{
var team = db.TEST.WHERE(a => a.id == ID).ToList();
List1.Add(new object[]
{
team
});
return teamList;
}
and this my Function using Javascript & jQuer & Json
function BindList(id) {
$.ajax({
url: "/WebService1.asmx/GetData",
type: "GET",
dataType: "json",
contentType: "application/Json; Charset= Utf-8",
success: function (data) {
var list = "";
$.each(data.d[0][0], function (index, item) {
list += "<li class='text-secondary p-1'><a class='btn-link text-secondary'><b>" + item.Id+ "</b>" + ", " + "<span class='font-italic'><small>" + item.Name + "</small></span><small><a href='#' Onclick='Delete(" + item.Name + ")'> <i class='float-right far fa-trash-alt'></i></a></small></a>" + "</li>";
});
$("#list").html(list);// and this to print data to this list id
},
error: function (response) {
alert(response);
}
});
}
and this my button to get data
<input id="Button1" type="button" onclick="BindMembersList(1)" value="button" />
My problem is where i need to put the id for give just data have id equal 1
thank you
Since it's an url you are calling, pass it on the url of your AJAX call like so:
function BindList(id) {
$.ajax({
url: "/WebService1.asmx/GetData/" + id,
type: "GET",
dataType: "json",
contentType: "application/Json; Charset= Utf-8",
success: function (data) {
var list = "";
$.each(data.d[0][0], function (index, item) {
list += "<li class='text-secondary p-1'><a class='btn-link text-secondary'><b>" + item.Id+ "</b>" + ", " + "<span class='font-italic'><small>" + item.Name + "</small></span><small><a href='#' Onclick='Delete(" + item.Name + ")'> <i class='float-right far fa-trash-alt'></i></a></small></a>" + "</li>";
});
$("#list").html(list);// and this to print data to this list id
},
error: function (response) {
alert(response);
}
});
}
If it's not working or you need to pass more parameter to the action, you can specify them and using the "&" as separator like so:
url: "/WebService1.asmx/GetData?id=" + id + "¶meter2=" + param,
Anyway, your c# method is wrong since you are returning teamList, which is not implemented inside the action
Try this url:
url: "/WebService1.asmx/GetData?id="+id
I have two dropdown lists which one of them is dependent on the other. Let's call is multiselect 1 and multiselect 2. Based on the value selected in multiselect1, multiselect 2's dropdown list changes via ajax call.
I am triggering my ajax call based on 'onChange'.
However, when user opens the page and as default all values will be selected in multiselect 1 but as my current set-up is only for onchange, how to trigger my ajax call based on all selected as default?
On change AJAX Call which perfectly works except when all selected --->
$('#market-select').multiselect(
{
includeSelectAllOption: true,
selectAllValue: 'multiselect-all',
filterBehavior: 'value',
enableFiltering: true,
buttonWidth: '270px',
onChange: function (option, checked) {
var markets = $('#market-select option:selected');
var selected = [];
var json = "'" + JSON.stringify(selected) + "'";
$(markets).each(function (index, markets) {
selected.push($(this).val())
});
$.ajax({
type: "POST",
dataType: "json",
url: _config.GetCampaignsByMarket,
data: JSON.stringify({
marketValue: selected
}),
contentType: 'application/json',
success: function (data) {
var items = ''; //the original example which makes constant call to dom when the other one makes call only twice
$('.select-ajax').empty();
$.each(data, function (key, val) {
$('.select-ajax').append('<option selected value="' + val.CampaignInitiative + '">' + val.CampaignInitiative + '</option>');
items += "<option value='" + val.CampaignInitiative + "'>" + val.CampaignInitiative + "</option>";
});
$('.select-ajax').multiselect('rebuild');
},
error: function (xhr, status, error) {
}
});
}
});
Attemt to initialize ajax call on initialization which clearly does not work. I am going crazy at this point.
$("#market-select").multiselect('selectAll', false);
$("#market-select").multiselect('updateButtonText');
var allMarkets = $('#market-select:selected').map(function (a, item) {
$.ajax({
type: "POST",
dataType: "json",
url: _config.GetCampaignsByMarket,
data: JSON.stringify({
marketValue: allMarkets
}),
contentType: 'application/json',
success: function (data) {
var items = ''; //the original example which makes constant call to dom when the other one makes call only twice
$('.select-ajax').empty();
$.each(data, function (key, val) {
$('.select-ajax').append('<option selected value="' + val.CampaignInitiative + '">' + val.CampaignInitiative + '</option>');
items += "<option value='" + val.CampaignInitiative + "'>" + val.CampaignInitiative + "</option>";
});
//var options = data.map(function (o) {
// return '<option selected value="' + o.CampaignInitiative + '">' + o.CampaignInitiative + '</option>'; // faster as it only accesses the DOM twice, compared to the original's 2+N array items.'
//}).join('');
$('.select-ajax').multiselect('rebuild');
},
error: function (xhr, status, error) {
}
});
});
Right here bootstrap-multiselect has onSelectAll configuration. Is that what you're looking for?
I am using jquery to pull football data from an api as follows
type: 'GET',
dataType: 'json',
url: "http://api.football-data.org/v1/competitions/426/teams",
processData: true,
//idLength: url.Length - url.LastIndexOf("/", StringComparison.Ordinal) - 1,
//id: url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1, idLength),
success: function (data, status) {
var trHTML = '';
$.each(data.teams, function (key, item) {
var id = item._links.self.href;
var indexOfLastBackSlash = id.lastIndexOf("/") + 1;
id = id.substring(indexOfLastBackSlash);
//$('<option>', { text: item.TeamName, id: item.ID }).appendTo('#lstTeams');
trHTML += '<tr class="info"><td>' + item.name +
'</td><td>' + item.code +
'</td><td>' + item.shortName +
'</td><td>' + item.squadMarketValue +
'</td><td>' + item.crestURL +
'</td><td>' + id +
'</td></tr>';
I want to be able to select a 'td' and navigate to another url like "http://api.football-data.org/v1/teams/322/fixtures" for the team with id of 322. How can I do so?
You can create a function which will do same ajax request but this time for single record. On your target's click event you need to call that function passing the id you need to fetch records for. One way of doing this is to set a data attribute to your target container.
Below is the sample code performing similar functionality.
$(function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/',
method: 'GET',
dataType: 'json'
}).then(function(Data) {
$.each(Data, function (key, data) {
var id = data.id;
var title = data.title;
$('.tableAllRecords').append('<tr><td><a href=# class=mylink data-id='+id+'>'+id+'</a></td><td>'+title+'</td></tr>');
});
});
});
function fetchSingle(id) {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + id,
method: 'GET',
dataType: 'json'
}).then(function(data) {
var id = data.id;
var title = data.title;
var body = data.body;
$('.tableSingleRecord').append('<tr><td>'+id+'</td><td>'+title+'</td><td>'+body+'</td></tr>');
});
}
$(document).on('click', '.mylink', function(e) {
var id = $(this).data('id');
fetchSingle(id);
e.preventDefault(); // disabling anchor's default [redirect] behaviour
});
Here is the link to fiddle. https://jsfiddle.net/2h54vu7h/
If you need to display records on a new page, you simply have to pass id into your url and on next page you have make an ajax request getting the id variable from url.
Example: '<a href=somepage.html?id='+id+'>View Details</a>';
I want to add the values inot the database but I am not to able to do that.
var Array;
$(document).ready(function ()
{
$.ajax({
url: '../api/Emp/GetAll',
type: 'Get',
cache: false,
datatype: 'json',
success: function (text) {
Array = text.Table;
var List = JSON.stringify(text);
for (var i = 0; i < data.length; i++) {
var Id = Array[i].id;
var Name =Array[i].name;
var city = Array[i].city;
$('#table body').append('<tr><td>' + Id + '</td><td><input type="text" value="' + Name + '" id="txt' + Id + '" /></td><td>' + city + '</td> </tr>');
}
}
})
If you need to put it back into the database you just need to reverse the process.
Use post for your type and send the data back with ajax to a php script page that inserts the data into your database.
You can edit the data on the php page before you insert it into the database or you can edit the data with javascript then send it back to php page.
Create an ajax post
$.ajax({
type: "post",
datatype: "json",
url: "insertPage.php",
data: {dataNameHere: editedDataGoesHere},
success: function(data){
alert("SUCCESS");
},
error: function(e){
alert("ERROR");
}
});
And then in your PHP:
$obj = $_POST['dataNameHere'];
and insert it into your database like you normally would.
I am using two drop down(first drop-down category and second drop-down sub category) in a page,both drop-down will be loaded dynamically, in which I will be selecting a value from first drop-down accordingly I have to load value to second drop-down.I has done that,but thing is that it will get done for first time.
But when I click on some other option in states drop-down, its not getting updated on second drop-down.
And My code is:
This piece of code is to get list of category while loading page ie under document.ready
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
This part of ajax is to load sub category
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
From what I see in your code you always append new entries, yet never remove old ones before. So possibly your list just keeps getting longer with new entries at its end? Try to remove the entries before append new ones:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
In my experience $.each with $.append can get very slow at some amount of list entries. I would rewrite it in native javascript with for() and createElement().
Try adding $("#productCategory").empty() before the first $.each and $("#productSubCategory").empty() before the second $.each.
you need to make html in .each and append after .each end. No option change from first drop down you need to remove the previous on by using $("#productSubCategory option").remove();
$.ajax({
url: "../category/getCategory",
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
var categoryBOs = data.categoryBOs;
var html = '';
$.each(categoryBOs, function (key, value) {
html += '<option value=' + value.categoryId + '>' + value.categoryName + '</option>';
});
$("#productCategory").append(html);
}
});
$("#productCategory").on('change', function () {
alert($(this).val());
$.ajax({
url: "../category/getSubCategory",
type: "post",
cache: false,
dataType: "json",
data: "categoryId=" + $(this).val(),
success: function (data) {
var subCategoryBOs = data.subCategoryBOs;
var html = '';
$.each(subCategoryBOs, function (key, subCategoryBO) {
subCategories.push({ lable: subCategoryBO.categoryId, value: subCategoryBO.categoryName });
html += '<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>';
});
$("#productSubCategory").append(html);
}
});
});
Just simple thing you have to do here is that every time when you load sub-categories just place following before that .
$(dropdown).empty();
Thanks !
$("select#catname").change(function () {
// part of code
$("#subcatname").append($newOpt1);
// appending the category of dropdown
}
$("#subcatname").trigger('contentChanged');
// changing the contenet
}
});
$("select#subcatname").change(function () {
// something changes after trigger in dropdown
});
// removing the content or clearing the content after selecting
$("#subcatname").empty();
});
});