Sam3000 Sam3000 - 1 year ago 111
Ajax Question

How to use client and server side javascript files correctly - Node.js

This is very new to me, so apologies if these are obvious questions:

I would like a button on a web page to run a server side function and return the output to the client, would the following be the correct method?

  1. Button calls client side function

  2. Client side function makes an AJAX request to a .js file on the server, which runs the function specified in the AJAX request.

  3. The result of the server side function is sent back to the client and can be used to modify the web page content.

If this is the correct method, what would the (vanilla, preferably) AJAX request look like?

My final question is, are only scripts listed within the HTML documents of the webpages downloaded to the client?

I'm sure these are both simple questions, but thank you nonetheless.

Answer Source

Yes that is mostly the correct flow for doing what you want. It is usually the case that your AJAX request will go to an api endpoint on the server, but it could also get the contents of a file.

Your ajax call will look something like:

    $.ajax({url: "/some/api/endpoint", success: function(result){

This uses jQuery to make the request.

Regarding your second question, the browser can use scripts from .js files that are not embedded into your html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download