Ajax post sometimes removes body and adds NTLM Authorization - ajax

We're experiencing some problems with some ajax calls. On the server side we're running Apache Tomcat with Servlets. On a few calls an Authorization (NTLM) is added in the request header,
and the post body is removed. We are using NTLM authentication on the site, but authentication is already done before these ajax calls are made, and this only happens on certain ajax calls.
Here the JavaScript making the Ajax call.
var postObjects = function(f, parameter, value, variables)
{
var post = {};
post['f']=f;
post['courseid']=trapi.courseID;
post['courseresourceid']=trapi.courseResourceID;
post['mode']=trapi.mode;
if(parameter!=null)
post['parameter']=parameter;
if(value!=null)
post['value']=value;
if(variables!=null)
{
for(var i=0; i<variables.length;i++)
{
post[variables[i][0]]=variables[i][1];
}
}
var returnString="";
$.ajax(
{
url : location.pathname,
data:post,
cache:false,
global:false,
dataType:'text',
contentType:'application/x-www-form-urlencoded; charset=UTF-8',
type:'POST',
async:false,
success: function(data)
{
returnString=data;
},
error: function(jqXHR, textStatus,errorThrown)
{
returnString="Error: "+textStatus;
}
});
return returnString;
}
And here is info from fiddler about a POST made by the postObjects function which adds NTLM authorization:
POST http://localhost:8080/trainweb/courses HTTP/1.1
Accept: text/plain, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/trainweb/courses?f=courseframe&courseid=909
Accept-Language: nb-NO
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Connection: Keep-Alive
DNT: 1
Host: localhost:8080
Pragma: no-cache
Cookie: JSESSIONID=C18B2FA564626BCEB82C4C3AD8837AE8; FillScreenWidth=0; DefaultSearch=docno; lang=no
Authorization: NTLM BASE64ENCODEDSTRING
Content-Length: 0
And here is info from fiddler about a POST made by the same postObjects function not adding NTLM authorization:
POST http://localhost:8080/trainweb/courses HTTP/1.1
Accept: text/plain, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/trainweb/courses?f=courseframe&courseid=909
Accept-Language: nb-NO
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 61
DNT: 1
Host: localhost:8080
Pragma: no-cache
Cookie: JSESSIONID=C18B2FA564626BCEB82C4C3AD8837AE8; FillScreenWidth=0; DefaultSearch=docno; lang=no
f=getlasterror&courseid=909&courseresourceid=4079&mode=normal
Do I have to re-authenticate each time this happens?

Related

POSTing JSON data to WCF Rest Service

I know there are many questions on SO about this but none of the suggestions have worked for me.
Here is my code:
var restService = "http://wcfrestservice:8004/RADPOCService/WebApp1";
$.ajax({
url: restService,
type: "POST",
data: { PhoneNumber: y },
dataType: "json",
contentType: "application/json; charset=utf-8",
success:
function (data) {
window.open(data.Url, '_blank');
}
});
Fiddler shows my request going across the wire like so (redacted):
POST http://localhost:8004/RADPOCService/WebApp1 HTTP/1.1
Host: localhost:8004
Connection: keep-alive
Content-Length: 22
Accept: application/json, text/javascript; q=0.01
Origin: http://localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://localhost:8000/Default.aspx
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Requestor: Me
PhoneNumber=1234567890
I am expecting the payload to look like this:
{ "PhoneNumber": "1234567890"}
When I set the payload as above in the Fiddler Composer tab the service works as expected. What am I doing wrong?
I hate to do this so quickly after posting my question but the answer is to use the JSON.stringify API on the data being sent to the service. So the above should have the following code for 'data' in the ajax call:data: JSON.stringify({ PhoneNumber: y })

AJAX CORS webAPI request fails even after the preflight OPTIONS succeeds

