Using XMLHttpRequest with the easy-to-use MongoDB REST endpoint

I am new to both Ajax and MongoDB. I wanted to visualize some of my MongoDB data using a web browser, which is currently running on the same host. My idea was to retrieve the data through XMLHttpRequests. The MongoDB instance is running with the --rest option and when I access hxxp://localhost:28017/test_db/ss_test/ in Firefox, I receive the expected response (a JSON document containing data from the ss_test collection in the test_db database). Everything seems to be working fine so far.

I created a JavaScript function that I linked to a button's "onclick" event:

function makeRequest()
{
  var myrequest = new XMLHttpRequest();
  myrequest.onreadystatechange = function()
  {
    alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
    if (myrequest.status == 200 && myrequest.readyState == 4)
    {
      // ...do something with the response
    }
  }    
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}

When I load the HTML file in Firefox, open the console, and click the button, I can see that the http request is being sent, the status code is "HTTP/1.0 200 OK," and a response with Content-Length: 219257 is received, which is promising. However, the XMLHttpRequest object does not show the status=200. The alerts constantly display a status of 0 while the readyState progresses from 1, 2, to 4, and my if statement remains false.

Can someone please guide me on where I might be going wrong? Initially, I suspected issues with loading the HTML via the file protocol or potential same-origin policy problems, but even after moving the HTML file to a localhost web server and accessing it from there, the problem persists. Thank you for any help!

Answer №1

To tackle the request, it is essential to develop a function.

Check out this informative link for more insights.

Explore further details on AJAX here.

function makeRequest()
{
  var myrequest = new XMLHttpRequest();
  myrequest.onreadystatechange = create_this_function()
  {

  }    
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
#
function create_this_function()
{
    alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
    if (myrequest.status == 200 && myrequest.readyState == 4)
    {
      // ...do something with the response
    }
}

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

The response data from Axios cannot be stored using useState hook

Struggling with fetching data from my express backend and MySQL database to display on my react frontend using axios. However, I'm facing issues when trying to update the fetched data using the useState hook. Here is how my frontend function is struc ...

Attempting to enable a checkbox using a controller located in a separate controller

I am attempting to trigger a checkbox from a separate controller. Suppose I have a card called information technology under one controller, and when clicked, it should redirect to another page that contains a checkbox for information technology managed by ...

Passing ngModel from controller to directive in AngularJS

I'm currently working on a project that involves a controller with an attribute directive nested inside of it. This directive requires access to the ngModel of its parent controller. For more context, feel free to check out this Plunkr. Issue at Han ...

the 'class' keyword cannot be utilized in ECMA6

I attempted to execute a class in ECMA2015 but encountered the following error: class Task { constructor(name) { this.name=name; this.completed = false; }; } I received the error below: class Task { ^^^^^ SyntaxError: Unexpected reserved word} Not ...

Performing a MongoDB query to transform a document into a nested object structure

Hello! I have provided the data below and the desired output that I am looking for. I have been struggling to achieve this using MongoDB aggregation, can you please help me with it? //Sample Data let data = [ {'name': 'A', 'paren ...

Tips for managing both DOM manipulation and state changes at the same time in AngularJS

<div my-custom-directive> <button id="myButton" ng-click="handleClick(mymodel.id)"><button> </div> app.controller('myCtrl', function($scope) { $scope.handleClick = function(id) { //Perform state change here without ...

Utilize Javascript to perform operations on ndb.key()

When working with my application, I encounter keys that are created within a Python system and written to Google Datastore. To access the corresponding data, I require the IDs of these items, which are contained in the 'key' string. Unfortunate ...

What is the best way to retrieve data from a database, display it in an editable table, and then export

After searching diligently, I have been unable to find a table or data grid that is editable and capable of retrieving data from a MySQL database. My attempts with Slickgrid proved challenging due to the lack of documentation and complexity in making it op ...

Activate a function when the v-data-table in Vuetify is expanded and then collapsed

While trying to create a v-data-table, I came across some odd behavior when monitoring the expanded.sync value. The first layer's expanded.sync value seems normal, but the second layer's expanded.sync has three consecutive identical records. I w ...

Retrieving the final item from an ng-repeat loop that has been sorted using the orderBy function

I need assistance in creating a list of terms and their definitions, each categorized under a header based on the first letter of the term. A Apple B Banana Currently, I am using the following code: <div ng-repeat="definition in definitions"& ...

When placed above in the template, the ng-model is causing the ng-repeat to not display anything

Currently, I am teaching myself Angular by following a tutorial at https://docs.angularjs.org/tutorial, but with my twist of using different data to keep things interesting. My struggle seems to stem from a simple mistake I might be making, compounded by ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

What is the best way to integrate a notification system using jQuery?

I am looking to create a notification area that will refresh whenever a new message is sent using jQuery or Ajax (my database is stored in a soap server). I want to make a soap call every few seconds to achieve this, but I'm not sure how to go about i ...

Sort information with checkboxes using jQuery, AJAX, MySQL, and PHP

I am working with a group of dynamic checkbox options related to locations. <?php foreach($qry_2 as $v2) { ?> <li class="checkbox"> <label> <input type="checkbox" class="i-check" id="locality" name="locality[]" ...

JSON conversion error: Unable to convert circular structure to JSON - locate problem within JSON structure

Currently, I am utilizing Contentful in conjunction with a MEAN stack. Upon querying the Contentful API, I receive a json object. contentClient.entries(query, function(err, entries){ if (err) throw err; console.log(entries); }); Lately, I have been e ...

Updating a component from a different source

As a newcomer to React, I'm curious about the ability to update one component's content based on events from another component. I have two React components set up. The first component loads data when the page initializes, while the second compon ...

Ways to showcase flair in PHP code such as this

I currently have this code snippet: <h2 class="index-single">Tech Categories</h2><?php $args2 = array( 'cat' => 11 , 'posts_per_page' => 9 , 'paged' => $paged ); $the_query2 = new WP_Query( $args2 ); ...

Is it possible to create a Queryable in Mongoid 3 and then pass it to a where method?

Trying to understand how to properly utilize an Origin::Queryable object has been a bit of challenge. The documentation for Origin and Mongoid don't provide clear guidance on this topic. Can I create an Origin::Queryable object and then pass it to a M ...

Encountering difficulties displaying a webpage in Express.js following a successful DELETE request

While working on a URL shortening project using Node.js, MongoDB, and ejs, I encountered an issue when trying to render a page after successfully handling a DELETE request. Although the 'deletion' page is loaded in the response preview in the bro ...

Axios.post makes the request twice

Can anyone help me with an issue regarding axios.post where it sends the same request twice with identical data? I have searched online for a solution but haven't found anything. Any ideas on how to resolve this problem? https://i.sstatic.net/lXTss.p ...