localhost to different domain not passing credentials - javascript

I have an ajax call that i use to call a web page and i wanted to get the result. The issue with it, is that it doesnt seem to work, and at the moment returns a jQuery parse Error.
When i look in the debug console and click though, it will take me to the page i want, it just doesnt seem to do it via ajax and store the result/ call success.
My code:
$.ajax({
type: "GET",
url: "mywebsite",
data: {username: username, password:password},
dataType: "jsonp",
contentType: "application/json",
xhrFields: {withCredentials: true},
crossDomain: true,
success: function(result, status, jqxhr){ alert("success"); },
error: function(xhr, status, message){ alert(status + ": " + message); }
});
as you can see i have some credentials i want to add to it, and i was told to have it in data, instead of doing the ajax options for username and password.
Im not sure whats going on, and it seems like there is something wrong. I was looking at 3 different approaches via stack overflow, but none seemed to give me the correct answer.
Posted Data
Request URL:http://10.224.65.5/mas3/DataSources/inspecttech.inspecttech/Schema/Classes?callback=jQuery17202808878293726593_1373384418801&username=njtax.hinspecttech&password=4e1cb7494843c513ee913d122e30ef2fe27635e5f82f575c92d006691906bebbbdb1fe483cfc06b087f7c4070c2879bd3585234a3614a1f04fca8de64ad6bfaf&_=1373384423017
Request Method:GET
Status Code:200 OK
Request Headersview source
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic bmRvdG1vYnguaG1vYmlsZWRldmljZTpzdXBlclNlY3JldERldmljZVBhc3N3b3Jk
Connection:keep-alive
Host:10.224.65.5
Referer:http://localhost:3033/BentleyFormIntegrationFrameset.aspx
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Query String Parametersview sourceview URL encoded
callback:jQuery17202808878293726593_1373384418801
username:njtax.hinspecttech
password:4e1cb7494843c513ee913d122e30ef2fe27635e5f82f575c92d006691906bebbbdb1fe483cfc06b087f7c4070c2879bd3585234a3614a1f04fca8de64ad6bfaf
_:1373384423017
Response Headersview source
Response Headers
Cache-Control:no-cache
Content-Language:en-US
Content-Length:801
Content-Type:application/json; charset=utf-8
Date:Tue, 09 Jul 2013 15:40:22 GMT
Expires:-1
Mas-License-Error-Id:NoClientLicense
Mas-License-Error-Message:Client's license is invalid.
Pragma:no-cache
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
additional Information
Preview (In Google Chrome) shows the returned object, but im not sure why it would fail. It looks like it fetched everything correctly.
Possible alternate Option Via ASP?
HttpWebRequest request = HttpWebRequest.Create(Request.Url.Scheme + "://" + site +"/DataSources/inspecttech.inspecttech/Objects/DeviceDatabase/" +action) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential(bic_name + "x.h" + user.in_username, user.in_password);
request.Credentials = cred;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string resp = "";
StreamReader reader = new StreamReader(response.GetResponseStream());
while (!reader.EndOfStream)
resp += reader.ReadLine();

I was struggling with this same error, so then I found a blog post about CORS (Cross-Origin Resource Sharing) with ASP.NET. The author also published a complete solution using ASP.NET Web.API and AJAX calls with JQuery.
Blog post: http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version.aspx
Code: http://code.msdn.microsoft.com/CORS-support-in-ASPNET-Web-01e9980a

I assume that you haven't defined username & password
I'm not sure where you'll want these to come from. On the one hand, you might need to get these from their fields in which case you'd want something like this:
$.ajax({
type: "GET",
url: "mywebsite",
data: {username: $('#username').val(), password:$('#password').val()},
dataType: "jsonp",
contentType: "application/json",
xhrFields: {withCredentials: true},
crossDomain: true,
success: function(result, status, jqxhr){ alert("success"); },
error: function(xhr, status, message){ alert(status + ": " + message); }
});
And this will get the value from the fields assuming they are #username & #password
Or, you just want to pass them as a string in which case you'd do:
data: {username: 'username', password:'password'},
And the above will just post an value username with the value username and likewise with password.

Related

JSON.stringify odd behavior

