Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 477
Mojimi Avatar asked Dec 09 '16 17:12

Mojimi


People also ask

How does JavaScript send data to server?

When sending data to a web server, the data has to be a string. So we are using JSON. stringify() function to convert data to string and send it via XHR request to the server.

How does JavaScript interact with a server?

The server responds with the requested content. This is usually the dynamic content, and can come in many different formats: HTML, XML, JSON, plain text, etc. That response comes back to the JavaScript code, and the JavaScript code parses the content to build out the rest of the UI using JavaScript functions.

Where do I put JavaScript code in HTML?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


1 Answers

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.

like image 103
Kalimah Avatar answered Nov 03 '22 00:11

Kalimah