JSONP error callback without using Jquery - javascript

I'm using JSONP, without jquery, by doing something like this:
var scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = url;
document.getElementsByTagName('head')[0].appendChild(scriptElement);
Where url is for calling my server. Is it possible to return error response (for example, 403) with a message to display, and display it?
I was able to catch the existence of an error by defining:
scriptElement.onerror = function (event) {
...;
};
But this way I'm not able to see the message got from the server.
I can't use jquery so I can't use $.ajax.fail.
Thanks!

Related

How to add a script tag dynamically using javascript and detect if the script failed to load the file?

I know how to add a script tag to the body or head using append functions. But if the file (example.js) that I am trying to add is not present, it gives an error. How do I detect if this happens?
script elements have load and error events you can listen to.
Run whatever your dependent code is in a load event handler and do something else in error handler
Example loading jQuery :
var jQurl='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'
var s = document.createElement('script');
s.src = jQurl;
s.onerror = function(err) {
console.log(err)
}
s.onload = init;
document.head.appendChild(s);
function init(){
console.log('jquery version=', jQuery.fn.jquery)
$('body').append('<h3>Loaded!</h3>');
}
I think you could do something like the following:
script = document.createElement('script');
script.type = 'text/javascript';
script.onerror = () => {
// Whatever you want to do in case the load fails
};
script.src = '...' // your src for the script
// After this, append the script to wherever you want in the HTML document
Hope it helps!

JSONP request error

I'm trying to make a request to this url:
https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=json
...using JSONP.
The function I'm using to make this request is
<script>
function foo(data)
{
var obj = JSON.parse(data);
console.log(obj);
}
var script = document.createElement('script');
script.src = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
</script>
When I load this function in google chrome I get
Refused to execute script from 'https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=jsonp?callback=foo' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
... in the console. How do I execute this request? Thanks!!!
Try changing the src URL to the following:
https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=json&callback=foo
This should cause the API to send the appropriate JSONP response you are looking for.
EDIT - Now with working code.
function foo(data)
{
console.log(data[0]);
}
var script = document.createElement('script');
script.src = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=apple&limit=5&namespace=0&format=json&callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers

Simple http request and response

var _body = document.getElementsByTagName('body')[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = "http://someurl.com?param1=one"
_body.appendChild(newScript);
My Question is
Is there a way to store the respose for this simple http request ?
(Like we have httpRequest.onreadystatechange if we are using ajax)
There is no way to directly access the source code of an externally loaded JavaScript from within JavaScript.
You could (cross-origin rules permissions) request the script with XMLHttpRequest, or the script loaded might include code that exposes the relevant data in a global variable (or passes the data to a callback function you provide).

How to find a file is available on server in jQuery?

I am trying to load a java script file from another server to my web page using java script code document.write method. like,
document.write("<script type='text/javascript' src='http://www.mydomain.com/js/myscript.js'></script>");
But the respective path does not has the myscript.js so its throw 404 File not found error in browser error console.
How can I predict and avoid this kind of errors?
If possible to predict the error, I will display alternative message instead of calling missed js file functions.
Use JavaScript to load script:
function onReadyState() {
console.error("Unable to load file: "+ this.src + ". Please check the file name and parh.");
return false;
}
function addJS(path){
var e = document.createElement("script");
e.onerror = onReadyState;
e.src = path;
e.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(e);
}
addJS('http://www.mydomain.com/js/myscript.js');
Try jQuery.getScript( url [, success(script, textStatus, jqXHR)] ) - you can set success and error handlers in it.
If the file requested is in your domain (as it seems from the question) just do a previous ajax call (with HEAD method) of that resource and check if the response status is 200 (ok) or 304 (Not modified)
try this approach
var js="ajax/test.js";
$.getScript(js) .done(function(script, textStatus) {
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = js;
document.body.appendChild(script);;
})
for more details: jQuery.getScript
Please note: Use javascript (not jQuery) to manipulate HTML DOM

Method for data transfer with bookmarklet

I'm building a bookmarklet for a service. I need to transfer data (url, text) from open window but I don't know which would be the best method. GET limits the amount of data and ajax isn't possible due cross-domain problem.
What would be the optimal way?
You could use POST if it's a lot of data. Create a hidden iframe with a form with a textbox. Set the form method to post and the action to your service. Put the data into the textbox, attach the iframe to the document, and submit the form.
Try something like this:
function postData (data, url, cb) {
var f = document.createElement('iframe'),
fname = (+((''+Math.random()).substring(2))).toString(36);
f.setAttribute('name', fname);
f.setAttribute('id', fname);
f.setAttribute('style', 'width:0;height:0;border:none;margin:none;padding:none;position:absolute;');
document.body.appendChild(f);
var frame = window.frames[fname],
doc = frame.document,
form = doc.createElement('form'),
text = doc.createElement('textarea');
text.setAttribute('name', 'data');
text.appendChild(doc.createTextNode(data));
form.setAttribute('action', url);
form.setAttribute('method', 'post');
form.appendChild(text);
doc.body.appendChild(form);
if (cb) { document.getElementById(fname).onload=cb; }
doc.forms[0].submit();
}
You can remove the iframe from the document in the callback if you want.
You can put your data in an encoded JSON string and send it with and AJAX POST. AJAX support POST.
The method no recommends would work.
An alternate method, to get around the cross-domain issue: you can host a JS file with a majority of the JavaScript required (including the XHR code), and simply use your bookmarklet code to inject a script element into the current page referencing your JS file (line-breaks added for readability; remove them in the bookmarklet code of course):
javascript:(function() {
var sc = document.createElement("SCRIPT");
sc.type = "text/javascript";
sc.src = "http://domain.com/path/to/script.js";
document.body.appendChild(sc);
})();

Categories

Resources