Executing an Ajax call to trigger a NodeJS function that executes a bash script

I have created a bash script to generate a JSON file that needs to be parsed and sent to the client-side JavaScript for display. My goal is to achieve this without refreshing the page and without using jQuery. I attempted to use Axios but seem to be facing challenges.

Despite my Ajax request, I am unable to reach my NodeJs function or load the file even though it is a direct path. It seems like everything would work if only the function could run properly.

I've been grappling with this issue for about a week now, and I just can't seem to grasp these AJAX requests. If anyone can provide assistance along with a detailed explanation, that would be greatly appreciated.

    function digIt() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if(xhr.readyState === 4 && xhr.status === 200) {
            document.getElementById('mapSection').innerHTML = xhr.responseText;
        } else {
            alert(xhr.statusText);
        }
    };
    xhr.open('GET', "./../../middleware/index.js", true);
    console.log("done");
    canYouDigIt(domain);
    xhr.send();

};

This section contains my HTML code, which is written in Jade/Pug.

 section(id="digToolWrapper")
        form(id="digToolInput")
            ul
                li #[input(id="digTool" name="domain" type="text" placeholder="Can you dig it?")]#[input(id="whois" value="whois" type="button" onclick="digIt(domain)")]

Here's a glimpse of my middleware/index.js file.

    const shell = require('shelljs');


function loggedOut(req, res, next) {
    if (req.session && req.session.userId) {
        return res.redirect('/profile');
    }
    return next();
}

function checkForbidden(req, res, next) {
    if(! req.session.userId) {
        var err = new Error("You are not authorized to view this page.");
        err.status = 403
        return next(err);
    }
    return next();
}


// Whois Bash Script!!!
function canYouDigIt(domain) {
    shell.env["domain"] = domain;
     shell.exec(digIt.sh)
     console.log("here")
    };


module.exports.canYouDigIt = canYouDigIt;
module.exports.checkForbidden = checkForbidden;
module.exports.loggedOut = loggedOut;

This is the script I'm attempting to run, for reference purposes to better understand what I'm trying to accomplish:

domain=google.com
aRecord=$(dig -t a +short $domain)

ipWhois=$(whois $aRecord | awk '/NetRange/,0'| cut -d\# -f 1)

server=$(host $aRecord)

mxRecord=$(dig -t mx +short $domain)

nsRecord=$(dig -t ns +short $domain)

txtRecord=$(dig -t txt +short $domain)

ptrRecord=$(dig -x ptr +short $aRecord)

whoisRecord=$(whois $domain | awk '/Domain Status|Registrant Organization|Registry Expiry Date|Registration Expiration Date|Registrar:/')

serverType=$(curl -iA . -s $domain | awk  '/Server:/ {print $2}')

echo -e "{\n

\t \"domain\" :\n\"$domain\",\n
\t \"aRecord\" :\n\"$aRecord\",\n
\t \"ipWhois\" :\n\"$ipWhois\",\n
\t \"server\" :\n\"$server\",\n
\t \"mxRecord\" :\n\"$mxRecord\",\n
\t \"nsRecord\" :\n\"$nsRecord\",\n
\t \"txtRecord\" :\n\"$txtRecord\",\n
\t \"ptrRecord\" :\n\"$ptrRecord\",\n
\t \"whoisRecord\" :\n\"$whoisRecord\",\n

}" > ./whoisJson/whois$domain.json

Answer №1

When using Ajax, it is important to understand that the script needs to be running on the server side in order to deliver output to the client for display. Setting up a web server on the server side (possibly using node) allows for receiving a GET request from the client, invoking the script, collecting its output, and sending it back to the client. Ajax simply assists in packaging the request to the server and delivering the response.

On the other hand, attempting to download JavaScript to the client and then executing a function like canYouDigIt() on the client side does not align with how Ajax operates. Calling a method on the client side will not automatically run on the server without proper setup and communication between the two sides.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to submit a POST method without using a form?

I am looking to create a button that functions similar to the "Follow" buttons found on social networks. The challenge I face is that I need to refresh the page when the user clicks the button, as the content of the page heavily depends on whether the user ...

What could be causing req.body to consistently come back as an empty object?

