1 year ago
#127424
Jakub Kowal
ASP.NET Core MVC - ajax, jQuery, json, javascript - retriving data from json, api controller
I want to lazy load using button the rest of articles form chosen category. Every time I submit "Show more" button I get two requests: the proper one with data in json and "undefined" request and I can't retrieve data from my json. Below is my code where I get the JSON data. Maybe should I add a jquery library? The "undefined" request is affected by this error I guess: jsfiddle.net/dhsom5n3. From 3035 line to the end the lines are underlined on red.
<button id="articles-button" onclick="ShowMore(2)">Pokaż więcej</button>
@section Scripts {
<script>
let ShowMore = function(quantity) {
let filterCategory = '@ViewData["kat"]';
var path = '/api/lazyloading' + '?id=' + @Model.Last().ArticleId + '&quantity=' + quantity + '&filterName=' + filterCategory;
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status === 200) {
try {
const data = JSON.parse(this.responseText);
for(var index in data) {
let article = data[index];
let newRow = document.createElement("tr");
let name = document.createElement("td");
$(name).text(article["ArticleName"]);
let price = document.createElement("td");
$(price).text("$" + article["ArticlePrice"])
let imageData = document.createElement("td");
let image = document.createElement("img");
$(imageData).append(image);
$(image).addClass("miniature");
$(image).attr("src", "/" + article["Image"]);
let formData = document.createElement("td");
let form = document.createElement("form");
$(form).attr("action", "https://localhost:44388/Shop/Display");
$(form).attr("method", "post");
$(form).addClass("add-to-cart");
let id = document.createElement("input");
$(id).prop("type", "hidden");
$(id).prop("name", "id")
$(id).val(article["ArticleId"]);
let button = document.createElement("input");
$(button).prop("type", "submit");
$(button).addClass("btn btn-primary");
$(button).val("Dodaj do koszyka");
$(form).append(button);
$(formData).append(form);
$(form).append(id);
$(newRow).append(name);
$(newRow).append(price);
$(newRow).append(imageData);
$(newRow).append(formData);
$("#body").append(newRow);
}
if (data.length === 0) {
$("#articles-button").hide();
} else {
last = data[data.length - 1]["id"];
}
} catch (e) {
console.warn('error with json');
}
} else if (this.status === 204) {
window.alert("No elements");
} else {
console.warn('Received' + this.status);
}
};
xhr.open("get", path)
xhr.send();
}
</script>
}
javascript
jquery
ajax
asp.net-core
polish
0 Answers
Your Answer