MVC partial view update from ajax success - ajax

On the main page in the view the user selects a project and that selection fills up a partial view (call it first partial) with data. In this partial view the user can also select an item which provides an editing partial view under below the previous one. Here a new item can be added, updated or deleted.
The question is: when a new item added the first partial view should be updated. The method how I am trying to achieve it is like this:
function addBottle() {
var code = $("#Code").val();
var desc = $("#Description").val();
var id = $("#ProjectId").val();
$.ajax({
url: "#Url.Action("AddBottleType", "Managers")",
data: { code: code, desc: desc, id: id },
type: "POST",
datatype: "text",
success: function (data) {
if (typeof data == "undefined") {
alert("Something went wrong. Sorry!");
}
if (data.Success) {
$.alert(data.Data, "Success!");
$.ajax({
url: "#Url.Action("BottleTypes", "Managers")",
data: { projectId: id },
type: "GET",
datatype: "text",
});
} else {
$.alert(data.Data, "Warning!");
}
}
});
};
This gives me the data in the controller, but the view is not updated. Probably this is not the best way, I am open the suggestions, solutions.
I've also done my part, google and stackoverflow is my friend, but none of the solutions worked.

You need to load it into your div. Something like this. Check for success in your controller action so you need not do Success() in the front end:
function addBottle() {
var code = $("#Code").val();
var desc = $("#Description").val();
var id = $("#ProjectId").val();
$.ajax({
url: "#Url.Action("AddBottleType", "Managers")",
data: { code: code, desc: desc, id: id },
type: "POST",
datatype: "text",
success: function (data) {
if (typeof data == "undefined") {
alert("Something went wrong. Sorry!");
}
if (data.Success) {
$.alert(data.Data, "Success!");
$("#bottleTypes").load("/Managers/BottleTypes", { projectId: id });
} else {
$.alert(data.Data, "Warning!");
}
}
});
};

Related

Kendo DataSource catch server response

