Asynchronous AJAX calls (multiple) - javascript

I posted this yesterday but i may not have explained my situation well.
I have 3 grids on a page that are built dynamically through JavaScript.
I then have 3 separate JavaScript methods to set a session when a row is clicked in a certain grid.
Once the session is set i would like it to navigate to the next page.
Here is what i have
OnClick event
$('#clinician-planned').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetPASession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-recent').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetRDSession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-theatre').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetTESession", "Clinician")';
AjaxCall(Location, ID);
});
AJAX Post To Controller
function AjaxCall(Location, ID) {
alert('1');
$.ajax({
type: 'POST',
url: Location,
dataType: 'text',
async: false,
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).done(function (response) {
alert('2');
location.href = "#Url.Action("Summary", "Patient")" + "/" + ID;
});
}
Here are the controller methods
public ActionResult SetPASession()
{
Session.Remove("Clinician");
Session["Clinician"] = "pa";
return Json(null);
}
public ActionResult SetRDSession()
{
Session.Remove("Clinician");
Session["Clinician"] = "rd";
return Json(null);
}
public ActionResult SetTESession()
{
Session.Remove("Clinician");
Session["Clinician"] = "te";
return Json(null);
}
The problem i have is when the row is clicked "alert('1'); shows instantly, however it seems like it takes a while and waits for all grids to be populated before the 2nd alert appears. I have tried putting async: false, but this doesnt seem to work.
Any ideas would be much appreciated.

Related

Redirect to View(ActionResult) with complex object as paremeter from Javascript

I have to perform following operation.
On a button click from View1, do Ajax request and get complex object as return.
Pass this object to View2 as parameter.
Process the data sent from view1 in client side(inside $(window).load()).
Below is my code:
View1 :
var Url = baseUrl() + "/InteractiveReport/GetRatingProfitData/";
$.ajax({
type: "POST",
url: Url,
contentType: "application/json; charset=utf-8",
dataType: "html",
// dataType: "json",
data: JSON.stringify({ "Projects": SelectedProjectinfo }),
success: function (JsonData) {
debugger;
var w = window.open('about:blank');
w.document.open();
w.document.write(JsonData);
w.document.close();
},
error: function (retVal) {
alert("error:" + retVal.responseText);
}
});
InteractiveReportController :
public ActionResult RatingProfitReport(ProfitRatingInfoModel RatingProfitData)
{
return View("RatingProfitReport", RatingProfitData);
}
public ActionResult GetRatingProfitData(IRSelectedProjectInfoModel Projects)
{
ProfitRatingInfoModel RatingProfitData = new ProfitRatingInfoModel();
//GET RatingProfitData from Database
return RatingProfitReport(RatingProfitDataMdl);
//var jsonSerializer = new JavaScriptSerializer();
//string response = jsonSerializer.Serialize(RatingProfitDataMdl);
//return Json(response, JsonRequestBehavior.AllowGet);
}
View2 :
#using Enterprise_Dashboard.Models
#model ProfitRatingInfoModel
<script>
//Control not entering this section
$(document).ready(function () {
init_bind_rating_profit_table();
});
function init_bind_rating_profit_table()
{
debugger;
var RatingProfitData = #Model.ProfitRatingData;
alert(RatingProfitData[0].BU);
}
</script>
Is there any better way to redirect to different view from Ajax call with parameters.
from my View1, if i directly make Ajax call to View2, i cannot pass complex object as parameter, since its too big string.
Is there any way i can set RatingProfitDataMdl into Session or ViewBag or ViewData or anything else and i can access it in View2?
OR
Is there any way i can eliminate Ajax call on button click so button click on View1 will automatically call GetRatingProfitData and it internally redirects to RatingProfitReport with modal object parameter?
OR
Completely different approach available to handle this scenario?

Multiple AJAX calls and show div on finish

I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});

Json GET is not showing the details in popup

