I am trying to do a AJAX request with server side Node JS and client side Jquery.
Currently my client-side code looks like this:
let theSearchRequest = $("#search").val();
$.ajax({
method:"GET",
url:"./main.js",
data: theSearchRequest
})
.done( (theListOfNames) => {
$("#listOfNames").html(theListOfNames);
});
my server-side code looks like this:
let request = require("request");
let names = ["ryan", "liam", "john", "james", "michael"];
request.get({
url:"./index.html",
},
(error, response, body) =>{
console.log(body);
});
the output is that the “p” tag with the id “listOfNames” shows the server side code.
How do I send and receive the ajax request instead of grabbing the code from the main.js file?
2
Answers
You have to pass search input in any specific key
On server-side, you will get search input in the query string parameter.
In your jQuery ajax request you are calling
url:"./main.js"
which actually is a file (a javascript file).I assume
main.js
is your server side code, right?What you want to do, is to call not
main.js
butindex.html
in your ajax request on the client side.On top, you should convert the searchRequest value to a query string and send that to the server.
I can’t tell if this is what you really want to achieve (calling the
index.html
file).In order to work anyway, the node.js server needs to run.