Ajax request from file:// - html

I am having real difficulty knowing what to do. I have been reading some sources that are inferring that you cannot make ajax calls when launching an html file from the local file system (file:// in the url).
I have a html file on my desktop (ie in the browser url file://) containing the following ajax call:
$.ajax({
type: "POST", // This for array
url: "http://www.mywebsite.com/exclude.php",
async: true,
cache: false,
crossDomain: true, // This needs to be true for other people
success: function (data) {
var json = jQuery.parseJSON(data);
// Use json in interesting ways
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Silent error
}
});
My php file on my server is basic:
<?php
header("Access-Control-Allow-Origin: *"); // To allow cross domain
$KeyCodeStatics_BlackList = ["181K2", "4V419"];
echo json_encode($KeyCodeStatics_BlackList);
?>
Some are suggesting ajax calls are not allowed from an html file launched in the local file system (file:// in url).
The errors I am getting:
Origin file: not found in Access-Control-Allow-Origin header.
and
XMLHttpRequest: Network Error 0x80700013, Could not complete the operation due to error 80700013.
How can I overcome this? I need to make an async call to /www.mywebsite.com/exclude.php from the html file from my local file system.
Note: It is not just me that has to do it, it is every end-user that uses this html file. So this means I cannot ask them to change security settings on their browser.

Related

How to call .asmx web service using plain html page

I am trying to call an asmx web service in plain html page. But not getting output. I'm not getting the exact problem. Here is my ajax code that I wrote to call that asmx web service.
function Getdet(Name)
{
alert('hellotest');
$.ajax({
type: "POST",
url: "http://192.168.1.20/myservice/service.asmx?HelloWorld", // add web service Name and web service Method Name
data: "{''}", //web Service method Parameter Name and ,user Input value which in Name Variable.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
alert('abcd1');
$("#spnGetdet").html(response.d); //getting the Response from JSON
},
failure: function (msg)
{
alert(msg);
}
});
}
Should I have to add anything in the code..?? Please let me know where I am going wrong in this above code.
ASMX pages are plain old Web Services and the output is (almost) always in XML format, so don't except JSON out of the box.
Plus, they don't work well on different domain call by default, you will need to ensure that the cross domain is correctly handled.
After all this is done, you will then use the call as:
success: function(response) {
// http://stackoverflow.com/a/1773571/28004
var xml = parseXml(response),
json = xml2json(xml);
$("#spnGetdet").html(json.d);
}

JSON works Locally but not with Servers

Here is my little first project as practice, having real trouble figuring out how to use JSON, took me a while to get it work locally but still no luck with servers, and tried few a including one i hosted, and even tried it with other hosted json files.
http://jsfiddle.net/Atlas_/Mgyc5/1/
$.ajax({
dataType: "json",
async: false,
url: "package.json", //https://www.dropbox.com/s/fmw63i4v7dtnx6t/package.json
'success': function (json) {
theQuiz = json.quiz;
console.log(json);
console.log(theQuiz);
}
});
When you access another domain be carefully with "Crossdomain".
To use with dropbox, try changing the URL to:
https://dl.dropboxusercontent.com/s/fmw63i4v7dtnx6t/package.json
Your code will be like this:
$.ajax({
dataType: "json",
async: false,
url: "https://dl.dropboxusercontent.com/s/fmw63i4v7dtnx6t/package.json",
success: function (json) {
theQuiz = json.quiz;
console.log(json);
console.log(theQuiz);
}
});
When you request 'dl.dropboxusercontent.com', you have this:
Access-Control-Allow-Origin: *
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control
"In this case, the server responds with a Access-Control-Allow-Origin:
* which means that the resource can be accessed by any domain in a cross-site manner."
Another options: Some websites (twitter, for example) work with "jsonp". http://en.wikipedia.org/wiki/JSONP or ..you can create your own proxy.

jQuery JSON parsererror even though JSON is valid

I am trying to pull in some external JSON phone list for a test I am doing locally.
JSON = https://www.o2.co.uk/shop/homepage/scripts/phoneList.json
I have read on a seperate thread that to overcome allow origin / cross domain issues you can pass 'callback=?' to the end of the url. This seems to work fine as now in the devtools network tab I can see the file being pulled in fine.
However, I never get it to go into the success callback function. It always brings back a parsererror.
The code is 100% valid according to jsonlint.com
A snippet of the code as below:
$.ajax({
type: 'GET',
url: 'https://www.o2.co.uk/shop/homepage/scripts/phoneList.json?callback=?',
contentType: 'application/json; charset=utf-8',
cache: true,
dataType:'json',
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
Any ideas welcome as I am well and truly stuck.
Thanks.
JSONP only works if the server supports it. What the server needs to do, is take your callback parameter and wrap the json data in a function call with that name.
So when https://www.o2.co.uk/shop/homepage/scripts/phoneList.json responds with
[{
"handset":"Alcatel 10.30 Black",
"link":"/shop/phones/alcatel/10.30-black/"
}]
https://www.o2.co.uk/shop/homepage/scripts/phoneList.json?callback=MyCallback should respond with:
MyCallback([{
"handset":"Alcatel 10.30 Black",
"link":"/shop/phones/alcatel/10.30-black/"
}]);
If the server doesn't do that, JSONP can't work. Perhaps O2 doesn't want you using their data.

jQuery $.ajax failing no error message, server responded with 200 OK

I have an ajax call that works fine locally, but when I published it into the server, the code is never executed but returns "200 OK" anyway. No "success" code is ejecuted, nor the "error" code. Here's my ajax call:
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
for (var i = 0; i < myObj.length; i++) {
var element = document.getElementById("LbItem " + myObj[i].MenuItemID);
element.innerHTML = "<b>" + element.innerHTML + " (" + myObj[i].Cantidad + ")</b>";
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I also tried to put the complete url in the "url" field but still no luck.
The weird thing is that when I put the complete url directly into the browser, it is still not executing the code. And it works fine locally!!
I know there's a similar post (jQuery $.ajax failing silently, no error messages, and server responded with 200 OK) but is not resolved and it's driving crazy here.
PD: this is NOT cross-domain, my ajax code is in a .ascx and I am trying to call a method on an .aspx
Thanks very much!!!!
EDIT: I tried to remove the System.web.extensions reference of my web project and add the dll to my bin, but it's still not working (the 1.0.61025.0 version). Besides, I am running the ASP.NET website in IIS with framework 2.0, and I don't have framework 3.5 installed on my server (but locally I do). Maybe that's the problem? I can't install it because of the client security policies, what shall I do?
EDIT 2: I tried doing a simple response from my .aspx, just to test if the problem was in that method, but it is still not executing the success function. Here's my .aspx code:
[WebMethod]
public static string ObtenerContadores()
{
return new JavaScriptSerializer().Serialize("true");
}
and adapted the .ascx
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(dictionary) {
alert("hello");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
Here's your problem: "The weird thing is that when I put the complete url directly into the browser, it is still not executing the code." Your JavaScript is expecting -- requiring -- a JSON response, and is apparently getting no response at all. This is not a JavaScript problem, but a problem with your .aspx page.
EDIT: Based on your comments below, it's clear that the problem is that your .aspx page is not returning what you expect. Because the .aspx doesn't produce the expected output even when you go to it directly, the problem is in that page, not in the jQuery.
Pretend the .aspx produces {}, false, or true. Your success code will run, but not do anything. Try putting an alert("Foo"); in there and watch what happens. The problem isn't that your jQuery is busted; it's that it isn't getting meaningful input from your .aspx page.
P.S. I would recommend using a variable name other than data in your success function, just in case it's getting messed up by the data object attribute in your .ajax call.
Okay, I believe I've figured this out, so I'm posting a second answer to preserve the prior discussion.
Here's the fix. Remove this line:
contentType: "application/json; charset=utf-8",
In my test script, this caused jQuery to send the Content-Type header application/json; charset=utf-8, as expected, but the actual contents of the request were not properly sent as JSON. For example, rather than sending {"foo":"bar"}, it was sending foo=bar. As a result, the receiving script acted as if no data was posted at all. When I commented out the line above, my test script worked fine and did whatever I expected with the values received from the target URL.
Note that this will post your data as normal post data. For example, if your $.ajax() call looks like this, the posted data will contain a variable named foo and one named who:
$.ajax({
...
data: {foo : "bar",
who : "what"},
...
});
If you want to post already-serialized JSON, do it like this:
$.ajax({
...
data: { somevariablename: '{"foo":"bar","who":"what"}' },
...
});
Then, you just have to parse the POST parameter somevariablename on the server side.
Hope this helps!
If its VS2012, try for adding Mime Type Handler, since VS2012 has IIS express and it need to add Mime type handler externally,
Add below code to web.config
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
.. and if its not VS2012 then follow this link
add .json handler support in IIS 7
I want to thank everyone for your help.
I finally had to install the 3.5 Framework on the server, I had no choice.
The second I installed it, and updated the web.config dll's references to 3.5, it worked like a charm.
Thanks again!!!!!

Issue with Chrome calling cross domain jsonp resource via jQuery ajax

solved - it was Adblock Plus
I have a cross-domain OAuth scenario where I'm calling OAuth protected jsonp resources on a 3rd party api directly from JavaScript.
The client relies on my server (the site of origin) to generate signed request urls for OAuth resources on the provider. The client GETs these OAuth resources directly in an attempt to limit OAuth proxy duties of my server to simply generating signed resource urls and letting JS do the rest. Here's the JS:
myNamespace = {
callApi: function(signedRequest, callback) {
$.ajax({
url: signedRequest,
dataType: "jsonp",
type: "GET",
crossDomain: true,
jsonp: false,
jsonpCallback: callback,
cache: true,
async: true
});
},
usersCallback: function(jsonp) {
alert(jsonp);
},
getOAuthResource: function(resource, callback) {
$.ajax({
url: "/GetSignedRequest?resource=" + encodeURIComponent(resource + "&callback=" + callback),
success: function (signedRequest) {
myNamespace.callApi(signedRequest, callback);
}
});
}
}
Because the parameter order matters when signing the request, I include the callback manually so that it gets ordered & included in the signed request the server generates.
So an example usage would be simply,
myNamespace.getOAuthResource("/users?id=1", "myNamespace.usersCallback");
This is working in FireFox 20 and IE 10 - I get the alert msg & the expected json from the provider.
Chrome 26 refuses to perform the cross-domain call to the provider. In dev tools, the GET for the cross-domain resource immediately shows a Status of "(failed)" and the GET shows up in the console as an error.
If I subsequently ask Chrome to open this supposedly "failed" URL in a new window, it re-requests the URL directly on the provider and I get the expected jsonp response:
myNamespace.usersCallback({...})
Why won't Chrome perform the cross-domain call?