Jquery global ajax event handler w/ json data - javascript

I'm trying to make global ajax handler of general purpose responses. (Eg. refresh page)
Is there any handler or hack so i'd get already parsed json, so i woudn't have to parse it twice?
$(document).ajaxSuccess(function(e, xhr) {
// Validate and parse xhr.responseText TWICE!
});
Okay, found a bit "hacky" solution, maybe useful to others :)

Solution is to override jquery ajax json parser:
function parseJsonResponse(d) {
var json = jQuery.parseJSON(d); // Same as default
// Do anything with json object :)
return json;
}
// Override original parser, defaults to jQuery.parseJSON.
jQuery.ajaxSettings.converters['text json'] = parseJsonResponse;
And if you dont want parseJsonResponse to be a global function then you can put this code in self-executing anonymous function

Related

What's the correct way to send Javascript code along with rendered HTTP to a client?

Mid development I decided to switch to server-side rendering for a better control amongst other benefits. My web application is completely AJAX based, no url redirecting, so the idea here is a website that builds itself up
I just couldn't figure out the proper way to send javascript events/functions along with the html string, or should all the necessary javascript always be preloaded in the static files?
Let's say client clicks a pre-rendered button 'open table'
The server will make a query, build the html table and send it back, but this table also needs javascript triggers and functions to work properly, how are these sent, received and executed?
There are a couple of articles that mention to not use eval() in Javascript, is there any way around this? I don't want to have to preload unnecessary events for elements that don't yet exist
The server is Python and the Client is Javascript/JQuery
Theoretical example :
Client Base Javascript :
$("body").on("click", "#open_table", function() {
$.getJSON('/get_table', function(response){
$("#table_div").append(response.html);
eval(response.javascript()); //??
}
});
Python Server(views.py) :
def get_table(request):
data = {}
#String containing rendered html
data['html'] = get_render_table()
#String containing Javascript code?
data['javascript'] = TABLE_EVENTS_JAVASCRIPT
return HttpResponse(json.dumps(data),content_type='json')
Worth noting my question comes from an experimental/learning perspective
Update:
You can use jQuery.getScript() to lazy load JS. I think this solution is as close as you can get to run JS without using eval().
See this example:
jQuery.getScript("/path/to/script.js", function(data, textStatus, jqxhr) {
/* Code has been loaded and executed. */
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
and "/path/to/script.js" could be a string returned from $.getJOSN response.
Also, the documentation for getScrippt() has examples on how to handle errors and cache files.
Old Answer:
Using .on() attaches events to current and future DOM elements.
You can either attache events prior to DOM insertion or attache event after DOM insertion.
So in your example you can do something like:
$("body").on("click", "#open_table", function() {
$.getJSON('/get_table', function(response){
var code = $(response.html);
code.find(".elementToFind").on("click", function (){
// Code to be executed on click event
});
$("#table_div").append(code);
}
});
I did not test the code but I think it should work.
Assuming you can't just set up an event-binding function and then call it from the main script (the JavaScript you need can't be guessed ahead of time, for example) then one really easy way is just to append the JavaScript to the bottom of the returned HTML content within script tags. When it's appended along with the HTML, the script should simply execute, with no eval() required.
I can't swear that this would work in old browsers, but it's a trick I've used a couple of times, and I've had no problems with it in Firefox, Chrome, or any of the later IE versions.
I think I see what you're asking here, from my understanding you want to send the new "page" asynchorously, and render the new javascript and html. It looks like you already got your request/response down, so i'm not gonna go and talk about sending JSON objects, and the whole "how-to" of sending html and javascript because it looks like you got that part. To do what you want and to dynamically add your javascript in, this stackoverflow question looks like it has what you need
Is there a way to create a function from a string with javascript?
So pertaining to your example, here is how it would look when you recieve the JSON string from your python script:
$("body").on("click", "#open_table", function() {
$.getJSON('/get_table', function(response){
$("#table_div").append(response.html);
/* Create function from string */
var newFunction = Function(response.javascript['param_1'], response.javascript['param_2'], response.javascript['function']);
/* Execute our new function to test it */
newFunction();
}
});
*Your actual function contents would be the string: response.javascript['function']
*Your parameter names if any would be in separate strings ex: response.javascript['param_1']
That is almost a direct copy of the "String to function" code that you can see in the linked question, just replaced it with your relevant code. This code is also assuming that your object is sent with the response.javascript object containing an array with your actual function content and parameter names. I'm sure you could change the actual name of the var too, or maybe put it in an associative array or something that you can keep track of and rename. All just suggestions, but hopefully this works for you, and helps you with your problem.
I am also doing similar work in my project where I had to load partial html using ajax calls and then this partial HTML has elements which requires events to be attached. So my solution is to create a common method to make ajax calls and keep a js method name to be executed post ajax call in html response itself. For example my server returns below html
<input type="hidden" data-act="onPartialLoad" value="createTableEvents" />
<div>.........rest of html response.....<div>
Now in common method, look for input[type='hidden'][data-act='onPartialLoad'] and for each run the method name provided in value attribute (value="createTableEvents")
Dont Use Eval() method as it is not recommended due to security
issues. Check here.
you can run js method using window["method name"]...so here is a part of code that I use.
$.ajax(options).done(function (data) {
var $target = $("#table_div");
$target.fadeOut(function () {
$target.html(data);
$target.fadeIn(function () {
try {
$('input[data-act="onPartialLoad"]', $target).each(function () {
try {
//you can pass parameters in json format from server to be passed into your js method
var params = $(this).attr('params');
if (params == undefined) {
window[$(this).val()]();
}
else {
window[$(this).val()]($.parseJSON(htmlutil.htmlDecode(params)));
}
} catch (e) {
if (console && console.log) {
console.log(e.stack);
console.log($(this).val());
}
}
});
}
catch (e) {
console.log(e.stack);
}
});
});
});
use jQuery.getScript() (as suggested by Kalimah Apps) to load the required js files first.

What is this window["obvInit"] ({...}) doing in a script?

I'm attempting to extract some information from Medium URLs and I notice that each page has the entire post contents stored in JSON format. The content looks like this on the page:
<script>// <![CDATA[
window["obvInit"]({"value":{"id":"e389ba1d8f57","versionId":"1b74...
How do I easily extract this JSON from the page? What does the preface of window["obvInit"] before the JSON mean? Can I call the function obvInit in my Chrome console and get the JSON output somehow?
What this does is call a function. It's probably (but not necesarrily) been declared like function obvInit(...){...} on the global window namespace. Now for your problem: You can easily extract the passed object by overwriting the function like this:
var _oldObvInit = window.obvInit;
window.obvInit = function(){
console.log(arguments[0]); //use this to extract the object
console.log(JSON.stringify(arguments[0])); //use this to extract JSON
return _oldObvInit.apply(window, arguments);
}
Put this before the script tag you've posted here and after the declaration of the function obvInit.
A bit context: inside every javascript function there's an implicit variable arguments which stores the arguments to the function as an array. And apply calls a function, sets the context (this) and takes the arguments as an array. Exactly what you need to wrap it.
This is a technique known as JSONP. Basically, since some older browsers don't have great support for cross-origin AJAX using XMLHttpRequest, you can insert a <script> tag into the page that gets the resource you want, except wrapped like this:
functionName({ /* ...data... */ });
So it calls a function known as functionName with the data as an argument. You would provide this function in your own code before inserting that script, like so:
function functionName(data) {
// use the data
}
window["obvInit"]() is equivalent to window.obvInit() which is equivalent to calling a function defined as obvInit at the global level.
As scripts are not subject to the same-origin policy, you can now get JSON-like data from any domain that will return it in this format.

getScript Local Load Instead of Global?

From what I have read JQuery's getScript function loads the script file in a global context using a function called 'global eval'. Is there a particular setting or method to change this so it will instead load within the function I am calling it from?
If I do the following code name returns undefined as its not loading the script in the local context.
function callscript(){
var name='fred';
getScript(abc.js);
}
//abc.js:
alert(name);
I believe I have found the solution using a regular JQuery ajax call. The trick is you set the datatype to 'text' as otherwise if its script or if use getScript or the alternative .get() it will auto run the script inside and place it in the global context.
function abc(){
var msg="ciao";
$.ajax({
url: 'themes/_default/system/message.js',
success: function(data){
eval(data);
},
dataType: "text"
});
}
//message.js
(function() {
alert(msg);
})();
This alerts 'ciao' as expected :)
Before anyone says anything yes I'm using eval but its perfectly fine in this situation.
As you already noticed, there's nothing in the docs regarding this. I double checked the source code and found that the underlying call has no options for you to pass to override this behavior.
// http://code.jquery.com/jquery-1.9.1.js
...
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
...
As far as I can tell, loading a script asynchronously into a local scope is not possible with jQuery. jQuery's API doesn't give you any other means to configure its usage like this.
I am still investigating how it might be possible using some other technique.
Ok i know this is 2017, 4 years later, but it seems jQuery team never bothered to address this issue, well sort of. I had the same problem and i think this is the solution, the actual intended way of using getScript in a local context. What I noticed was that there is no way that code could be easily eval'd in a local context against your code, which jQuery has no idea how it is going. I haven't gone deeper, but if you look at the jQuery source, how it is injecting the script into the document, it's genius, it avoids eval altogether. The script it therefore ran as if it's a file that was imported through script tag. Without further ado...
I have decided to do the vice-versa of the situation, it better explains what's going on. You can then reverse it to that example in question.
If you noticed getScript actually sends a unique ID to the server in the query string. I don't know why they didn't mention this in documentation. Use that to identify returned scripts. But you have to do something in the backend...
let imports;
$.getScript("scripts.php?file=abc.js", (data, textStatus, jqXHR) => {
window[jqXHR.getResponseHeader('X-scriptID')](imports);
alert (imports.name);
});
abc.js:
imports.name = 'fred';
backend wraps whatever script we are getting scripts.php:
// code that gets the file from file system into var $output
$output = file_get_contents($_REQUEST['file']);
// generate a unique script function name, sort of a namespace
$scriptID = "__script" . $_REQUEST['_'];
// wrap the script in a function a pass the imports variable
// (remember it was defined in js before this request) we will attach
// things we want to become local on to this object in script file
$output = "window.".$scriptID."=function(imports) { ".$output." };";
// set the script id so we can find this script in js
header ("X-scriptID: " . $scriptID);
// return the output
echo $output;
What going is that the js requests a script through getScript, but it doesn't request directly to the file it uses a php script to fetch the contents of the file. I am doing this so that i can modify the returned data and attach headers that are used to id the returned script (this is large app in mind here where a lot of scripts are requested this way).
When getScript runs the returned script in the browser as usual, the actual content of the script are not ran, just a declaration of the wrapper function with a unique name __script1237863498 or something like (the number was given by getScript upon requisition of that script earlier), attached to the global window object.
Then js uses that response to run the wrapper function and inject properties into the imports object... which become local to the requesting whatever's scope.
I don't know jQuery implementation, but the reason name is returning undefined is because name is a private property of the callscript object. To negate this, you could declare the variable outside of the function call:
var name = ''; //Declare name outside of the function
function callscript(){
name='fred';
getScript('abc.js'); //Shouldn't it be $.getScript? and argument should be passed as a string
}
//abc.js:
console.log(name) //Returns undefined
callscript(); //Call the script
console.log(name); //Returns "fred"
// global.js
var global1 = "I'm a global!";
// other js-file
function testGlobal () {
alert(global1);
}

Override .load function of jQuery

I have site which uses $(selector).load(path) function in more than 300 pages. Now my client's requirement has changed and I need to access cross domain to call these pages.
For the purpose I have to replace all the .load( function to some cross-domain function with the help of YQL.
Is it possible to override my .load function and call prevent default and do my own code?
There is no clean way to do this, especially since $.fn.load does different things depending on the arguments and replacing it would affect all those subfunctions.
However, jQuery supports AJAX hooks which you might be able to achieve what you want.
In case all you need is support for IE's XDomainRequest, have a look at this plugin: https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js
Anyway, if you really want to replace the ajax load function of jQuery, this code should do it:
var _load = $.fn.load;
$.fn.load = function(url, params, callback) {
if(typeof url !== "string") {
return _load.apply(this, arguments);
}
// do your ajax stuff here
}
This is exactly the same check jQuery uses to decide whether someone wants to bind the onload event or perform an AJAX load.
The most reasonnable way seems to me to not overload the jquery function but simply do a search and replace in your favorite editor to replace $(xxx).load( by yourpackage.load(xxx,.
This can be done in minutes even on 300 js files. Future changes will be easier and the code will be more readable as the reader never expects a jquery function to do something that isn't on the doc.
Yes, it's possible:
$.fn.load = yourFunc;
Is it recommended? I think not.

jQuery injecting data in ajax global event

I'm trying to inject data in my ajax requests, but it fails and I don't know why. I tried to look at the jQuery source code, but still can't find why it doesn't work, Any help appreciated. Here is the code :
$('#someElement').ajaxSend(function(e, req, options) {
options.data += (options.data.length > 0 ? '&' : '') + '__token=' + $('input#requestToken').val();
}).ajaxSuccess(function(e, req, options, data) {
if (data.nextToken) {
$('input#requestToken').val(data.nextToken);
delete data.nextToken;
}
});
The response looks like this :
{
"response":
{
"code":0,
// ...
},
"nextToken":"4ded26352b3d44"
}
A typical request would be, for example :
$.getJSON(url, {something:'value'}, function(data) {
if (data.response.code != 0) {
// handle code
}
});
The problem is that, the data sent is "something=value"; the modified data is not sent.
** EDIT **
The current request data is
something: value
and should be
something: value
__token: 4ded288eec1f56
In the ajaxSend event callback, if I print the value of options.data after modifying it, the value is "something=value&__token=4ded288eec1f56", but "__token=4ded288eec1f56" is not sent. Why isn't it sent in the request?
But more specifically, how to "fix" this, if even possible?
I think the problem is that by the time jQuery decides to call the "ajaxSend" callback, the parameters have already been used to prepare the request. Thus, changing them in that handler has no effect.
edit — given the answer from #mikermcneil I'm not sure this is right. The jQuery "ajax" method is, to say the least, complicated. His sample page certainly seems to work, which confuses me but probably should just help me realize how little I know about jQuery internals :-)
-edit
Update-- the trouble is with getJSON.
It looks like, while jQuery does fire the ajaxSend event in both cases, it doesn't actually use the changed data variable with getJSON like it does with post.
Replace getJSON with $.post to solve your problem (that's what I'm doing in the example I linked to below).
-edit-
Well, I set up a version of it here:
http://abolition.me/toys/View/attachAjax.html
(see the console)
I'm having the server send back whatever it got and it's saying:
__token: "toketoketoke"
key: "val1"
key2: "val2"
So it looks like modifying the request data is working-- what does your handler look like server-side?
I'm looking into it-- first and foremost though (and I mistake I made as I tried to replicate the problem), have you checked that you're assigning your event after the document is ready? ($(function(){ });)
I am not sure that your JSON response is correct:
{
"response":
{
"code":0, <-- this is not valid
},
"nextToken":"4ded26352b3d44"
}
valid should be:
{
"response":
{
"code":0
},
"nextToken":"4ded26352b3d44"
}
To validate your JSON response you can use:
The JSON Validator
You are only passing data within the second parameter in your getJSON call {something:'value'}. Any data you want to send to the server must be included there. Thus, the __token must be included in that parameter.
The third parameter in the getJSON call is the call back function. The parameter passed to that function is the response from the server.
$.getJSON(
url,
{
something:'value',
__token: 'token value'
,
function(response) {
if (response.response.code != 0) {
// handle code
}
}
);

Categories