1

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.

2 Answers 2

2

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:

$("button").click(function(){
    $.ajax({url: "/some/api/endpoint", success: function(result){
        $("#div1").html(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

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, this is the method i used for my RPI truck, the code would look something like this, if you use express and jquery:

client:

document.querySelector("#urdiv").innerHTML = $.ajax({
  type: "POST",
  url:"192.168.0.7/control/",
  data: {data: data}
})

server:

app.post('/control/', function (req, res) {
  res.send("<h1>Your html goes here</h1>")
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.