JQuery AJAX Call reports success in every browser but Chrome - asp.net

I'm working on a bit of legacy code that is being used to authenticate users to a web application via username/password check. The code is contained within a standard ASPX page (yes, I know) and, when the page is requested it either returns status 404 to indicate an authentication failure or populates a literal on the ASPX page if all is well.
Its a standard JQuery ajax call:
$("#btnSWSignInPin").click(function () {
$.ajax({
url: "/Security/Validate.aspx",
type: "GET",
data: "Rnd=" + Math.random() + "&Identifier=" + $(".inpIdentifier").val() + "&Pin=" + $("#inpSWPin").val(),
success: function () {
$("#divSessionLogin").jqmHide();
WarnInFuture();
DoChecks = true;
},
error: function () {
ShowLogin("The password you entered was incorrect. Please try again.");
}
});
$("#inpSWPin").val("");
return false;
});
The .NET code which this calls runs fine and I can successfully step through it with no issues in VS. I have tested extensively in Safari, Firefox and IE9, all but the latter on OSX and Windows, and it executes as expected. However in Chrome (latest build) the success function is never executed, the javascript seems to think that something other than status 200 is being returned from the browser although Fiddler shows its definitely a 200 in the Response header.
Can anyone suggest what I can check to try to understand and correct this behaviour?

I think it can be a url parsing problem, please try by giving your parameters this way :
data = {
"key_1": "value_1",
"key_2": false,
"key_4": 123
};

Set
async: false
Google Chrome seems to have an issue with firing success when async is set to true.

Related

jQuery Ajax Stop is not invoked (No error; 200 OK)

I have a working ASP.Net 2.0 code in my development server that uses jQuery Ajax. The result of the ajax call is used to load dropdown values.
But when this code is deployed to a new DMZ server, the result is not getting populated in dropdown – though I am getting 200 OK as response. One obvious thing is that the Type is different in the response. It is expected as application/json but coming as text/plain.
I have success call back and error callback codes. Along with this I have handlers for ajax start and stop. But none of these events are getting fired. What is the reason error/stop handlers are not getting fired? How can we make it work?
Note: The behavior is same in both IE and Chrome.
Update
Also observed that there is an error logged in console, as shown below. Is it related to the "Type"? How can we address this?
Note: Also note that the Content-Length is 0 in the response headers shown below.
Success Callback
jQuery
function loadASN()
{
var receiveScanParameter = getContainerParameters();
// console.log(receiveScanParameter);
$.ajax({
type: "POST",
url: "rcvScanTXAdd.aspx/GetASNForPlant",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ receiveScanParameter: receiveScanParameter }),
success: successPopulateASN,
error: errorFunction
});
}
Global jQuery Code
//Global Ajax Error handling Function
function errorFunction(xhr, status, error)
{
if(xhr == 'undefined' || xhr == undefined)
{
alert('xhr undefined');
}
alert(status);
alert(error);
}
$(document).ready(function ()
{
//Ajax Start
$('body').ajaxStart(function()
{
//Change cursor to waiting
$(this).css({'cursor':'wait'})
});
//Ajax End
$('body').ajaxStop(function() {
//Reset the cursor
$(this).css({'cursor':'default'})
});
});
Screenshots
I figured it out.
Step 1: Observed that there is an error logged in browser’s console (saying result is null). [This screenshot is updated in the question]
Step 2: Observed that the content length of the response is zero. Also observed that there is a gzip compression happened on the response (by reading the response headers).
Step 3: Analyzed the server's web.config. It was uisng a C# httpModule for compression. In that httpModule added bypassing logic for json. [I don’t want json to be compressed with this custom module. Later I will consider adding compression to JSON when I use IIS for compression instead of custom module]. Following is the C# code segment for by-passing JSON compression
request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json")
WHen in doubt, read the API docs:
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
http://api.jquery.com/ajaxStop/
Same note can be found in $.ajaxStart docs

LinkedIN Integration JS API

We are integrating with Linked IN to extract the users profile. Its working fine, but we notice in some Windows 7 / IE 9 machines, Linked IN pop up comes up and is blank. We see the below error in console.
Message: Object doesn't support property or method 'replace'
Line: 861
Char: 17
Code: 0
URI: http://platform.linkedin.com/js/framework?v=0.0.2000-RC1.21420-1403&lang=en_US
Code Snippet Below
<script type="text/javascript" src="https://platform.linkedin.com/in.js?async=false" >
api_key: tw6oqfav7ms1
authorize:false
</script>
//We have a custom image for linkedIN, onclick of the same below code is called.
$("#mylinkedin").click(function () {
IN.UI.Authorize().params({"scope":["r_fullprofile", "r_emailaddress","r_contactinfo"]}).place();
IN.Event.on(IN, "auth", onLinkedInAuth);
});
function onLinkedInAuth() {
IN.API.Profile("me").fields([ "id","firstName", "location","lastName","skills","positions","educations","languages","phone-numbers","certifications","emailAddress","mainAddress"]).result(displayProfiles);
IN.User.logout(); //After we take the data, we do a log out
$.get("https://api.linkedin.com/uas/oauth/invalidateToken");
}
function displayProfiles(profiles) {
//Access profile and process
member = profiles.values[0]
...........
}
Thanks for your response.I was able to figure the issue on my own. What we observed was in the Win7 machines with IE9, the Linked IN authorization Pop Up was blank. When I uncheck the "Enable Protected Mode" the pop up is coming up without any issues.
I haven't had a chance to test this, but to me it looks like you've introduced a race condition in your code, specifically, in onLinkedInAuth().
The call to IN.API.Profile() invokes an async call to LinkedIn that may not be complete by the time the JavaScript engine in the IN.User.logout() code.
I would change the code to the following to see if this resolves the issue:
IN.API.Profile("me")
.fields([ "id","firstName", "location","lastName","skills","positions","educations","languages","phone-numbers","certifications","emailAddress","mainAddress"])
.result(function(profile) {
displayProfiles(profile);
IN.User.logout(); //After we take the data, we do a log out
$.get("https://api.linkedin.com/uas/oauth/invalidateToken");
});

