synchronous ajax calls from jquery to mvc - asp.net-mvc

I have to generate several graphs and each graph data I should get it from mvc controller.
so I am using the below jquery to do ajax calls from jquery to mvc
$(".emailgraphs").each(function () {
YAHOO.Report.Print("Email", $(this).attr("responsefield"), $(this).attr("id"), $(this).attr("metricid"));
});
Print: function (name, graphid, divid, metricid) {
try {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: m_oReport.ds,
data: JSON.stringify(m_oReport.printp(name, graphid, metricid)),
beforeSend: function () {
//Displays loading image before request send, till we get response.
//$("#" + divId).addClass("loading");
},
success: function (data) {
// if they define a success function (s), call it and return data to it.
if (typeof m_oReport.prints === "function") {
m_oReport.prints(data, divid, name)
}
},
error: function (err) {
$("#" + divid).html(err);
}
});
}
catch (err) { alert("catch"); }
}
The problem is the calls are asynchronous. sometimes I am getting one graph and sometime 2 like that and sometimes nothing.
Is there any fix for this?

try to use something like this
function getDataSync() {
return $.ajax({
type: "POST",
url: remote_url,
async: false,
}).responseText;
}

Related

Making AJAX call to MVC API

I am trying to make an API call with ajax:
svc.authenticateAdmin = function (id, code) {
$.ajax({
url: 'api/event/authenticate',
data: { 'id': id, 'code': code },
datatype: 'json',
contentType: 'application/json',
type: 'GET',
success: function (data) {
App.eventBus.publish('authenticationComplete', data);
}
});
};
The method in the API Controller:
[ActionName("All")]
public bool Authenticate(int id, string code)
{
var repo = new MongoRepository<Event>(_connectionString);
var entry = repo.FirstOrDefault(e => e.Id == id);
return entry.AdminPassword == code;
}
But I am getting a 404 error: urlstuff/api/event/authenticate?id=123&code=abc 404 (Not Found)
I have copied the implementation from a number of known working calls (that I did not write). That look like:
svc.getEventFromCode = function (code) {
$.ajax({
url: '/api/event/',
data: { 'code': code },
dataType: 'json',
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedEvent', data);
App.eventBus.publish('errorEventCodeExists');
},
error: function () {
App.eventBus.publish('eventNotFound', code);
}
});
};
and
svc.getEventPage = function (pageNumber) {
$.ajax({
url: '/api/event/page/',
data: { 'pageNumber': pageNumber },
dataType: "json",
contentType: "application/json",
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedNextEventsPage', data);
}
});
};
But neither has to pass in 2 parameters to the API. I'm guessing it's something really minor :/
Your action name is called "Authenticate", but you have included the following which will rename the action:
[ActionName("All")]
This makes the URL
/api/event/all
The problem lies in your url.
Apparently, ajax interpret / at the start of the url to be root
When the application is deployed on serverserver, its URL is something like http://localhost:8080/AppName/
with api/event/page/, ajax resolve the URL to http://localhost:8080/AppName/api/event/page/ or an url relative to your current directory.
However, with /api/event/page/, the URL is resolved to http://localhost:8080/api/event/page/
Hope it helped.

Success and Error functions not firing in Ajax call

Below is an Ajax call I'm using to determine which menu options to show to users (I know it's a flawed method, just up against a time crunch for a demo). When the page loads, I can step through the controller method in Visual Studio so I know it's hitting the controller and sending back the right information.
Looking at Chrome's Network console I can also see that the browser received the right response. However, neither the console.log or the alert are firing. Nothing in the success or error methods is executed either. Does anyone see what's going wrong?
View
$(document).ready(function ($) {
//Determine which links to show in navbar
window.onload = function () {
$.ajax({
type: 'GET',
url: '#Url.Action("CheckSecurity","Home")',
dataType: 'json',
succcess: function (data) {
console.log(data);
alert(data);
if (data == "admin") { $('#adminLink').show(); }
else if (data == "IT") { $('#ITLink').show(); }
else if (data == "viewer") { $('#viewerLink').show(); }
else if (data == "modifier") { $('#modifierLink').show(); }
},
error: function (data) {
alert("error");
}
});
};
Controller
[HttpGet]
public JsonResult CheckSecurity()
{
if (Security.IsAdmin(User)) return Json("admin", JsonRequestBehavior.AllowGet);
if (Security.IsItSupport(User)) return Json("IT", JsonRequestBehavior.AllowGet);
if (Security.IsViewer(User)) return Json("viewer", JsonRequestBehavior.AllowGet);
if (Security.IsModifier(User)) return Json("modifier", JsonRequestBehavior.AllowGet);
return Json("NA", JsonRequestBehavior.AllowGet);
}
Here are a couple screen shots of the Network and regular console in Chrome. Bother are from after I've stepped through the controller method and the program has returned a value back to the browser.
Network Console
Standard Console
There is an extra c in your
succcess:
So the response is a 200 request , but because you have no mapping for success defined, it is just never logged
It is success instead of succcess
NealR
Deprecation Notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks
will be deprecated in jQuery 1.8. To prepare your code for their
eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always()
instead.
Check the done, fail and always callbacks below.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
}).fail(function (data) {
debugger;
}).always(function(data) {
alert("complete");
});
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8.
In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown).
This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).always(function(data) {
alert("complete");
});
.ajax().done(function(data, textStatus, jqXHR){});
Replaces method .success() which was deprecated in jQuery 1.8.
This is an alternative construct for the success callback function above. Refer to deferred.done() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
});
.ajax().fail(function(jqXHR, textStatus, errorThrown){});
Replaces method .error() which was deprecated in jQuery 1.8.
This is an alternative construct for the complete callback function above. Refer to deferred.fail() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).fail(function (data) {
debugger;
});
Check here for more details
Check here for the documentation details

