This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
Just wondering if this is even possible.
I am making a store web application in asp.net MVC 4 i guess.
And my articles have a category and a sub category.
So I got this code which I can't make to work.
Script:
$("#ManageCategories").click(function (e) {
$.ajax({
type: "GET",
url: "Acp/LoadManageCategories",
success: function (response) {
$("#main-acp-display").html(response);
},
error: function () {
alert("Error!");
}
});
});
$(".get-subcategories").click(function () {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: $(this).attr("id") },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
});
(the first part works like a charm)
Controler:
[CustomAuthorize(Roles.Admin)]
public ActionResult LoadManageCategories()
{
IEnumerable<CategoryModel> model = _categoryManager.GetAll().Select(x => (CategoryModel)x);
return PartialView("Partial/_LoadManageCategories", model);
}
[CustomAuthorize(Roles.Admin)]
public ActionResult LoadManageSubCategories(string subCategoryId)
{
int id = Convert.ToInt32(subCategoryId);
IEnumerable<SubCategoryModel> model = _categoryManager.GetAllSubCategoriesByCategoryId(id).Select(x => (SubCategoryModel)x);
return PartialView("Partial/_LoadManageSubCategories", model);
}
Now you see the first level code works. When I click a div on index it loads all categories. But the other function wont load unless I place the clickable div on index page too and I wanted it to be a part of first partial view.
So it should be Button(click) > Shows all categories(click any) > Loads subcategories.
Is this even possible?
Offtopic: Does MVC work only on one level? Cause I remember trying to have a Model with List of other models inside of it and inside this list there was another model and it wasn't so good xD (Managed to find simpler solution, but this is where I got the mvc one level only thought)
Update:
So #bigless had an idea to make this a function so here it is so far:
function createSubcategories(id) {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: id },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
};
And calling it by:
<button onclick="createSubcategories(1)"><i class="fas fa-angle-double-right main-cat-icon"></i></button>
Current error:
Uncaught ReferenceError: createSubcategories is not defined
at HTMLButtonElement.onclick (Acp:89)
You can not attach event listener to DOM element(.get-subcategories) that does not exist yet. Try something like $(document).on('click', '.get-subcategories', function() { .. or:
$("#ManageCategories").click(function (e) {
$.ajax({
type: "GET",
url: "Acp/LoadManageCategories",
success: function (response) {
$("#main-acp-display").html(response).ready(function() {
$(".get-subcategories").click(createSubcategories);
});
},
error: function () {
alert("Error!");
}
});
});
function createSubcategories() {
$.ajax({
type: "GET",
url: "Acp/LoadManageSubCategories",
data: { subCategoryId: $(this).attr("id") },
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$("#subcategory-display").html(response);
},
error: function (response) {
alert(response.responseText);
}
});
};
Related
At following method i'm trying to get grid selected row. By the way, i use syncfusion component library.
My question when i call the grid.rowSelected, function's inside works last. So i can't pass model in ajax.
What's the reason of it ?
function editPackage() {
var editPackageModel;
var grid = document.getElementById("Grid").ej2_instances[0];
grid.rowSelected = function(args) {
console.log(args.data);*// works last*
editPackageModel = args.data;*// works last*
}
$.ajax({
type: "GET",
url: "/Package/Edit",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: editPackageModel,
success: function (result) {
$('#generalModal').html(result);
},
error: function () {
alert("Dynamic content load failed.");
}
});
}
I'm not sure exactly what is the situation with "grid", i assume you have that element ready before the function is called, so try this:
var grid = document.getElementById("Grid").ej2_instances[0];//Get node reference.
grid.rowSelected = function (args) {//Setup event listener.
editPackage(args.data);//Pass the data from the event to your function
}
function editPackage(editPackageModel) {//Get the "model" and send ajax
$.ajax({
type: "GET",
url: "/Package/Edit",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: editPackageModel,
success: function (result) {
$('#generalModal').html(result);
},
error: function () {
alert("Dynamic content load failed.");
}
});
}
I'm trying to make a GET call in jQuery passing a parameter here is what I'm doing
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere",
contentType: "application/json; charset=utf-8",
data: id,
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
}
On server side the controller is called but the data I'm getting is always null...
[HttpGet]
public IEnumerable<TypeOfObject> GetDataHere([FromBody]string id)
{}
Any idea how's that happening?
You need to give the value a key so that the ModelBinder can recognise and work with it:
data: { id: id },
You also need to remove the [FromBody] attribute in the action signature, as GET data is sent in the URL (either as part of the querystring, or in a routing structure).
Lastly, the options object of $.ajax() has no failure property so that can be removed as it's redundant.
I upvoted #RoryMcrossan, but there is another solution.
you could just add it to the end of the url.
function getChirurghi() {
var id = "1";
$.ajax({
type: "GET",
url: "/api/ControllerName/GetDataHere/" + id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (data) {
alert(data.responseText);
},
error: function (data) {
alert(data.responseText);
}
});
I make an Ajax Request that adds content to the page with HTML from the back-end, and then I make another Ajax Request that modifies that dynamically added HTML.
$("#list-customers-button").click(function () {
var selectedAcquirer = $("#acquirer-select").val();
if (selectedAcquirer === "adyen") {
if (listed) {
listed = false;
$("#customer-list-area").hide().html('').fadeIn(fadeTime);
} else {
listed = true;
$.ajax({
type: "GET",
url: "/adyen_list_customers",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#list-progress").show();
},
success: function (data) {
console.log(JSON.stringify(data));
$("#customer-list-area").hide().html(data["response_html"]).fadeIn(fadeTime).promise().done(function () {
$(".collapsible").collapsible();
resetDatepicker();
});
},
complete: function () {
$(document).on("change", "#file-download-datepicker", function () {
$("#file-download-progress").hide();
$("#file-download-date").val(selectedDate);
fileDownloadData = $("#file-download-form").serialize();
displayMessage(fileDownloadData);
$.ajax({
type: "POST",
url: "/adyen_update_file_list_by_date",
data: fileDownloadData,
beforeSend: function () {
$("#file-download-progress").show();
},
success: function (response) {
},
complete: function (response) {
$("#file-download-progress").hide();
console.log(response.responseText);
// Doesn't work. Selector should exist, but it doesn't.
$("#merchant-file-list").html(response.responseText);
},
error: function (response) {
displayMessage(response["responseText"]);
}
});
});
},
error: function (data) {
displayMessage(data);
},
});
}
} else if (selectedAcquirer === "stone") {
displayMessage("Adquirente indisponível no momento.");
} else {
displayMessage("É necessário selecionar uma adquirente.");
}
});
I get a perfect HTML response from the server, but selectors that were previously added with HTML also from the server (#file-download-progress, #merchant-file-list) are completely ignored. .html() doesn't work, nor anything, and I don't know how to use .on() to work around this because I just need to access that content. Since the ajax request is being made after the previous one is complete, they should be able to be accessed. They just don't exist nowhere in time.
I have an ASP.NET application where I am invoking a controller methode from JavaScript. My JavaScript code looks like this:
function OnNodeClick(s, e) {
$.ajax({
type: "POST",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (data) {
if (data != null) {
$('#GridView').html(data);
}
},
error: function (e) {
alert(e.responseText);
}
});
}
This calls the Home controller's DeviceManifests() method.
This is what the method looks like:
public ActionResult DeviceManifests(Guid selectedRepo)
{
var repoItem = mock.GetRepoItem(selectedRepo);
return View("Delete", repoItem.childs);
}
The method gets invoked but the problem is the Delete-View doesn't get rendered. There's no error, just nothing happens.
How can I update my code to get my desired behaviour?
Do like below code so if you have error you will have it in alert box or success result will rendered in DOM
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
dataType: "html",
success: function (data) {
if (data != null) {
$('#someElement').html(data);
}
}
},
error: function (e) {
alert(e.responseText);
}
});
You can do the redirect in the javascript side.
function OnNodeClick(s, e) {
$.ajax({
type: "GET ",
url: '#Url.Action("DeviceManifests", "Home")',
data: { selectedRepo: e.node.name },
success: function (msg)
{
window.location = msg.newLoc;
}
});
}
Make sure you include the redirect url in action and return JsonResult and not ActionResult. I'd also include pass the guid so that the destination Action and let it look up the data.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
i have this code that needs to populate an array that will be used on some diagramming tools. so there's a button that will show the results and a checkbox that enables the user to add another set of rows to the array. i use .push() for the array and it works. now, the problem is that the second push on my second ajax calls did not add the data to the array. here's my code:
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one fails
alert("pushed");
});
},
failure: function (data) {
alert(data.d);
}
});
drawChart(rows);
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});
i really don't know why it fails. what happens is that even if the condition is satisfied and the second ajax call succeeds, the contents of the array rows is still the first array push. what's the problem with the code?
the result you are getting is actually expected because of async nature of ajax
you should call the method within the success callback of the second ajax call like this
$.ajax({
type: "POST",
url: "Default.aspx/GetSubCategorySalesPerTerritory",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.each(response.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values); //this one works
});
if ($('#chkPromotion').is(":checked")) {
$.ajax({
type: "POST",
url: "Default.aspx/AddPromotion",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data.d, function (i, val) {
var values = new Array(val.From, val.To, val.Thickness);
rows.push(values);
});
drawChart(rows); // here
},
failure: function (data) {
alert(data.d);
}
});
} else {
drawChart(rows);
}
},
failure: function (response) {
alert(response.d);
}
});