I am struggling with req.body always returning an empty object regardless of what I try. I have experimented with: var jsonParser = bodyParser.json(); and then including jsonParser in the function -> app.post('/api/get-last-project',jsonParser ...

What is the best way for library creators to indicate to VSCode which suggested "import" is the correct one?

As a library creator, I have noticed that VSCode often suggests incorrect imports to users. For instance, VSCode typically suggests the following import: import useTranslation from 'next-translate/lib/esm/useTranslation' However, the correct im ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

What makes using the `@input` decorator more advantageous compared to the usage of `inputs:[]`

In defining an input on a component, there are two available methods: @Component({ inputs: ['displayEntriesCount'], ... }) export class MyTable implements OnInit { displayEntriesCount: number; Alternatively, it can be done like this ...

"Encountering an issue with AJAX file upload displaying an error message for

Before I showcase my code, allow me to explain my objective. My goal is to create a page that updates a user's details in the database using AJAX. Initially, I successfully achieved this task. Subsequently, I wanted to enhance the functionality by inc ...

What is causing the issue preventing me from running npm run dev on CentOS 7?

Currently facing an issue while trying to install my application on a new server after migrating from centos6 to centos7. When attempting to install a Laravel app, everything goes smoothly as it did on centos6, except for when I run npm run dev [root@v6-a ...

What is the proper approach for populating custom fields in a bigquery table using NodeJS?

I'm currently utilizing the npm BigQuery module to handle data insertion into bigquery. In my case, I have a personalized field called params which is categorized as a RECORD and has the ability to accept any numerical (integer or floating-point) or t ...

Utilizing AngularJS filter in JavaScript without AngularJS Framework

This is a test to experiment and learn. Currently, I have a JSON object called obj. My goal is to utilize the angular Json filter to format this JSON object and display it in the chrome console. This should be achieved without the need for any button click ...

Toastr Notification Failure in AJAX CRUD Operations

When attempting to display a toastr message in my AJAX CRUD, only the modal pops up and nothing is displayed within it. I have added all the necessary CDN links in the master layout and script tags as well. The data stored successfully in the database show ...

Can JSON be used to perform mathematical operations and calculations?

Utilizing the amazing json-server as my application's backend has been incredibly beneficial for custom data retrieval. However, it would be even more valuable if it supported calculations and expressions to mimic backend behavior. Consider this data ...

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

Tips on transforming JSON data into a hierarchical/tree structure with javascript/angularJS

[ {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"1","zid":"1","statename":"Karnataka"}, {"id":1,"countryname":"India","zoneid":"1","countryid":"1","zonename":"South","stateid":"2","zid":"1","s ...

Transmitting JSON data using a Jquery AJAX request in PHP

I'm facing an issue passing a JSON array from a jQuery AJAX call to a PHP file and attempting to write the received data to a file. This is my code: var contacts = [{"address":[],"phone":[],"last_name":"abc","email":[{"address":"<a href="/cdn-cgi/ ...

Encountered issue with Ajax post request without any additional details provided

I could really use some assistance with this issue. It's strange, as Chrome doesn't seem to have the same problem - only Firefox does. Whenever I submit the form, Ajax creates tasks without any issues. My MySQL queries are running smoothly and I& ...

"Run npm install to add fsevents to your project dependencies

Hey there, I'm currently in the process of setting up fsevents using npm. Here are the versions I'm working with: Node : 4.2.6 NPM : 3.5.2 OS : Ubuntu 16.04 LTS I'm running the following command: Edited npm install fsevents --no- ...

Install a package by using the npm command within a node container

After following the steps outlined in the node.js documentation to create a Dockerfile, I attempted to run the command docker exec -it mynodeapp /bin/bash with the intention of entering the container to install a new npm package. However, I encountered the ...

React Header Component Experiencing Initial Scroll Jitters

Issue with Header Component in React Next.js Application Encountering a peculiar problem with the header component on my React-based next.js web application. When the page first loads and I begin scrolling, there is a noticeable jittery behavior before th ...

Having trouble with playing audio from an array in Javascript

I've been working on creating a Drum Kit website. My approach involves using an array to hold all the sound files, and using a loop to call the play() function. However, I encountered an issue when trying to load the sounds - the debug console showed: ...