I'm wrapping up some values to send back to an ASP.NET MVC controller action. I'm getting Invalid JSON primitive exceptions, but I'm using JSON.stringify and am confused.
I build up a search value holding called searchValues. Putting console.log(JSON.stringify({ "values": searchValues })); in my code and opening Chrome's console outputs the following
{"values":["name_last:foo"]}
I use the exact some bit of code sans the console.log usage to populate the data parameter to the ajax call. However, watching the call in Fiddler, the request being sent looks like such
0=%7B&1=%22&2=v&3=a&4=l&5=u&6=e&7=s&8=%22&9=%3A&10=%5B&11=%22&12=n&13=a&14=m&15=e&16=_&17=l&18=a&19=s&20=t&21=%3A&22=f&23=o&24=o&25=%22&26=%5D&27=%7D
I'm using this in a Kendo grid but am specifying it to be sent as post as such:
$("#search-preview").kendoGrid({
columns: ...column stuff...,
dataSource: {
transport: {
read: {
url: "/SearchPreview",
dataType: "json",
data: JSON.stringify({"values": searchValues}),
type: "POST",
contentType: "application/json; charset=utf-8"
}
}
}
});
And I can see in Fiddler it being sent in the request body and not being appended to the URL such as if it were a GET. What's going on here?
Edit:
Adding what the entire Fiddler request looks like:
POST http://localhost/MvcTestBed/SearchPreview HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 149
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://localhost/MvcTestBed
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: .... asp.net cookie fluff ....
0=%7B&1=%22&2=v&3=a&4=l&5=u&6=e&7=s&8=%22&9=%3A&10=%5B&11=%22&12=n&13=a&14=m&15=e&16=_&17=l&18=a&19=s&20=t&21=%3A&22=f&23=o&24=o&25=%22&26=%5D&27=%7D
Edit 2:
I've experimented with the processData and traditional settings on the jQuery ajax constructor, and the best I've gotten is for the post body to now look like
[object Object]
Based on the results you're getting in fiddler, it looks like something is calling $.param on your json string. jQuery does not do that, so it must be kendo grid.
One solution would be to make the ajax request directly, then in the success initialize the grid with the result.
After some research my solutions is use read as a function:
$("#search-preview").kendoGrid({
columns: ...column stuff...,
dataSource: {
transport: {
read: function (options) {
url: "/SearchPreview",
dataType: "json",
data: JSON.stringify({"values": searchValues}),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
}
}
}
});

jQuery .post is working but triggering .fail without any information

I've got my data posting successfully but I'm not having any luck getting my .post response handler code to work. I get inconsistent results in the different browsers/tools I've tried. Here's the post code:
$.post(form.attr("action"), form.serialize(), "json")
.done(function (response, textStatus, jqXHR) {
alert('done');
})
.fail(function (jqXHR, textStatus, errorThrown) {
// log the error to the console
alert('responsetext:' + jqXHR.responseText + ', status:' + textStatus + ', error:' + errorThrown);
})
In FireFox and Chrome it always goes to the .fail (even though the data is successfully posting) but the only item set is textStatus to "error". In Firefox when I try to view the response it just shows the Error, "SyntaxError: JSON.parse: unexpected end of data at line 1 column 1". In Chrome, in the Console I'm seeing this: "XMLHttpRequest cannot load http://example.net/applicationsvc/formprocessor/index.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.net' is therefore not allowed access." Which seems very relevant but my attempts to solve it haven't worked.
How can I resolve the Access-Control-Allow-Origin issue in a .post? Why aren't I getting any error data and why is FireFox unable to parse the response.
Using PostMan, and using the same headers and body, I do see I'm getting a response of:
{"successful":true,"thankyou_message":"<h2>Thank you!<\/h2><p>Thank you for signing up!<\/p>"}
But the code doesn't seem to be getting or handling that.
Here are the Request headers that are going out:
Host: example.net
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://example.net/mypage.htm
Content-Length: 655
Origin: http://example.net
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
UPDATE:
I've now switched from the .post to .ajax
$.ajax({
url: form.attr("action"),
type: "POST",
data: form.serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
alert('done');
}
});
With that I get a consistent HTTP 501 Response.
try to enable cross-origin on the server, example in php
header("Access-Control-Allow-Origin: *");
the server must send this in the response header, change the star accordingly to your domain for security reasons.
If you are using cross domain then try with the JSONP instea
Your Code
$.ajax({
url: form.attr("action"),
method: "POST",
headers: {"Access-Control-Allow-Origin":"*"},
data: form.serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
alert('done');
}
});
Change it to
$.ajax({
url: form.attr("action"),
type: "POST",
headers: {"Access-Control-Allow-Origin":"*"},
data: form.serialize(),
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
success: function () {
alert('done');
}
});

HighCharts query parameters issue with Flask webservice

