skip to Main Content

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


  1. You have to pass search input in any specific key

    let theSearchRequest = $("#search").val();
    $.ajax({
        method:"GET",
        url:"./main.js",
        data: {search: theSearchRequest}
    })
    .done( (theListOfNames) => {
        $("#listOfNames").html(theListOfNames);
    });
    

    On server-side, you will get search input in the query string parameter.

    let request = require("request");
    let names = ["ryan", "liam", "john", "james", "michael"];
    request.get({
        url:"./index.html",
    },
    (error, response, body) =>{
        console.log(body.query);
    
    });
    
    Login or Signup to reply.
  2. 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 but index.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.

    let theSearchRequest = $("#search").val();
    //e.g.
    let theSearchRequestQueryString = 'searchRequest=' + theSearchRequest;
    $.ajax({
        method:"GET",
        url:"./main.js",
        data: theSearchRequestQueryString
    })
    .done( (theListOfNames) => {
        $("#listOfNames").html(theListOfNames);
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search