So I have a number inside a div like this
<div style="display:inline" id="contItems">0</div>
and I am updating this number depending on the amount of items there are inside this cart from the controller and I am returning an Int and I need to replace the number inside the Div with the new Int, so I did this Ajax request:
function CountItemsDiv() {
$.ajax({
type: "GET",
url: '/Cart/CountItems',
cache: false,
success: function (data) {
$('#contItems').html(data);
}
});
}
and I call this function CountItemsDiv() when page loads and also when the user adds or removes a product and it works... but not all the times, sometimes it will change the number but some others it will not, I would say it would work 60% of the times someone would click on Add or Remove, I've tried to set cache to false but it still does it, what else could this be?
Yes, you need async function in false,async false waiting for request with all items.
function CountItemsDiv() {
$.ajax({
type: "GET",
url: '/Cart/CountItems',
cache: false,
async : false,
success: function (data) {
$('#contItems').html(data);
}
});
}
Related
newbie developer here and this is actually my first question on stack overflow. I'm in my first role as a developer and I've been given the task of finishing off an app that someone else started and I'm having a hard time getting the page to refresh when the users click a particular button.
The page has a list of items and each item has a checkbox next to it that users can put a check mark into and then click the Remove Items button. In theory clicking that button is supposed to refresh the page when it's done, or at least refresh the section of the page that contains the list..as far as I can tell. And the item is being removed, but the refresh isn't working so users are having to manually refresh the page before the items they chose to remove actually disappear off the screen.
Here's what's behind the button in controller:
[HttpPost]
public ActionResult UpdatePartStatus(List<tblPart> parts, tblArea area)
{
_LookupService.UpdatePartStatus(parts);
// return RedirectToAction("Details", area);
// return Redirect("~/Details");
return RedirectToAction("Parts", "Menu", false);
// <% return Response.Redirect(Request.RawUrl); %>
// return Response.Redirect(Request.RawUrl);
// return Page.Redirect(Page.Request.RawUrl, false);
// return Redirect(Request.UrlReferrer.ToString());
// return View();
// return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
}
The first line that's commented out is the way the previous developer left it. All the other lines that are commented out are the things I've tried so far, none of which worked. And the one that isn't commented out just happens to be the last one I tried before posting this. Most of those attempts are the results of searching around here on stack overflow
And here's the script from the Details view:
<script>
$('#btnAjax').click(function () {
....validation code I removed for this post....
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json'
})
}
});
</script>
And here's the MapRoute code that I've seen referenced in several other posts on this topic:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Parts", action = "Menu", id = UrlParameter.Optional }
The last thing the previous developer said before they left was that this is all standard MVC, nothing out of the ordinary but I'm running out of ideas.
I appreciate any thoughts or advice anyone can offer.
Thanks
The code you shared in question does not have anything to reload the current page. Looks like you are making an ajax form submit to the server. So it does not really make sense to return a redirect response from that.
If you want to reload the page, you can do that in the done event of the ajax call.
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(res){
window.location.href = window.location.href; // This will reload the page
}).fail(function(a, b, c) {
console.log('ajax call failed');
});
But again, If you are reloading the page what is the point of doing the ajax post ? Instead of realoding the page, you may simply remove the specific DOM element(s) you removed using javascript. This will give the user a partial page update experience without the entire page reload.
If you know the Id of the item you removed, you can use that in your jQuery selector to remove it.
var idOfDeletedItem = "someDomElementId";
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function(res){
// Let's remove that DOM element from the DOM
$("#"+idOfDeletedItem).remove();
}).fail(function(a, b, c) {
console.log('ajax call failed');
});
Simply add a success function to the ajax request:
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json',
success: function() {
location.reload();
}
})
If you are using Ajax, then you should use
public JsonResult UpdatePartStatus(List<tblPart> parts, tblArea area)
{
_LookupService.UpdatePartStatus(parts);
return Json(null); //This will always return a null result to your ajax call indicating a success
}
For me, I usually do return json result this way :
try {
LookupService.UpdatePartStatus(parts);
return Json(new { Success = true});
}
catch {
return Json(new { Success = false});
}
And in your ajax call, do this:
$.ajax({
type: 'post',
url: '/Parts/UpdatePartStatus',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json',
success: function(result) {
if (result.Success)
location.reload();
} else {
alert("Delete failed");
}
}
})
im trying to get the value each time a client selects a option from my Dropdown list to send it back to controller where i use the value on creating a file and then refreshing the page but im unable to do so
This is my Dropdownlist:
<select id="sel0">
<option value="">Todos</option>
#foreach (var item in Model.Select(l => l.Fecha).Distinct())
{
<option value="#lines">#lines</option>
}
</select>
This is my Ajax Call:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
});
$("form").submit(function () {
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
and this is my Controller its named 'HomePosController':
public ActionResult MethodName(string Selected)
{
var db = new ArponClientPosContext();
String value = Selected;
var json4 = JsonConvert.SerializeObject(Selected);
System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\potzolcalli.brain.arpon.com\valorselected.txt", json4);
return View("~/Views/HomePos/Index.cshtml", db.Pos.ToList());
}
But whenever y select a option of my dropdown nothing happens, the page its not refreshed nor the file is created what am i doing wrong?
If you want it to be on dropdown change then you have to send ajax call in change event :
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePos")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
and you have to not write complete Controller class name, you have to skip the Controller postfix, it is convention which is followed by Url helpers in mvc, that way your url generated will be wrong and ajax call will fail.
whenever y select a option of my dropdown nothing happens
Well, this happens:
dataTable.columns('.fechas').search(this.value).draw();
But that doesn't invoke the AJAX request. It doesn't do much of anything, really.
how can i trigger the ajax ? i want it to trigger after a value is changed in the dropdown list
In that case you want to do that on the select element's change event. Currently you perform the AJAX request here:
$("form").submit(function () {
// AJAX
});
That is, you perform the request in the form's submit event. Just add it to the drop down's change event instead:
$('#sel0').on('change', function () {
dataTable.columns('.fechas').search(this.value).draw();
$.ajax({
url: '#Url.Action("MethodName","HomePosController")',
type: 'POST',
cache: false,
data: { Selected: $("#sel0").val() },
success: function (data) {
//
}
});
});
the page its not refreshed
Well, no. That won't happen in an AJAX request. Currently your success callback is empty, so nothing will happen on the page. Whatever you want to happen would need to be put in that callback.
Summery: I have to get several data from a service(hosted on multiple servers) using C# and finally display them to the user/s, all on one page, using ajax call. Consider that the final display formats contains charts and progresses that have created by Jquery and styled by CSS.
Some Code:
// Once Called Here and Timer Will Go On
UpdateDataA();
function UpdateDataA() {
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var $s = $(".second");
$s.val(r.d[0]).trigger("change");
updateProgressA(r.d[1]);
updateProgressB(r.d[2]);
updateNetworkData(bytesToSize(r.d[5], 2), bytesToSize(r.d[6], 2));
},
error: function (msg) {
alert(msg.error);
}
});
setTimeout(function () { UpdateDataA(); }, 1000);//Timer
}
Consider more calls like this.
Problem: Timer intervals doesn't update at intervals have set. One element updates correct then waits for others to complete while it shouldn't. But I need to update all continuously together. In this way, if one call crash, Others will be die.
Question: What can I do or What are my faults?
Note: I'm new to jquery and ajax.
Thank You previously
Neglect my comment about interval. I think u will need to keep track of your timers :
timerA = setTimeout(function () { UpdateDataA(); }, 1000);
and clear the in the update function till task is complete
var timerA;
// Once Called Here and Timer Will Go On
UpdateDataA();
function UpdateDataA() {
clearTimeout(timerA);
$.ajax({
type: "POST",
async: true,
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var $s = $(".second");
$s.val(r.d[0]).trigger("change");
updateProgressA(r.d[1]);
updateProgressB(r.d[2]);
updateNetworkData(bytesToSize(r.d[5], 2), bytesToSize(r.d[6], 2));
timerA = setTimeout(function () { UpdateDataA(); }, 1000);//Restart time after task is complete
},
error: function (msg) {
alert(msg.error);
}
});
}
I'm using ajax to check whether there is no new alerts stored in my sql database. I've set it to run every 30 seconds but instead it keeps on calling the function that checks the database every second. Here is my code.
This is code in the view. "_Tasks" is my partial view and it will be the view that is going to be updated. I haven't done anything for a success return because it never reaches that code.
#Html.Action("_Tasks")
<script type="text/javascript">
(function poll() {
$.ajax({
type: 'GET',
cache: false,
url: '#Url.Action("TasksRefresh")',
dataType: "json",
complete: poll,
timeout: 30000,
success: function (data) {
if (data.success == true)
alert("Hello");
}
});
})();
</script>
This is in the controller
public JsonResult TasksRefresh()
{
var alerts = getAlerts();
var cache = HttpRuntime.Cache["Tasks"];
if ( cache == alerts)
{
return Json(new
{
success = false,
});
}
else
{
return Json(new
{
success = true,
// View = this.Re
});
}
}
Try this:
(function poll() {
$.ajax({
type: 'GET',
cache: false,
url: '#Url.Action("TasksRefresh")',
dataType: "json",
complete: function () { setTimeout(poll, 30000); }, // Changed, call poll again when 30s has pasted
timeout: 30000, // This just says it fails if the request takes more than 30s
success: function (data) {
if (data.success == true)
alert("Hello");
}
});
})();
Timeout is not a delay. Timeout is how long it should wait before considering the request a failure. By setting complete to poll, you are telling it to immediately make another call. You need to put a delay in your complete function.
What I can guess is, you are executing the poll function again on complete of the ajax call. It might just take a second to complete that ajax call. You can use the timer at javascript code. try using settimeout or setInterval. And do ajax call in that timer. See if is helpful.
timeout: 30000 is just to make sure that your ajax call would wait for response for maximum of that much time.
You are executing your poll function as soon as ajax call completes that is why calls are made so quick.
I have a dialog in an ASP.Net,c# application.This dialog has a textbox.When I choose save I want to call a function from C# who makes some verifications in the database and then to get the result in javascript/jquery.If the inserted value is true I want to close the dialog other way to remain opened,but I can't succed to close the dialog box after i receive true from c# function.Below is the code:
ascx :
<div id="popup" title="Choose Delegate">
<label>Delegate<label><input type="textbox" value="" name="inputD" id=="inputD"/>
</div>
Javascript:
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
$(this).dialog("close");
},
failure: function () {alert("FAIL"); }}); }
});
}
C#:
[WebMethode]
public static Boolean check(string delegate)
{
.....
return true;
}
C# methode returns corect value.
I try also this :
$('#btnAdd').click(function(e){
$('#divPopup').slow("show");
$('#divPopup').dialog({
height:150,
width:300,
modal:true,
buttons:{
"close":function(){$(this).dialog("close");}
"save":function(){
var obj=document.getElementid("inputD");
var rez ;
$.ajax({
type: "POST",
url: "add.aspx/check",
data: "{delegate: '" + obj.Value+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
rez= "OK";
},
failure: function () {alert("FAIL"); }
});
if (rez="OK")
$(this).dialog("close");
}
});
But it doesn't see the rez value in this case.
Thanks !
You can use an Ajax Call in your "save":function(e) and just check the returned value if true close dialog, else remain opened
Ajax calls are really simple to implement, I let you search that :)
You need a web-service on the server side. (preferably REST)
http://restsharp.org/ is an easy to use library for that.
Take a look at this question for more info.
In the front end you make an ajax call to you're REST api (I see you use jquery so it won't be that hard ;))