I have a HighCharts client whose responsibility is to load data from a webservice and show a chart. The function that requests data looks as below:
function requestData() {
$.ajax({
url: 'http://myhost.com/type?x=1&y=2&z=3',
headers: {
Accept : "application/json"
},
type: "GET",
dataType: "json",
success: function(data) {
//do something
},
cache: true
});
}
(in the future, the url property will be dynamically generated)
The target webservice is read-only and implemented using Flask microframework: its purpose is to return JSON data to the HighCharts client. This is the Flask view (function) taking care of data requests:
#app.route('/<type>')
def get_data(type):
x = request.args.get('x','')
y = request.args.get('y','')
z = request.args.get('z','')
[...]
Problem: when I execute the javascript code in Chrome, the following HTTP request is sent to the webservice:
GET /type?x=1&y=2&z=3 HTTP/1.1 // '&' have been escaped to '&'
Host: myhost.com
Connection: keep-alive
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
Accept: application/json
Referer: http://myhost.com/chart.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
...I get a 404 status code (Bad Request) from the server, which is perfectly good and expected whenever one or more of the request's query parameters is null or malformed:
HTTP/1.0 400 BAD REQUEST
Content-Type: text/html; charset=utf-8
Content-Length: 16
Server: Werkzeug/0.8.3 Python/2.7.3
Date: Wed, 14 Nov 2012 10:23:49 GMT
After debugging on my Flask webservice I noticed that only the x query parameter (which please note is the first given in the HTTP request) is correctly parsed, while y and z are empy strings, which causes the 404.
Why is it happening? Any charset inconsistency regarding the & -> & escaping?
Thanks, any hint would be of real help (just ask if you need more specs or code)
I think the error is as you expected the escaped ampersand.
Try this:
function requestData() {
$.ajax({
url: 'http://myhost.com/type',
headers: {
Accept : "application/json"
},
data: {
x: 1,
y: 2,
z: 3
},
type: "GET",
dataType: "json",
success: function(data) {
//do something
},
cache: true
});
}

JQuery AjaxComplete Method Stripping Out Custom Headers?

I am trying to follow option #3 in the solution at this SO post: A controller action which returns a partial view inserts the logon page when authorization fails
I'm running into a problem reading my custom header in the ajaxComplete method in jquery.
I have confirmed in fiddler and in chrome's debug tools that the custom header is in fact being sent back and received by the browser...
Response Headers (in Fiddler):
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 15 Jan 2012 04:00:13 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Unauthorized: 1
Cache-Control: private
Content-Length: 0
Connection: Close
Response Headers (as received by Chrome):
Cache-Control:private
Connection:Close
Content-Length:0
Date:Sun, 15 Jan 2012 04:12:13 GMT
Server:ASP.NET Development Server/10.0.0.0
Unauthorized:1
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
Response Headers (as found from calling "getAllResponseHeaders()" on the xmlHttpRequest variable passed into ajaxComplete):
Date: Sun, 15 Jan 2012 04:42:21 GMT
X-AspNet-Version: 4.0.30319
Connection: Close
Content-Length: 65
X-AspNetMvc-Version: 3.0
Server: ASP.NET Development Server/10.0.0.0
Content-Type: application/json; charset=utf-8
Cache-Control: private
Interestingly, the function that is called upon the return of the original ajax request (as initiated by jquery) does receive the Unauthorized header.
Does anyone know what's going on here and what I can do to solve this issue?
Here's my "ajaxComplete" javascript code
$(document).ajaxComplete(function (event, request, settings) {
alert(request.getResponseHeader('Unauthorized'));
});
You can take a look here. It might be helpful if you are using the same plugin (ajaxmanager) on your page. If not, check your other plugins.
Vucetica's initial response got me thinking and I spent the last hour looking through jquery's code. I have my custom header coming back now. It looks like the trouble stemmed from an unhandled exception in my code within the success callback of the original ajax request.
Definitely something I should fix, but it seems odd that jquery would allow itself to be susceptible to that in a way that it fails silently and only affecting the custom headers. This unexpected behavior really led me in the wrong direction initially.
Anyway, thanks for your help everyone.
For completeness sake, here is my code before and after.
Before (no custom headers received in the ajaxComplete method)
$.ajax({
type: "GET",
url: "/Game/GetPlay/27?roundId=" + that.gameState.RoundToDisplay,
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (play, request, settings) {
that.play = play;
that.startGame();
},
error: null,
cache: false
});
After (working)
$.ajax({
type: "GET",
url: "/Game/GetPlay/27?roundId=" + that.gameState.RoundToDisplay,
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
success: function (play, request, settings) {
that.play = play;
try {
that.startGame();
} catch(err){
}
},
error: null,
cache: false
});