I am trying to show the details of each Student with Json and I think it is not going to the ajax part.
It shows the id and the url when I console.log() them, but I get this error message for the ajax part
I don't know what's missing or where is the issue?
This is my html link
#Html.ActionLink("Details", "StudentDetails", new { id = item.ID }, new { #class = "modalDetails", #id = item.ID })
script
<script type="text/javascript">
$(function () {
$(".modalDetails").click(function (e) {
e.preventDefault(); //stop the default action upon click
var id = $(this).attr('id');
console.log(id);
var url = $(this).attr("href");
console.log(url);
$.ajax({
type: 'GET',
data: { id: id },
dataType: "json",
url: url,
success: function (data) {
$(".modalDetails").append('<span> First Name: ' + data.firstName + '</span></br>');
console.log("success");
}
});
$('#myModal').modal('show'); // show the modal pop up
});
});
</script>
StudentController
public JsonResult StudentDetails(int id)
{
Student student = studentRepository.GetStudentByID(id);
var json = new{
firstName = student.FirstMidName
};
return Json(json, JsonRequestBehavior.AllowGet);
}
Everything was fine, except that I needed to build the solution and append the details to the modal-body. Sometimes it is just a simple fix.

unable to post id of selected dropdown to controller through knockout function

This is my Post function something like this:
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.NeighbourhoodId = data.id || "";
This is my simple function in knockout. Here at the last line u can see, data: ko.toJson(post)
self.addPost = function () {
var post = new Post();
post.Message(self.newMessage());
return $.ajax({
url: postApiUrl,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: ko.toJSON(post)
})
.done(function (result) {
self.posts.splice(0, 0, new Post(result));
self.newMessage('');
})
.fail(function () {
error('unable to add post');
});
}
Now, along with this, i want to pass dropdown selected id something like this:
data: { id: $("#Locations").val() }
Right now, i have tried using this:
data:{post: ko.toJSON(post), id: $("#Locations").val() }
but in controller, post: ko.toJSon(post) is sending nothing however i am getting id of selected dropdown but not the message property of post parameter.
If i use this line:
data: ko.toJSON(post)
then i can get every property of post parameter but then id is null so, how to deal with this.Plzz Plzz help me out.Debugger is showing nothing useful information.My Post Controller is:
public JsonResult PostPost(Post post, int? id)
{
post.PostedBy = User.Identity.GetUserId<int>();
post.NeighbourhoodId = id;
db.Posts.Add(post);
db.SaveChanges();
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
NeighbourhoodId = post.NeighbourhoodId
};
return Json( ret,JsonRequestBehavior.AllowGet);
}
on my view page,this is the button on which click event i fired addPost function
<input type="button" data-url="/Wall/SavePost" id="btnShare" value="Share" data-bind="click: addPost">
along with this, dropdown for sending id is something like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
<script type="text/javascript">
$(document).ready(function () {
$("#btnShare").click(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("PostPost", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
Plzz someone help me out.I am not getting what to do from here.

ASP.NET MVC - Javascript array always passed to controller as null

I'm having some problem with passing a javascript array to the controller. I have several checkboxes on my View, when a checkbox is checked, its ID will be saved to an array and then I need to use that array in the controller. Here are the code:
VIEW:
<script type="text/javascript">
var selectedSearchUsers = new Array();
$(document).ready(function () {
$("#userSearch").click(function () {
selectedSearchUsers.length = 0;
ShowLoading();
$.ajax({
type: "POST",
url: '/manage/searchusers',
dataType: "json",
data: $("#userSearchForm").serialize(),
success: function (result) { UserSearchSuccess(result); },
cache: false,
complete: function () { HideLoading(); }
});
});
$(".userSearchOption").live("change", function () {
var box = $(this);
var id = box.attr("dataId");
var checked = box.attr("checked");
if (checked) {
selectedSearchUsers.push(id);
}
else {
selectedSearchUsers.splice(selectedSearchUsers.indexOf(id), 1);
}
});
$("#Send").click(function () {
var postUserIDs = { values: selectedSearchUsers };
ShowLoading();
$.post("/Manage/ComposeMessage",
postUserIDs,
function (data) { }, "json");
});
});
</script>
When the "Send" button is clicked, I want to pass the selectedSearchUsers to the "ComposeMessage" action. Here is the Action code:
public JsonResult ComposeMessage(List<String> values)
{
//int count = selectedSearchUsers.Length;
string count = values.Count.ToString();
return Json(count);
}
However, the List values is always null. Any idea why?
Thank you very much.
You might try changing the controller's action method to this:
[HttpPost]
public JsonResult ComposeMessage(string values)
{
JavaScriptSerializer jass = new JavaScriptSerializer;
AnyClass myobj = jass.Deserialize<AnyClass>((string)values);
...
...
}
I believe that you have to take the JSON data in as a string and do the conversion
manually. Hope it helps. Cheers.

Categories