I am trying to make CORS AJAX "GET" call to an web API service hosted in a test server. webAPI URL = http:xxx:xxx:xxx:xxx/api/v1/jobs
I have the following lines of code in WebAPIConfig.cs
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
AJAX request (from local)
$.ajax({
type: "GET",
datatype: "JSON",
url: http: xxx: xxx: xxx: xxx / api / v1 / jobs,
contentType: "application/json";
charset = utf - 8 ",
accept: 'application/json',
beforeSend: BH,
success: callback
}).done(function (data) {
var str = data.job_id + ': ' + data.job_name;
$('#responsevalue').text(str);
}).error(function (jqXHR, textStatus, errorThrown) {
$('#responsevalue').text(jqXHR.status + "::" + jqXHR.statusText + "::" + jqXHR.responseText );
});
In Fiddler, I can see the pre-flight request with OPTIONS being sent and the response with 200.
Fiddler Request Headers:
OPTIONS http:xxx:xxx:xxx:xxx/api/v1/jobs HTTP/1.1
Host: 50.17.211.226
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:55346
Access-Control-Request-Method: GET
Access-Control-Request-Headers: requestdateutc,requestverificationtoken
Connection: keep-alive
Fiddler Response Headers
HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Accept
Access-Control-Max-Age: 1728000
X-Powered-By: ASP.NET
Date: Thu, 20 Nov 2014 14:21:50 GMT
Content-Length: 0
In Firebug, i can see the following details:
Firebug Request Headers:
OPTIONS http:xxx.xxx.xxx.xxx/api/v1/jobs HTTP/1.1
Host: xxx.xxx.xxx.xxx
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http:localhost:55346
Access-Control-Request-Method: GET
Access-Control-Request-Headers: requestdateutc,requestverificationtoken
Connection: keep-alive
Firebug Response Headers:
HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *, *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Accept, Content-Type
Access-Control-Max-Age: 1728000
X-Powered-By: ASP.NET
Date: Thu, 20 Nov 2014 18:08:36 GMT
Content-Length: 0
I read lot of documentation here and in other places. It seems pretty simple and works for everyone (except me).
Final note: I tested the API with the html page residing in side the test server an it worked fine. Meaning the service and the web page both residing in the same domain.
Additional Info: Browser: Firefox, ASP.NET 4.5, web API 2.2, VS2013 Express
Thanks in advance and any help will be much appreciated.
In your response, it says the allowed headers are Content-Type, Accept, Content-Type, but you are asking for requestdateutc,requestverificationtoken. Try explicitly allowing those headers.

JQuery-Ajax headers issue