Passing Multiple Checkbox value using jquery ajax

I am displaying multiple records on my ASP.NET MVC 4 view where each record has a checkbox. I want the user to be able to select multiple records (by checking checkboxes) and click Delete button in order to delete them. So far I can call the Delete Action method via jquery ajax but the problem is my action method does not seem to be accepting the passed array.
Here is my jquery code:
$(function () {
$.ajaxSetup({ cache: false });
$("#btnDelete").click(function () {
$("#ServicesForm").submit();
});
$("#ServicesForm").submit(function () {
var servicesCheckboxes = new Array();
$("input:checked").each(function () {
//console.log($(this).val()); //works fine
servicesCheckboxes.push($(this).val());
});
$.ajax({
url: this.action,
type: this.method,
data: servicesCheckboxes,
success: function (result) {
if (result.success) {
}
else {
}
}
});
return false;
});
});
and here is my action method:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
if (deleteservice != null)
{
//no hit
}
}
What am I missing?
Edit
I also tried console.log(servicesCheckboxes); before $.ajax() which outputs ["3", "4"] but still get null when I pass data as specified in answer below data: { deleteservice: servicesCheckboxes }. Even I tried data: [1,2] but still action method shows null for deleteservice in action method.
Just pass the array to your action:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: { deleteservice: servicesCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
Or, just use the serialize() jquery method to serialize all fields inside your form:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: $(this).serialize(),
success: function (result) {
if (result.success) {
}
else {
}
}
});
In your controller:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
bool deleted = false;
if (deleteservice != null)
{
// process delete
deleted = true;
}
return Json(new { success = deleted });
}
Finally got it working. "MVC detects what type of data it receive by contentType" as explained here so I made the following changes to $.ajax()
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
//data: { deleteservice: servicesCheckboxes }, // using the parameter name
data: JSON.stringify({ deleteservice: servicesCheckboxes }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});

JQuery: $.ajax calls seem to be blocking image download

I have a series of AJAX calls that are fired to the web server to load more information after the DOM is loaded (I wrap the calls in the $.ready function). However, it still seems to be blocking. I did not set the async option in my code. Am I doing something wrong here? Below are my code:
$(document).ready(function() {
var places = #{#results.to_json};
Places.SERP.initialize(places);
});
In my serp.js where the Places.SERP.initialize(places) is defined:
initialize = function(places) {
initMap(places);
initDeals(places);
initFriends(places);
};
In the 3 init* calls, I have numerous $.ajax calls to fetch more information from the server. The code looks something like this:
$.ajax({
type: "GET",
timeout: 1000,
url: url,
dataType: "json",
success: function(retval) {
if (retval) {
var data = retval.data;
if (data) {
var stats = data.stats,
friends = data.friends;
if (stats) {
$("#places-" + internalId).find(".checkins-wrapper").
hide().
append(template({
checkinCount: stats.checkinsCount
})).
fadeIn();
}
}
}
},
error: function(jqXHR, status, errorThrown) {
}
});

how do I get the form data in a javascript object so I can send it as the data parameter of an $.ajax call

How to return json after form.submit()?
<form id="NotificationForm" action="<%=Url.Action("Edit",new{Action="Edit"}) %>" method="post" enctype="multipart/form-data" onsubmit='getJsonRequestAfterSubmittingForm(this); return false;'>
<%Html.RenderPartial("IndexDetails", Model);%>
</form>
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").submit(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
I guess what you're actually looking for is not the Submit method, but how to serialise the form data to a json object. To do this you have to use a helper method like here: Serialize form to JSON
Use this instead of running the submit() method, and you'll be fine.
Also, this question is a duplicate of this (even though the question text, and the title are completely misleading): Serialize form to JSON with jQuery
Posting the jQuery extender, just in case, so that it doesn't get lost :)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
After you have this in your page, you can update your ajax call with this:
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").serializeObject(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
UPD: If you want to POST the form, then get the response as a json object, and do another ajax call.. then you should look at the jquery.form plugin. you will be able to post your form using an ajax call, then get the response, and run some js when it will return.

Resources