In my kendo dataSource > transport > update. I want to catch a server response status (refer image), but none of this methods trigger an alert. Any idea why?
update: {
url: "./getRevenueAccounts.php",
type: "POST",
data: function() {
return {
method: "editRevenueAccounts"
}
},
success: function(e) {
if(e.status == 'duplicate'){
alert('Trigger 1');
}
},
error: function(e) {
if (e.errorThrown == 'duplicate') {
alert("Trigger 2");
}else if(e.status == 'duplicate' ){
alert("Trigger 3")
}
},
complete: function (e) {
if(e.status == 'duplicate'){
alert('Trigger 4');
}
}
},
console.log(e) screen shot
Try the following code for your success function:
success: function(e) {
if(e.responseText.status == 'duplicate'){
alert('Trigger 1');
}
},
Essentially, you are looking at the status property when you should have been looking at the responseText property to get the status (which is another property on that object).
You need to make an ajax call inside the update function.
Like:
var dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
/* implementation omitted for brevity */
},
update: function(options) {
// make JSONP request to https://demos.telerik.com/kendo-ui/service/products/update
$.ajax({
url: "https://demos.telerik.com/kendo-ui/service/products/update",
dataType: "jsonp", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
// send the updated data items as the "models" service parameter encoded in JSON
data: {
models: kendo.stringify(options.data.models)
},
success: function(result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
schema: {
model: { id: "ProductID" }
}
});
For more details please check this from telerik documentation: https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/configuration/transport.update
Is not a good method to apply, but it works to fetch the response.
if(e.responseText=='{"status":"duplicate"}'){
kendo.alert('duplicate data');
}

Ajax GET call in a razor page not breaking inside the method in the controller

I have the following javascript using ajax:
function MoveToWeek(weekIndex) {
if (weekIndex == 1) {
var index = #Model.WeekIndex;
index = index+1;
$.ajax({
url: '#Url.Action("RenderCalendar", "Calendar")',
data: { weekIndex: index },
type: "GET",
success: function (data) {
$("#RenderCalendarArea").html(data);
}
});
}
else if (weekIndex == -1) {
var index = #Model.WeekIndex;
index = index+-1;
$.ajax({
url: '#Url.Action("RenderCalendar", "Calendar")',
data: { weekIndex: index},
type: 'GET',
success: function (data) {
$('#RenderCalendarArea').html(data);
}
});
}
}
And the following method in my controller "CalendarController":
[HttpGet]
public ActionResult RenderCalendar(int weekIndex = 0)
{
//..snip
}
I have confirmed the ajax code runs (if I put a javascript breakpoint on the $.ajax line, it'll break there). In addition the values in the ajax method do seem to be set correctly. In the debugger the javascript method has been compiled as such:
function MoveToWeek(weekIndex) {
if (weekIndex == 1) {
var index = 0;
index = index+1;
$.ajax({
url: '/Calendar/RenderCalendar',
data: { weekIndex: index },
type: "GET",
success: function (data) {
$("#RenderCalendarArea").html(data);
}
});
}
else if (weekIndex == -1) {
var index = 0;
index = index+-1;
$.ajax({
url: '/Calendar/RenderCalendar',
data: { weekIndex: index},
type: 'GET',
success: function (data) {
$('#RenderCalendarArea').html(data);
}
});
}
}
However, when this code runs, it does not break inside the method in the controller. Can anyone see why this doesn't work?
This particular partial view didn't use the layout file... which meant it didn't import the jquery lib. That's why it didn't work. Ooops.

Restructuring nested ajax calls so variables work

My "value" variables below are not being inherited into the second call. What is the recommended way to reconstruct this so that it works?
First, I get all the data from our data table. Then, I need to get pending changes from a completely different database (change control). I need to display the second data if it exists.
function getData(appid) {
$.ajax({
url: 'services/getData',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data) {
var field1Value = data.field1;
var field2Value = data.field2;
var field3Value = data.field3;
//get pending changes
$.ajax({
url: 'services/getPendingChanges',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data2) {
if (data2.field1 <> '') { field1value = data2.field1 };
if (data2.field2 <> '') { field1value = data2.field2 };
if (data2.field2 <> '') { field1value = data2.field2 };
},
complete: function () {
//set data in UI regardless of whether it came from getData or getPendingChanges
$('#txtField1').html(field1value);
$('#txtField2').html(field2value);
$('#txtField3').html(field3value);
}
})
}
})
}
of course when I do this, all the "*value" variables are undefined.
Unsure whether this will help you at all (and it probably won't), but this is what I've learned in my time in Javascript. But the nature of anon classes in javascript are so that you can use them without worry of variable collisions. The easiest way is that you funnel up to a higher scope variable to use later. But that's generally bad practice... So you could throw a wrapper around all that...
I ended up hiding the fields then calling the second ajax from the complete of the first. I set the fields in the success of the first call and also in the success of the second call, if they exist. Then I unhide them in the complete of the second.
function getData(appid) {
$('#txtField1').hide();
$('#txtField2').hide();
$('#txtField3').hide();
$.ajax({
url: 'services/getData',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data) {
var field1Value = data.field1;
var field2Value = data.field2;
var field3Value = data.field3;
$('#txtField1').html(field1value);
$('#txtField2').html(field2value);
$('#txtField3').html(field3value);
},
complete: function () {
//get pending changes
$.ajax({
url: 'services/getPendingChanges',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data2) {
if (data2.field1 <> '') {
field1value = data2.field1
$('#txtField1').html(field1value);
};
if (data2.field2 <> '') {
field2value = data2.field2
$('#txtField2').html(field2value);
};
if (data2.field3 <> '') {
field3value = data2.field3
$('#txtField3').html(field3value);
};
},
complete: function () {
$('#txtField1').show();
$('#txtField2').show();
$('#txtField3').show();
}
})
}
})
}
Ultimately instead of hiding them I would swap them out with a loading indicator. Also, I realize the BEST thing to do would be have a single web service that did all the logic in the background and just returned the appropriate data.

Kendo UI reload treeview

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

asp.net mvc ajax crazy

From a page Index.cshtml, i have a very simple ajax call
controller1 and controller2 have the same action:
public ActionResult abc(string name)
{
return new JsonResult()
{
Data = new
{
success = true,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
}
};
}
$(document).ready(function ($) {
$.ajax({
url: '#Url.Action("abc", "controller1")',
type: 'POST',
data: { name: 'John' },
dataType: 'json',
success: function (result) {
if (result.success) {
alert("ok");
}
else {
alert(result.error);
}
}
});
});
not work
however using exactly the same syntax, just change the controller, it works !!!.
abc action is the same.
$.ajax({
url: '#Url.Action("abc","controller2")',
type: 'POST',
data: { name: 'John' },
dataType: 'json',
success: function (result) {
if (result.success) {
alert("ok");
}
else {
alert(result.error);
}
}
});
it drives me crazy, don't know what happen. On a new project, i tried the same code, it works perfectly, but not on my current work.

Resources