I'm not sure if this is crossdomain issue or not. I'm trying to use $.ajax to load file. But some file I get readyState=4 and some file I get readyState=1
This is the path where I run my jasmine test
file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html
And in the code I used jQuery.pyte to require relevant file. But it's stuck at readyState:1 when the code comes to $.ajax
if I do something like this, it returns readyState=4 correctly and print out the content inside SpecRunner.html
$.ajax({url: 'file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html', async: false}).responseText
but if I do something like this, I only get readyState=1 and nothing is returned.
$.ajax({url: 'file:///home/myname/development/path1/path2/src/main/webapp/static/js/core/application/FileThatIWant.js', async: false}).responseText
you should avoid file:// URLs in general, because browsers do not allow them in many different places. Try XAMPP it's a simple to use local webserver, you will definitively need one.
Yes, this is a cross-domain issue. You can solve this problem by forcing jQuery to use crossdomain AJAX (JSONP).
$.ajax({
url: "yoururl",
cache: false,
crossDomain: true,
data: {}, //put your GET parameters here or directly into the url
dataType: "jsonp",
processData: true,
success: function(data, textStatus, jqXHR){
//This will be executed if it worked
},
error: function(data, textStatus, jqXHR){
//This will be executed if it failed
},
timeout: 4000, //You can put any value here
traditional: true,
type: "GET"
});
jQuery will automatically add a callback parameter containing a random string (&callback=XXXXXX).
The target URL needs to output the following:
XXXXX(your_output_encoded_in_JSON);
where XXXXX is the random string. The PHP code to do so is:
echo $_GET["callback"]."(".json_encode($myoutput).");";
Make sure that the PHP (or whatever language you're using) page ONLY outputs that!
If, instead, the page you are querying is not built dynamically, such as an HTML page, you need to add the following options to the $.ajax options object:
jsonp: false,
jsonpCallback: "mycallback",
mimeType: "text/javascript",
Your .html file will contain something like this:
mycallback("<html><head></head><body>TEST PAGE. This is a double quote: \" and I didn't forget to escape it!</body></html>");
This technique is very handy to bypass the strict crossdomain restrictions hardcoded in browsers, but it only supports GET parameters. XMLHTTPRequest v2 supports cross-domain requests, but we won't be able to assume that all users have a XHRv2-compatible browser before at least 2016.
http://caniuse.com/xhr2
Related
I have a web service that expects POST requests carrying a JSON string in the body. I'm trying to use this web service using jQuery, but I have two problems :
1) jQuery seems to always use the GET method, no matter what I do ;
2) jQuery seems to append weird things into the URL.
The relevant pice of my code :
var WEB_SERVICE_URL = 'http://localhost/XXXX/';
// ...
$.post({
url: WEB_SERVICE_URL + 'GetConfigLabels/',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
success: function(response) {
// Whatever
},
error: function(xhr, message) {
// Whatever
}
});
The developper tools of the browser (Firefox Quantum 60.0.2) shows me a weird URL :
http://localhost/XXXX/GetConfigLabels/?callback=jQuery331012146934861340841_1530707758905&{}&_=1530707758906
While the following was expected :
http://localhost/XXXX/GetConfigLabels/
Also the HTML file is openned as a file (using file:///) through the file system, hence the use of JSONP for cross domain.
I failed to find existing questions related to this issue. What could be causing this ? Thank you !
Please refer to the dataType : json section at http://api.jquery.com/jquery.ajax/ :
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests that have a callback placeholder,
e.g. ?callback=?, are performed using JSONP unless the request
includes jsonp: false in its request options. The JSON data is parsed
in a strict manner; any malformed JSON is rejected and a parse error
is thrown. As of jQuery 1.9, an empty response is also rejected; the
server should return a response of null or {} instead. (See json.org
for more information on proper JSON format
overrding random name of callback using jsonpCallback :
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.
I used i18n plugin for load *.properties file for translation and its working fine on android platform but same library not working on IOS 10.3.1. It gives me below error:
i have done some changes in i18n library but still its not working.
function loadAndParseFile(filename, settings) {
$.ajax({
url: filename,
async: false,
cache: settings.cache,
crossDomain: true,
jsonpCallback: 'callback',
contentType: 'text/plain;charset=' + settings.encoding,
dataType: 'text',
success: function (data, status) {
parseData(data, settings.mode);
}
});
}
In above code:
i have been added Cross-Domain 'true' and datatype 'text'.. when i changed datatype 'text' to 'jsonp' its working but it gives .properties file error.
Please check below error..
That means. file is loaded, but inner data format is different.
If you are using now JSONP instead of text, the file will be loaded as javascript code, so if contents are not valid javascript code it will fail.
Surround data with a global variable assignation or a function call:
window.variable = "_DATA_"; // or
functionName("_DATA_");
If _DATA_ are JSON format, then you don't need surround with quotes, otherwise you'll need to use "_DATA_" because without quotes it will not be valid javascript syntax.
add this line to your ajax parameters
xhrFields: {
withCredentials: true
}
Fellas,
I'm trying to do an ajax call to get some JSON. I can get around the cross origin issues in Chrome very easily but in IE the only way I got it working without throwing an error is using JSONP. My problem is that i don't know how to process the response. I can see that the call executes and it returns JSON in fiddler but how do i catch it and play with it in my code that's below.
$.support.cors = true;
function callAjaxIE(){
$.ajax({
type: 'GET',
async: true,
url: usageUrl,
dataType: 'jsonp',
crossDomain: true,
jsonp: false,
jsonpCallback: processDataIE,
// cache: false,
success: function (data) {
alert('success');
//processData(data)
},
error: function (e){
console.log(e);
}
}).done(function (data) {
alert('done');
});
function processDataIE(){
alert('processing data ie');
}
It works when i run it, it displays a message box saying 'processing data ie' but so what. How do i play with the results?
UPDATE:
So I've updated the code as per Quentin. It doesn't go into the 'success' block. It errors out with the following.
When i look at fiddler. The JSON is there. How do i get it?
Don't force the function name. That's a recipe for race conditions. Remove jsonpCallback: processDataIE. Let jQuery determine the function name.
Don't remove the callback parameter from the URL. Make the server read callback from the query string to determine which function to call. Remove jsonp: false,.
Use the success function as normal. (Get rid of processDataIE, that's what success is for).
Asides:
crossDomain: true is pointless. It tells jQuery that when it is using XHR (which you aren't) and the URL is pointing to the same origin (which it isn't) then it should not add extra headers in case the server does an HTTP redirect to a different origin.
async: true is pointless. That's the default, and JSONP requests can't be anything other than async anyway.
$.support.cors = true; is pointless at best and can be harmful. Remove it.
Don't override jQuery's detection of support for CORS by the browser. You can't make ancient browsers support CORS by lying to jQuery. You're using JSONP anyway, so CORS is irrelevant.
The above is the sensible, standard, robust solution.
If you want the quick hack that maintains all the bad practises you have in play, then just look at the first argument to processDataIE.
When I first load a page I make an ajax call to bring some data for the client-side. The call is made to a different domain and the answer comes as JSONP. The call looks similar to:
$.ajax({
type: "GET",
url: url + "?callback=?",
dataType: "jsonp",
contentType: "application/javascript;charset=UTF-8",
async: true,
success: successCallback,
error: errorCallback,
cache: true,
jsonpCallback: jsonCB
});
'application/javascript' would be the possible culprit here as I did my research on the subject but this is present in a previous version of the code which never had this problem.
On all browsers except IE I receive the following error (sometimes, usually the first time and then the problem dissappears) :
script5007 object not found - line 1, char 1
The JSONP received looks like that:
func({"result":"abc"})
The param of the func is a valid JSON as I checked this using jslint.
Any idea will be highly appreciated! Thank you!
You're missing the object brackets { } inside your $.ajax function. Modify it like so:
$.ajax({
url:'',
contentType: 'application/javascript;charset=UTF-8',
crossDomain:true
......
});
The jQuery $.ajax method either takes a url parameter and an optional parameter of additional options specified as an object, or an object parameter including the url.
I am trying to access data from a php server with a cross domain support. So when i try $.ajax with dataType : 'jsonp' i have an error in console: Uncaught SyntaxError: Unexpected token The file is interpret as a javascript file an the request fail. Have you an idea for get data whithout this error.
$.ajax({
url : 'http://domaine.com/json.php',
contentType: "application/json; charset=utf-8",
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});
First make sure that your PHP script supports JSONP. Identify the query string parameter that needs to be passed so that the script returns JSONP. Then test it in your browser by directly entering the following address in your address bar:
http://domain.com/json.php?callback=abc
You should see something along the lines of:
abc({ ... some JSON here ... })
You might need to adjust the callback name parameter if your PHP script expects a different one. This could be the case if you see the following output ({ ... some JSON here ... } without being wrapped in your javascript function)
And once you have ensured that you have a valid PHP script that returns JSONP you could consume it:
$.ajax({
url : 'http://domain.com/json.php',
jsonp: 'callback',
dataType : 'jsonp',
success : function(data){
console.log(data);
// no enter in this callback
},
complete: function(data1, data2, data3){
// no data from file.js
}
});
Things to notice:
I have specified the callback using the jsonp: 'callback' parameter
I have gotten rid of the contentType: 'application/json' parameter because jQuery's implementation of JSONP uses script tags which doesn't allow you to set any request headers.
You need to add ?callback=? to the request so that the proper callback is evaluated. It may not be called callback, though. You need to find out what it is called from the domain.
If the domain (and browser) supports CORS, you don't even need to use JSONP. You can use a normal request.