I got a problem with the headers when i'm trying to do a POST Request with JSON
This is the code:
$.ajax({
type: "POST",
url: url,
data: jsonData,
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
error: function(){
alert("Fail");
},
success: function(){
alert("Success");
}
});
And this are the Request Headers displayed by Firebug.
OPTIONS /path HTTP/1.1
Host: 192.168.15.109:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0 FirePHP/0.7.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Origin: http://localhost
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
x-insight: activate
Pragma: no-cache
Cache-Control: no-cache
And the Response Headers:
HTTP/1.1 204 No Content
Date: Thu, 24 May 2012 19:17:01 GMT
Allow: OPTIONS,POST
As you can see, the headers doesnt match with the ones im specifying, but when i use CURL the Headers are this ones instead:
POST /path HTTP/1.1
User-Agent: curl/7.25.0 (i386-pc-win32) libcurl/7.25.0 OpenSSL/0.9.8u zlib/1.2
Host: localhost:8080
Accept: */*
Content-Type: application/json
Content-Length: 5
Any idea or solution for this?
I also modified JQuery Source to set default values of the Headers sent by Ajax to JSON, but didnt work.
Seems like a same-origin policy issue. Using dataType='jsonp' should work, but this might require other changes.
See https://developer.mozilla.org/en/http_access_control for an in-depth explanation.
Actually, it was a cross Domain problem, I defined my URL as an IP, so the browser interpreted it like a Cross Domain request.
Thanks for everything!

Run jQuery AJAX call when previous AJAX call fail due to connection was unexpactly closed

I know about error in application running on server and invoked operation disconnect all HTTP clients. I need to invoke this functionality on the server but I'm not able to fix the error.
Here is my server code:
<?php
// file: run_script.php
shell_exec('close_all_HTTP_connections_error '.$_REQUEST['params']);
?>
I'm trying to find workaround via AJAX call, I know that call fails, but user doesn't see error like ERR_EMPTY_RESPONSE. My problem is that I need to do another call to the server (which doesn't fail normaly). The second call is not send to server because previous call fail I guess.
Here is my jQuery AJAX call:
function sendData(url, step) {
$.ajax({
type: 'POST',
async: true,
url: url,
headers: { // I try it without this also
'Connection' : 'close'
},
data: {
'params' : 'bla bla'
},
complete: function(jqXHR, textStatus) {
console.log(jqXHR);
console.log(textStatus);
if (step < 2) {
sendData('another.php', step+1);
}
else {
console.log("done");
// go forward
}
},
dataType: 'html'
});
}
$(document).ready(function() {
sendData('run_script.php', 1);
});
Here is my screen shot from Chrome inspector:
And HTTP Requests:
run_script.php:
POST http://?????.com/test/run_script.php HTTP/1.1
Origin: http://?????.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.22 (KHTML, like Gecko)
Chrome/19.0.1049.3 Safari/535.22
Content-Type: application/x-www-form-urlencoded
Accept: text/html, */*; q=0.01
Referer: http://?????.com/test/result.php
params:bla bla
another.php:
POST http://?????.com/test/another.php HTTP/1.1
Origin: http://?????.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.22 (KHTML, like Gecko)
Chrome/19.0.1049.3 Safari/535.22
Content-Type: application/x-www-form-urlencoded
Accept: text/html, */*; q=0.01
Referer: http://?????.com/test/result.php
params:bla bla
There is no HTTP Response of course.
Problem was, that task previously invoked on server restarts server. Then I need to wait before next AJAX call is invoked.
I fact I have to solve problem with server restart first, this is work-around only and not the best solution.

Jquery AJAX call to pylons failing intermittently on identical requests

I am creating an ajax call like so:
var form = $("#form");
$.ajax({url: "/url/create_web_registration?invite_token=abc",
data: form.serialize(),
type: "POST",
dataType: "json",
success: $.web_registration.index.registerSubmitSuccess,
error: $.web_registration.index.registerSubmitError,
});
However when I repeat the request with identical parameters, I sometimes get the success callback and sometimes get the error callback. When the error callback is called, the jqXHR.status is always 0 on a failure, but there is nothing descriptive in statusText, responseText, textStatus or errorThrown.
I did a tcpdump on the HTTP requests and the request looks like:
POST /shopkick/v1/user/create_web_registration?invite_token=abc HTTP/1.1
Host: [redacted]:5000
Connection: keep-alive
Referer: http://[redacted]:5000/wr2/abc?invite_token=&zip_code=94123&phone_number=%2B16785556982&facebook-form=
Content-Length: 169
Origin: http://[redacted]:5000
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1
Content-Type: application/x-www-form-urlencoded
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
invite_token=&zip_code=94123&phone_number=%2B16785552982
The response looks like:
HTTP/1.0 200 OK
Server: PasteWSGIServer/0.5 Python/2.6.1
Date: Wed, 31 Aug 2011 05:34:10 GMT
Pragma: no-cache
Cache-Control: no-cache
Content-type: text/plain
Content-Length: 74
{"error_message": "Facebook account already registered", "success": false}
I am at a loss to why it is sometimes succeeding and sometimes failing.
The problem was I was using ajax to submit a form. When I clicked the submit button it would work fine, but when I hit enter in a text input field it would encounter the errors. Apparently hitting enter in a input field was causing the form to submit twice. The fix was to set onsubmit="return false;" for the form to prevent double submission.

Resources