JSON get result null

I'm developing an app using HTML5 with jQuery, and I am using Sync Framework for the synchronization and it consumes a service in the cloud (Windows Azure).
The problem is when I send the Request frame to the service:
$.ajax({
dataType: "json",
Accept: 'application / json',
url: serviceUri,
crossDomain: true,
success: function (json) {
console.log(" reponse :" + json);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("error :" + XMLHttpRequest.responseText);
}
});
The Request frame is:
GET http://157.56.8.203/DefaultScopeSyncService.svc/defaultscope /DownloadChanges?id=7AE7C771-0A98-4A5D-A046-430DDB0A7917 HTTP/1.1
Host: 157.56.8.203
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept: application/json, text/javascript, /
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Referer: htp://localhost:49427/ListSample.htm
Origin: htp://localhost:49427
And the Reply is:
HTTP/1.1 200 OK
Content-Length: 1388
Content-Type: application/json
Server: Microsoft-IIS/7.0
SyncServiceVersion: 1.0
X-Powered-By: ASP.NET
Date: Wed, 30 Nov 2011 11:55:25 GMT
{"d":{"_sync":{"moreChangesAvailable":false,"serverBlob":"AAEAAAD/////AQAAAAAAAAAMAgAAAGVNaWNyb3NvZnQuU3luY2hyb25pemF0aW9uLlNlcnZpY2VzLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49ODk4NDVkY2Q4MDgwY2M5MQUBAAAAK01pY3Jvc29mdC5TeW5jaHJvbml6YXRpb24uU2VydmljZXMuU3luY0Jsb2IFAAAAIDxDbGllbnRLbm93bGVkZ2U+a19fQmFja2luZ0ZpZWxkIDxDbGllbnRTY29wZU5hbWU+a19fQmFja2luZ0ZpZWxkHDxJc0xhc3RCYXRjaD5rX19CYWNraW5nRmllbGQaPEJhdGNoQ29kZT5rX19CYWNraW5nRmllbGQaPE5leHRCYXRjaD5rX19CYWNraW5nRmllbGQHAQADAwIBbVN5c3RlbS5OdWxsYWJsZWAxW1tTeXN0ZW0uR3VpZCwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV1tU3lzdGVtLk51bGxhYmxlYDFbW1N5c3RlbS5HdWlkLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAJAwAAAAYEAAAAJDhhMzZhNGYyLTg5ZjQtNDJkMi1iNDhmLTJiNWM4ZDc5ZGE4OQEKCg8DAAAAkAAAAAIAAAAFAAAAAAAAAAEAAAAAAAAABQAAEAAAAAKKNqTyifRC0rSPK1yNedqJ6MOD+NOvRl6RwtFgNGnbbgAAABgAABABKAIAAAEAAAAVAAAAAgAAAAEAAAAAAAAAAQAAAAEAAAABAAAAAAAAAQ8AAAAXAAAAAQAAABYAAAABAAMAAAAAAQAAAAAAAAAZAQAAAAAL"},"results":[{"Id":"7ae7c771-0a98-4a5d-a046-430ddb0a7917","Name":"Santiago","Surname":"Dalto","BirthDate":"/Date(917913600000)/","Gender":"M","_metadata":{"uri":"http://157.56.8.203/DefaultScopeSyncService.svc/Persons(Id=guid'7ae7c771-0a98-4a5d-a046-430ddb0a7917')","type":"DefaultScope.Persons"}}]}}
The "data" object in the script is always null, but the reply frame has the correct data.
Can somebody help me?
You must write the call function with this code, the reponse data you can get with json.d.results if the response has more than one object if you will get single object than you reach them with json.d[0].
$.ajax({
dataType: "json",
Accept: 'application / json',
url: serviceUri,
crossDomain: true,
success: function (json) {
if (json.d.results == undefined)
{
// to do
}
else {
console.log(" response :" + json.d.results);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("error :" + XMLHttpRequest.responseText);
}
});
Best Regards.
Cross domain requests doesn't allowing in ALL modern browsers and it is not good to use them. In any case if you would like to receive your data you need to user your server like proxy, so it will work like this:
You implement request from server (YOUR SERVER) to another server
You call request to YOUR server, not to another (cross domain server)
Other ways is hucking.
I.e. you can use this link (BUT I don't suggest it) http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

Categories

Resources