prevent jquery ajax to execute javascript from script or html response - javascript

According to documentation:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string. Similarly,
script will execute the JavaScript that is pulled back from the
server, then return nothing.
How to prevent this?
I have js that shall modify the content that is obtained through ajax. Executing it before the html is returned makes no sense as it does not have content to work on (at least in my case).
my code:
function do_ajax(url) {
$.ajax({
cache: false,
url : url,
success: function(response, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('script') > -1) {
try {
eval(response);
}
catch(error) {}
} else {
var edit_dialog = $('<div class="edit_dialog" style="display:hidden"></div>').appendTo('body');
edit_dialog.html(response);
edit_dialog.dialog({ modal:true, close: function(event, ui) { $(this).dialog('destroy').remove(); } });
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
the script received by ajax is executed twice. First by me in the eval(response), then jquery execute it again (as described in the documentation)

Lee's answer already adequately addresses the case of HTML responses - scripts embedded in these are not in fact executed automatically unless you add the HTML to the DOM, contrary to the erroneous documentation you quoted.
That leaves the other case asked about in your question title - preventing script responses from being executed automatically when received. You can do this easily using the dataType setting.
$.ajax('myscript.js', {
dataType: 'text',
success: function (response) {
// Do something with the response
}
})
Setting dataType to 'text' will cause jQuery to disregard the Content-Type header returned from the server and treat the response like plain text, thus preventing the default behaviour for JavaScript responses (which is to execute them). From the (recently corrected) docs:
The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.
...
If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.

jQuery.ajax does not evaluate scripts on return when requesting HTML. The passage you quoted in the question was in fact a long-standing error in the documentation, fixed as of April 2014. The new docs have this to say (emphasis mine):
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
...
If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.
The scripts are evaluated in this case when you call
edit_dialog.html(response);
If you don't want to evaluate the scripts before inserting your response in to the DOM, you should be able to do something like:
edit_dialog.html($($.parseHTML(response)));
parseHTML is the key in that by default it removes script tags. However, be aware that parseHTML is NOT XXS safe and if your source is unknown this is still a security concern.

The documentation states that any embedded Javascript inside the retrieved data will be executed before the HTML is returned as a string. If you want to then alter whatever you have retrieved using your ajax call, you can do so within the succes property:
$.ajax({
url: "example.html",
type: "GET",
dataType: "html",
succes: function(data){
// Example: alert(data);
// Do whatever you want with the returned data using JS or jQuery methods
}
});

That's one of the really annoying things about jQuery that it executes javascript on response.
Other frameworks like MooTools disable script execution from responses unless you specifically set that you want them executed which is a much better approach.
The only way I could figure to prevent scripts being executed is to add a custom dataFilter
Its easy enough but I think it should be default and an ajax option to enable script execution if you want it (I've never had a use for it and other frameworks disable by default for security etc.)
Example
$.ajax('uri',{
dataFilter: function(data, type)
{
type = type || 'text';
if(type=='html'||type=='text'){
/*return data.replace(/<script.*>.*?<\/script>/gi, '');*/
return data.replace(/<script.*?>([\w\W\d\D\s\S\0\n\f\r\t\v\b\B]*?)<\/script>/gi, '');
}
return data;
}
, success: function(data)
{
// whatever
}
});
** UPDATED **
Needs that crazy regex to cover more script tag instances
NOTE
if dataType hasnt been set in options it will be undefined in dataFilter so I just default it to text for the filter - if you remove that line then it will only work if dataType is explicitly set.

Related

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

jQuery AJAX reload specific div

I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}

Why isn't this ajax returning the expected javascript

I have the following code:
var statusCheckUrl = "https://www.mydomain.com/webchat/live?action=avail";
$.ajax({
crossDomain: true,
dataType: "script",
url: statusCheckUrl,
success: function(result) {
console.log("result is: "+result);
eval(result);
},
error: function (jqXHR, textStatus, msg) {
unavailable();
},
timeout: 2000,
cache: false
});
If I access the url: https://www.mydomain.com/webchat/live?action=avail in my browser, the response looks like this: var isAvailable = true;
However, my console.log is printing out undefined which is obviously not working as expected.
I am running this code from localhost but thought that the crossDomain: true would overcome any cross domain issues?
How can I resolve this and why is it returning undefined in my success function?
EDIT: I have tried what the person below suggested with regards to the eval but it seems that the result value is always undefined, no matter what. Why am I getting undefined as a result of this ajax call?
The problem is not in the AJAX call, but instead that eval runs in its own scope. The var keyword in the downloaded script is setting a local variable which quickly goes out of scope. Instead you want to set a global variable (remove the var keyword).
See also: Using eval() to set global variables
Side comment: Don't execute code you don't have to, especially dynamically and cross-domain. If all you want to do is get a value - in this case if something is available or not - just return the value. (If you're not in control of the script, but it always looks the same, you could always parse it as a string. You may want to write a script which runs at some interval to check and alert you of any changes in their response format, however.)
Best practice for cross-domain requests is to make your request in your server side framework (.net, php), parse the info and get what's needed, then use your own response (json, text, whatever) back to the page.
As #Ic. said, you shouldn't be executing the code. Decent security risk there.

Getting rss feed with jquery and ajax

I found this site that allows to convert RSS feeds into json.
It also provides a way to specify a callback, so i think users are able to make jsonp calls to this web service.
However, i tried different ways to do that but none worked.
Here is my code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://www.blastcasta.com/feed-to-json.aspx',
dataType: "jsonp",
jsonpCallback: "loadRSS",
data: {
feedUrl: 'http://xml.corriereobjects.it/rss/homepage.xml',
param: "callback"
},
success: function (data) {
var list = "";
for (var propertyName in data) {
list+=data[propertyName];
}
console.log(list);
},
error: function(xhr, ajaxOptions, thrownError){
alert(ajaxOptions)
}
});
});
Whatever i try, the success handler doesn't get executed. I get error handler instead.
I tried with jsonpCallbak: "callback", jsonpCallback: "?", param: "callback" and other values too but without success.
I have to use ONLY javascript without the support any server side scripting language (no aps, no php, etc.)
Did someone get this service working in his site?
Any suggestion would be really appreciated!
I find jQuery JSON API not suitable for this kind of JSON response that provides BlastCasta service. It assigns JSON to a custom variable, specified in URL, and doesn't uses callback functionality JSONP operates with. For example this URL:
http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml&param=rssFeed will return following response:
rssFeed = { "rss": { "channel": /*...*/}}
So, script injection technic may be used:
/* URL of the BlastCasta service and his parameters:
feedUrl :== escaped URL of interest (RSS Feed service)
param :== javascript variable name which will receive parsed JSON object */
var url = "http://www.blastcasta.com/feed-to-json.aspx"
+"?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml"
+"&param=rssFeed";
/* since the service declares variable without var keyword,
hence in global scope, lets make variable usage via window object;
although you can write param=var%20rssFeed" in the URL :) */
window.rssFeed = null;
$.getScript(url, function() {
/* script is loaded, evaluated and variable is ready to use */
console.dir(window.rssFeed);
/* some feeds are huge, so free the memory */
window.rssFeed = null;
});
Update:
here's an example that works for your code:
$.getJSON("http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http://xml.corriereobjects.it/rss/homepage.xml&param=?", function(data) {
console.dir(data);
});
problem is, that I get some javascript errors with returning json:
see this jsfiddle

Should be really simple Jquery jsonp

Why does this not work? anybody:
In my code I have:
$.getJSON("http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=?",
function(data){
//This never gets executed
alert('here');
});
The text file can be viewed here:
http://isp123.co.uk/cw/NorthWales/Test.txt
This is not a JSONP response:
({"name" : "hello world"});
If you had a proper JSONP response, then your code should work.
The question mark in the "callback=?" part of the URL is changed by jQuery before making the request, your JSONP server needs to be able to dynamically create the JSONP "function" in response to the unique jQuery request. If you can't dynamically create your JSONP, perhaps you could use YQL/Yahoo pipes to turn it into JSONP?
This pipe should do the trick, to see if it works, use this URL instead in your getJSON function: http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?
I just tried this and it worked:
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?u=http%3A%2F%2Fisp123.co.uk%2Fcw%2FNorthWales%2FTest.txt&_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&_callback=?", function(data){
//This always gets executed!!!
alert('here');
});
I don't know if you know enough about JSONP but this is not JSONP
?({"name" : "hello world"});
It really should be something like this http://isp123.co.uk/cw/NorthWales/Test.txt?jsoncallback=foo
foo({"name" : "hello world"});
From the jQuery.getJson manual page:
Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.
Your JSON is invalid according to http://jsonlint.com/
Here Clearly mentioned
As of jQuery 1.5, setting the jsonp
option to false prevents jQuery from
adding the "?callback" string to the
URL or attempting to use "=?" for
transformation. In this case, you
should also explicitly set the
jsonpCallback setting
and read jsonpCallback section
jsonpCallback,
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
Probably worth using jQuery.ajax() - http://api.jquery.com/jQuery.ajax/
You can pass in the dataType as "jsonp" and then jQuery takes care of all the callback business, but more importantly you can specify a function to run when there's an error, which may help you:
$.ajax({
dataType: "jsonp",
success: function(d) {console.log(d);},
error: function() { console.log("error") } //do your debugging in here
//add other parameters such as URL, etc
});
The error function you define can be passed 3 variables, read up on it on the ajax() page on the jQuery docs (linked at the beginning of my post) to find out more about that and how to use them.
Your problem lies with how your server is outputting the information. In the link you've supplied, the assumption is that any name placed in the ?jsonpcallback should result in wrapping the JSONP code in a function with that same name. It, however, is not the case.
So the next option is this: use a static function name in your server file and wrap the code. (e.g. use foo(<jsonp>) and stick with it) Then, you have to explicitly tell jQuery that we are going to use a specific function name (leave jQuery with the assumption it's supplying (and thus receiving) that name back, when in-fact you're just supplying it server side and filling in the blanks).
Once you have your file setup, use something like the following:
$.ajax({
// setup the request
url: 'http://isp123.co.uk/cw/NorthWales/Test.txt',
crossDomain: true,
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'foo', // "supply" the jsonp function (pseudo-defined)
// function to call when completed
complete: function(data){
alert(data);
}
// just in case, catch the error
error: function(j,t,e){
alert('AJAX Error');
}
});
So now when jQuery makes the call and it thinks it's supplying the callback, it's really just getting the server-defined callback in return. So, for the above to work, your text file should look something like this:
foo({name:"Hello, World!"});
Also, if you can, change your header to application/javascript, though this is some-what optional.

Categories

Resources