JQuery: $.ajax calls seem to be blocking image download - ruby-on-rails

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) {
}
});

Related

I get 401 (Unauthorized) and Invalid HTTP status code 401 for the POST/OPTIONS call. Works on POSTMAN/RESTCLIENT

I'm new to Jquery and JqueryMobile . I'm having a bit of a trouble and was hoping someone here would help me. From what I understand, before I can actually do "POST", the browser does a "preflight" OPTIONS call. The problem with me is that the OPTIONS call fails with 401. I tested the api with RESTclient and POSTMAN and it works for just "POST".
I have one more block of code which is similar and makes a call to get the authorization token(authtoken). The only difference between this block and the other block are
1) Data block.
2) BeforeSend block.
The code for making the call.
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "https://myurl/api/APIName",
beforeSend: function (request)
{
request.setRequestHeader('AuthToken', "This is where I'll insert my authtoken");
request.setRequestHeader('Content-Type', "application/json");
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
data: {FirstName: "Albert", LastName: "Einstein"},
dataType: 'json',
success: function (response) {
alert(response.APIStatus.ErrorCode);
},
error: function () {
alert(response.APIStatus.ErrorCode;
}
});
The code to get Authorization Token. This block does its work without any issue.
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "https://myurl/api/THEURLTOAUTHENTICAREME",
beforeSend: function () {
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
data: {username: "Nickolas", Password: "Te$l#"},
dataType: 'json',
success: function (response) {
if (response.AuthToken) {
alert(response.AuthToken);
}else {
alert(response.APIStatus.Message);
}
},
error: function () {
alert("Woops");
}
});
I'm not the one whose working on the api piece of the application, but I do know the person who are working on it.
The first block needs to have an "authtoken" in the header and that's the reason why I'm doing request.setRequestHeader('AuthToken', "This is where I'll insert my authtoken");. Am I doing this wrong?
Hitting the API in Postman: http://i.imgur.com/rEk3rAr.png
Console/Inspector from Chrome: http://i.imgur.com/vfSHqR4.png
Please help me!

synchronous ajax calls from jquery to 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;
}

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.

Ajax sucess function not called (returning data)

I have a simple $.ajax call that i did a million times before
$.ajax({
type: "POST",
url: url,
data: data,
sucess: function (data) {
alert(data);
}
});
and a controller that accepts my data without a problem but i can't seem to return data to the sucess function.
[HttpPost]
public ActionResult MyAction(MyClass data)
{
//do something
return Content("blabla");
}
What seems to be the problem?
EDIT:
Everything was ok but i wrote sucess instead of success.
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
alert(data);
}
});
It could be that you need to return a json-p style response... if the javascript and server side code are running on different domains then this is almost certainly the case.
Take a looks at http://api.jquery.com/jQuery.ajax/ for some more details.
I suggest you try :
$.ajax({
type: "POST",
datatype: "text",
async: false,
url: url,
data: data,
sucess: function (data) {
alert(data);
}
});
The idea is if you ask for a synchronous call and request type of text then it should get around the jsonp / callback issue.
Hopefully worth a try :)

Url pathname issue in Ajax Post

In development I make an Ajax post which works in development. However when I put it on the Test server it doesn't work because IIS has assigned the application a subfolder, and this is missing in my development environment.
I have found work around (see below) but I am the first to admit this should not be the solution, as I have to remember to call a function for the url everytime I make an Ajax call.
There must be a better way.
However the code will show you what I am fixing;
function OperationsManagerFlagClickFunc(userId) {
$.ajax({
url: GetUrl("/Users/UpdateOperationsManagerFlag"),
type: "POST",
data: { "userId": userId },
success: function (data) { }
});
}
function GetUrl(path) {
var pathArray = window.location.pathname.split('/');
if (pathArray[1] === "ITOC")
return "/ITOC" + path;
else
return path;
}
If you have your javascript in .aspx file, you can generate url like this:
function OperationsManagerFlagClickFunc(userId) {
$.ajax({
url: "<%= Url.Action("UpdateOperationsManagerFlag","User") %>",
type: "POST",
data: { "userId": userId },
success: function (data) { }
});
}
Why not have a variable defined separately, like siteUrl, that will hold your site's url, with different values on the 2 servers?
Then just do:
url: siteUrl + "/Users/UpdateOperationsManagerFlag"

Resources