jQuery - Ajax showing empty RESPONSE / Success: not triggered when used with WordPress posts and pages

Any help would be appreciated.
I have created a small script which works fine when used with simple php pages. Now I just tried to add this script to my WordPress posts and pages. So I used "exec-php" plugin to call the php script.
Everything works fine. But when user fills the data and submits the form, the data actually gets submitted (I can see the posted variables in firebug), but the response is not displayed under the form when used with wordpress, where as it works fine when used with plain php pages.
My jQuery code is like this:
var dataString = 'name=' + name + '&country=' + country + '&lang=' + language;
$("#paypal-submit").click(function () {
$.ajax({
type: "POST",
url: "get.php",
data: dataString,
dataType: 'html',
success: function (gotresponse) {
$('#response-id').html("<div id='id-message'><p>Got Response</p></div>");
$('#id-message').html(gotresponse).fadeIn(1500, function () {
$('#id-message');
});
$('#name').attr('onchange', 'resetForm()');
$('#country').attr('onchange', 'resetForm()');
}
});
});
When I actually view the whole process in firebug, I can see that the data is actually posted to the server.
200 OK 2.03s
But when I see the response tab in firebug console, it is empty. I think the success message is not getting triggered when used with WordPress.
I cant figure out what could be the problem? Can someone help me solve this?
NOTE: The same script works fine when used as it is, but when used with WordPress the jQuery - Ajax success does not get triggered.
1st Edit:
I just included the error: in ajax function
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
Now when I submit the form I get the alert saing "You are offline!! Please Check Your Network." This error is getting triggered. So please help me now.
On you success:function() , it should success:function(data) then change .html(gotresponse) to .html(data)

jsonp cross domain only working in IE

EDIT: At first I thought it wasn't working cross domain at all, now I realize it only works in IE
I'm using jQuery to call a web service (ASP.NET .axmx), and trying to us jsonp so that I can call it across different sites. Right now it is working ONLY in IE, but not in Firefox, Chrome, Safari. Also, in IE, a dialog pops up warning "This page is accessing information that is not under its control..."
Any ideas?
Here is the code:
$.ajax({
type: "POST",
url: "http://test/TestService.asmx/HelloWorld?jsonp=?",
dataType: "jsonp",
success: function(data) {
alert(data.prop1);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status + " " + textStatus + " " + errorThrown);
}
});
And the server code is:
[ScriptService]
public class TestService : System.Web.Services.WebService{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {
string jsoncallback = HttpContext.Current.Request["jsonp"];
var response = string.Format("{0}({1});", jsoncallback, #"{'prop1' : '" + DateTime.Now.ToString() + "'}");
HttpContext.Current.Response.Write(response);
}
}
Glad it's working now.
You're trying to send the parameter, "jsonp" -- that you need to pass for the "padding" part of the json -- as a GET parameter, i.e. in the URL string. Which is the right thing to do.
But because you've specified POST, that's not happening. Effectively, because you're specifying POST, the server is expecting all the parameters to be in the POSTed data, not in GET variables, so it's not checking the URL to retrieve the parameter.
I think it's possible that jQuery is being quite forgiving/smart about how it's doing the JSON evaluation, and therefore still working in IE, because (a) if the server doesn't read the "jsonp" variable, I think it'll send back "({'prop1' : '<today's date>'})", which is still evaluate-able as JSON, and (b) IE doesn't have the same restrictions on cross-site scripting ("same origin" policy) as the other browsers. But I'd need to debug it to be sure.
I'd suggest using FireBug in Firefox to debug what's going on with this sort of request in the future, but the main take-away is that if you're sending parameters as part of the URL, use GET, not POST.
Cheers,
Matt
Unless you specify the jsonp and/or the jsonpCallback option, jQuery auto-generates the function name for you, and adds a query param like callback=jsonp1272468155143. Which means your application needs to output using that function name.
You can always set jsonpCallback to test, in which case your example would work.

Getting "401 Unauthorized" error consistently with jquery call to webmethod

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.

Resources