I have a problem with my code
There is a code of cycle
var myslides = document.getElementById("slider-list");
for (let i = 0; i < arr.length; i++) {
id[i] = arr[i].id;
pathToStudents[i] = `img/${arr[i].avatar}`;
fio[i] = arr[i].fio;
let slidediv = document.createElement("li");
slidediv.className = "slider-element";
slidediv.innerHTML = `<img src="${pathToStudents[i]}" alt="${fio[i]}"
onClick="OpenCase(${id[i]});">`;
let sliderp = document.createElement("p");
sliderp.className = "pSlides";
sliderp.innerHTML = `${fio[i]}`;
myslides.appendChild(slidediv);
slidediv.appendChild(sliderp);
};
The Dom-elements, which creates are:
<li class="slider-element" style="opacity: 0;"><img src="img/x36.jpg" alt="Oblak Y.B." onclick="OpenCase(36);"><p class="pSlides">Oblak Y.B.</p></li>
<li class="slider-element" style="opacity: 0;"><img src="img/anotertkach.jpg" alt="Tkach I.L." Onclick="OpenCase(37);"><p class="pSlides">Tkach I.L.</p></li>
.... etc.
Function OpenCase has the next form:
function OpenCase(id) {
$.ajax({
type: "post",
dataType: "json",
url: "php/getter.php",
data: {
mode: "spec"
},
success: function (spec) {
$.ajax({
url: "php/getter.php",
type: 'post',
dataType: "json",
data: {
mode: "student",
id: id
},
success: function (result) {
...
Despite the fact that the DOM elements are created with different values of the argument of the function OpenCase, it always produces the same result with the last i = arr.length-1.
If you manually substitute the argument value for the foo function in the DOM element, then it works without problems.
With what it can be connected? Can anybody help?
I will be very grateful for your help!
arr = [{
id: 1,
fio: 1,
avatar: 'x'
}, {
id: 2,
fio: 2,
avatar: 'y'
}]
id = []
fio = []
pathToStudents = []
var myslides = document.getElementById("slider-list");
for (let i = 0; i < arr.length; i++) {
id[i] = arr[i].id;
pathToStudents[i] = `img/${arr[i].avatar}`;
fio[i] = arr[i].fio;
let slidediv = document.createElement("li");
slidediv.className = "slider-element";
slidediv.innerHTML = `<img src="${pathToStudents[i]}" alt="${fio[i]}"
onClick="OpenCase(${id[i]});">`;
let sliderp = document.createElement("p");
sliderp.className = "pSlides";
sliderp.innerHTML = `${fio[i]}`;
myslides.appendChild(slidediv);
slidediv.appendChild(sliderp);
};
function OpenCase(id) {
$.ajax({
type: "post",
dataType: "json",
url: "https://jsonplaceholder.typicode.com/posts",
data: {
mode: "spec"
},
success: function(spec) {
console.log('succ')
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: 'post',
dataType: "json",
data: {
mode: "student",
id: id
},
success: function(result) {
console.log(result)
}
})
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="slider-list"></div>
Related
I have two kendo list boxes they exchange items between them. Basically an Items available and an Items selected pair.
I have Json service which controls what items are available via a Json array.
When the user selects a new filter I want both Kendo List Boxes to clear the items out before adding the new items from the server.
Currently it appends the new list from the server to the current list.
$(document).ready(function () {
$("#filterKeyWord").click(function () {
getResults($("#keywords"));
});
$("#availableReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
connectWith: "selectedReports",
dropSources: ["availableReports"],
toolbar: {
tools: ["transferTo", "transferFrom", "transferAllTo", "transferAllFrom", "remove"]
}
});
$("#selectedReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
dropSources: ["selectedReports"],
remove: function (e) {
setSelected(e, false);
},
add: function (e) {
setSelected(e, true);
}
});
var mydata = { ReportName: "", UserId: "" };
mydata.ReportName = "SomeName";
mydata.UserId = "SomeUser";
var crudService = "",
dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
update: {
url: crudService + "SaveReportList2",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "post",
},
filter: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read" && options.models) {
return JSON.stringify({ models: options.models });
}
if (operation === "read") {
return "request=" + JSON.stringify(mydata);
}
}
},
batch: true,
requestStart: function () {
kendo.ui.progress($(".demo-section"), true);
console.log("request start");
},
requestEnd: function () {
kendo.ui.progress($(".demo-section"), false);
console.log("request end");
},
error: function (e) {
console.log("Error" + e);
},
change: function (e) {
console.log("change" + this.data.length);
setDropDownBoxes(this);
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number" },
Selected: { type: "boolean" },
Name: { type: "string" },
Description: { type: "string" },
InternalId: { type: "string" }
}
}
}
});
$("#saveReportList").kendoButton({
click: function (e) {
dataSource.sync();
}
});
$("#getReportList").kendoButton({
click: function (e) {
mydata.ReportName = $("#keywords").val();
dataSource.read();
}
});
function setDropDownBoxes(obj) {
var data = obj.data();
var availableReports = $("#availableReports").data("kendoListBox");
var selectedReports = $("#selectedReports").data("kendoListBox");
var items = availableReports.dataItems();
for (var i = 0; i < data.length; i++) {
if (data[i].Selected) {
selectedReports.add(data[i]);
}
else {
availableReports.add(data[i]);
}
}
}
function setSelected(e, flag) {
var removedItems = e.dataItems;
for (var i = 0; i < removedItems.length; i++) {
console.log(flag + " " + removedItems[i].ID + " " + removedItems[i].Name + " " + removedItems[i].Selected);
var item = dataSource.get(removedItems[i].ID);
item.Selected = flag;
item.dirty = !item.dirty;
}
}
});
Not sure where in your exactly the clening should be performed, but, you can use both remove() and item() methods togheter to clear a listBox.
remove() method accepts a list of li elements, which is what items() returns, so it will remove the whole li collection from the list.
var listBox = $("#listBox").data("kendoListBox");
listBox.remove(listBox.items());
Demo
I retrieve a value in js and i want to insert it in the DB with ajax post. Is it possible to do that without asp:button to bind the value to the code behind?
UPDATE here is the Js:
function readXML() {
var xml = new XMLHttpRequest();
xml.open('GET', 'toXml/file.xml', false);
xml.send();
var xmlData = xml.responseXML;
if (!xmlData) {
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
}
var itemsID = xmlData.getElementsByTagName("entry");
var itemsTitle = xmlData.getElementsByTagName("entry");
var itemsCustomer = xmlData.getElementsByTagName("d:Customer");
var itemsBrand = xmlData.getElementsByTagName("d:Brand");
var itemsCountries = xmlData.getElementsByTagName("d:Countries");
var itemsElement = xmlData.getElementsByTagName("d:element");
var i, k, j, ID, Title, Customer, Brand, Countries;
var list = [];
for (i = 0; i < itemsTitle.length; i++) {
var Brands = "";
var Country = "";
itemI = itemsID[i];
itemT = itemsTitle[i];
itemCr = itemsCustomer[i];
itemB = itemsBrand[i];
itemCs = itemsCountries[i];
itemEl = itemsElement[k];
ID = itemI.getElementsByTagName("d:Id")[0].firstChild.data;
Title = itemT.getElementsByTagName("d:Title")[0].firstChild.data;
Customer = itemCr.getElementsByTagName("d:element")[0].firstChild.data;
for (k = 0; k < itemB.children.length; k++) {
Brand = itemB.getElementsByTagName("d:element")[k].firstChild.data;
if (k > 1) {
Brands += Brand + ",";
}
else {
Brands = Brand;
}
}
for (j = 0; j < itemCs.children.length; j++) {
Countries = itemCs.getElementsByTagName("d:element")[j].firstChild.data;
if (j > 1) {
Country += Countries + ",";
}
else {
Country = Countries;
}
}
list[i] = [ID, Title, Customer, Brands, Country];
}
var table = $('#table_id').DataTable({
lengthMenu: [[10, 25, 50, 200, -1], [10, 25, 50, 200, "All"]],
data: list,
columns: [
{ title: "ID" },
{ title: "Title" },
{ title: "Customer" },
{ title: "Brands" },
{ title: "Country" },
{ title: "Check", "defaultContent": "<button class=\"checkBtn\" type=\"button\">Check</button>" },
{ title: "Create", "defaultContent": "<button class=\"createBtn\" type=\"button\">Create</button>" }
],
columnDefs: [{
"targets": [0],
"visible": true,
"searchable": true
}]
});
$('#table_id').on('click', '.checkBtn', function () {
var data = table.row($(this).parents('tr')).data();
alert("ID:" + data[0] + "," + "Title:" + data[1] + "," + "Customer:" + data[2] + "," + "Brand:" + data[3] + "," + "Country:" + data[4]);
$.ajax({
type: "POST",
url: "Selida.aspx/InsertData",
data: JSON.stringify(data[0]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("all good");
},
error: function (errMessage) {
alert("Error:" + errMessage);
}
});
});
}
Through C# im getting data and i save it into an xml file. Then with the js i retrieve that data and with Jquery datatables im displaying on the page.
I Have a method in c# called InsertData which is supposed to insert the data in the DB. I think that the problem is in the ajax call.
The answer is yes, i can post a value from js with an ajax call that has no relation with the server side
$.ajax({
type: "POST",
url: "Selida.aspx/CheckData",
data: JSON.stringify({ trala : data[0] }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("It's already in the DB");
},
error: function (errMessage) {
console.log("Error:" + JSON.stringify(errMessage));
}
});
and the parameter in the c# method must have the name "trala" in order to retrieve the value from the post.
I have a JSON string coming from my database table but it has empty root element name
{"": [
{"ID":18,"MenuName":"dsadasdasd","IsActive":"InActive"},
{"ID":17,"MenuName":"Karachi","IsActive":"Active"},
{"ID":2,"MenuName":"User Management","IsActive":"Active"},
{"ID":1,"MenuName":"Home","IsActive":"Active"}
]}
I am trying to access this JSON with below jquery ajax call method
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d);
for (i = 0; i < Object.keys(MyData).length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
My Webmethod
[WebMethod(true)]
public static string CallDataTable_EmptyRootName(){
List<Category> Categories = new List<Category>();
clsMenu objMenu = new clsMenu();
DataTable dt = new DataTable();
objMenu.GetAllMenu(dt);
if (dt.Rows.Count > 0){
string jsonString = ConversionExtension.DataTabelToJson(dt);
return jsonString.ToString();
}else{
return "";
}
}
it is giving me undefined : undefined... Please help me. I am stuck now
Try this:
function Get_DataTable() {
$.ajax({
url: "GridView_JqueryFunctionality.aspx/CallDataTable_EmptyRootName",
type: "POST",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d) // showing json is fine
var MyData = $.parseJSON(data.d)[""];
for (i = 0; i < MyData.length; i++) {
alert(MyData[i].ID + ' : ' + MyData[i].MenuName);
}
}
});
}
Assuming you have a variable name for your object, you can reference it with an empty string as the key.
var a = {
"": [
{
"ID": 18,
"MenuName": "dsadasdasd",
"IsActive": "InActive"
},
{
"ID": 17,
"MenuName": "Karachi",
"IsActive": "Active"
},
{
"ID": 2,
"MenuName": "User Management",
"IsActive": "Active"
},
{
"ID": 1,
"MenuName": "Home",
"IsActive": "Active"
}
]
}
console.log(a[""]);
Try running the above code notice we can still access the objects elements despite having an empty root name.
You have to access with brackets the no-name property in the root object, and then iterate over the array of items.
success: function(response) {
var data = $.parseJSON(response.d);
var list = data[""];
list.forEach(function(item, i) {
console.log(item);
console.log(item.ID, ' -> ', item.MenuName);
});
}
I am trying to get all IDs from an array objects and put the in a list so they can be passed to a method (API)
var tempObj= Getlist();
var tmpList = tempObj.listOfdata.filter(function (result) { return (result.Id) });
var data = tmpList
then I have my AJAX call
$.ajax({
url: url,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
async: true,
method: 'POST',
success: function (data) {
console.log(data);
}
});
no data is being passed
If you want to extract values from a collection of objects, don't use filter. Use map.
let list = [
{ id: 1 },
{ id: 3 },
{ id: 23 },
{ id: 16 }
];
let data = list.map((obj) => obj.id);
console.log(data);
In ES5:
var list = [
{ id: 1 },
{ id: 3 },
{ id: 23 },
{ id: 16 }
];
var data = list.map(function(obj) {
return obj.id;
});
console.log(data);
I'd like to toggle between 2 ajax data objects on click of a link. Its not possible to do this with the method below, can anyone suggest a way I can do this? Thanks!
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
jQuery(".togglesearch").toggle(
function () {
data: JSON.stringify({
"Name": jQuery("#searchfield").val(),
"Number": ""
}),
},
function () {
data: JSON.stringify({
"Name": "",
"Number": jQuery("#searchfield").val()
}),
}
);
var data = ["Name", "Number"];
var obj = {"Name":"", "Number":""};
var val = jQuery("#searchfield").val();
var n = 0;
var res;
$("button").click(function() {
obj[data[n]] = val;
obj[data[n === 0 ? n + 1 : n- 1]] = "";
res = JSON.stringify(obj);
$("label").text(JSON.stringify(res));
// do ajax stuff
/*
jQuery.ajax({
url: "/somefile.php",
dataType: "JSON",
type: "POST",
data: res
})
*/
n = n === 0 ? 1 : 0
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button>click</button>
<input type="text" id="searchfield" value="123" /><label></label>
I think you'll have to put each different ajax call inside the toggles:
jQuery(".togglesearch").toggle(
function () {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify({
"Name": jQuery("#searchfield").val(),
"Number": ""
})
});
},
function () {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify({
"Name": "",
"Number": jQuery("#searchfield").val()
})
});
}
});
Try this:
jQuery(".togglesearch").toggle(function() {
var data = { "Name": "", "Number": jQuery("#searchfield").val() };
callAjax(data);
}, function(){
var data = { "Name": jQuery("#searchfield").val(), "Number": "" };
callAjax(data);
});
function callAjax(data) {
jQuery.ajax({
url: "/somefile.php",
dataType: 'JSON',
type: 'POST',
data: JSON.stringify(data),
success: function(response) { }
)};
}
In toggle finally call a function with ajax call. Let me know if it works for you.