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');
}
});
Related
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);
}
}
}
}
});
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.
I'm losing my custom header when using PUT type with .ajax. But, the header is fine with GET, but gets mangled with PUT. Please see evidence 1:
// GOOD GET:
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
headers: {
Accept: "application/json"
}
});
// Actual header sent (using fiddler):
Accept: application/json
// BAD PUT:
$.ajax({
url: url,
type: 'PUT',
dataType: 'json',
headers: {
Accept: "application/json"
}
});
// Actual header sent (using fiddler):
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
As you can see the only difference is the value of type causing the value of the Accept part of the header gets trashed. jquery-1.8.2.js. Any thoughts? Thanks
Stabby
It seems it is browser related:
http://jsfiddle.net/oceog/WqXzA/
Request URL:http://fiddle.jshell.net/_display/
Request Method:PUT
Status Code:200 OK
Request Headersview source
Accept:application/json
Chrome 25.0
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/
I am trying to call a web service from an ajax jquery. It is successfully entering the success method but unfortunately a 403 error is being triggered and thus won't allow me to access the data.
This is my code:
try {
$.ajax({
type: "POST",
url: urlAddress,
data: dataa,
contentType: "text/xml; charset=utf-8",
success: function(Msg) {
// $("#Result").text(msg.d);
alert("ok");
alert("hi "+Msg.responseText + " How are you?");
},
error: function(request, status, error) {
alert("Error "+request.statusText.toString());
alert("ERROR");
}
});
}
catch (e)
{}
Msg.ResponseText comes back "undefined"
From Live Http Headers I get the following:
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
Accept-Charset:
ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115 Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
HTTP/1.1 403 Forbidden
Content-Length:1758
Content-Type: text/html
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Date: Tue, 27 Jul 2010 10:59:04 GMT
Smells like urlAddress is not located on the same domain you're running that script.
That would breach the same origin policy and therefore, fail.
If I'm wrong here with that assumption, your're webservice might require a login (username+password) which you might missing to pass through .ajax().