The Ajax query returned a successful response, yet it unexpectedly triggered an error

Currently, I am delving into the realm of mongodb. I have integrated Express, Body-Parser, and Mongoose into my project, and I'm retrieving data from an online mongodb database hosted on mlab. Everything seems to be functioning smoothly as I've tested Get, Post, and Delete functionalities using Postman. My aim now is to fetch this data using JavaScript in order to display it in HTML format. For this purpose, I am employing Ajax which, although successful, seems to trigger the fail function.

The mongdb controller snippet:

exports.photoalbum_all = function (req, res, next) {
PhotoAlbum.find(({}), function (err, photoalbum) {
    if (err) return next(err);
    res.send("../Views/images", {photo: photoalbum});
});};

The Ajax call being made:


function getPhoto() {
    var photoAdd = 'http://localhost:1234/photoalbums/find'; 
    $.ajax({
        header: 'Access-Control-Allow-Origin: *',
        dataType: "jsonp",
        url: photoAdd,
        contentType: 'application/json; charset=utf-8',
        async: false,
        crossDomain: true,
        success: AjaxSucceeded,
        error: AjaxFailed
    });
}

function AjaxSucceeded(result) {
    alert("hello");
    alert(result);
}

function AjaxFailed(result) {
    debugger;
    alert("hello1");
    alert(result.statusText);
}
getPhoto();

Initially, I encountered errors related to ajax cross-origin request blocked, hence I had to utilize datatype: 'jsonp'. Upon inspecting the network log in the Chrome browser console, I noticed a successful response with the following address:


http://localhost:1234/photoalbums/find?callback=jQuery111202567313069615542_1545928466705&_=1545928466706

This URL returned the Json values below:

[{"_id":"5c22a5ffcb29611f905f756b","title":"prayer","albums":[{"_id":"5c22a5ffcb29611f905f756c","u_name":"family01","u_title":"family_man"}],"createdAt":"2018-12-25T21:49:51.091Z","updatedAt":"2018-12-25T21:49:51.091Z","__v":0},{"_id":"5c22a66bd3527c39342fafe7","title":"prayer","albums":[{"_id":"5c22a66bd3527c39342fafe8","u_name":"family01","u_title":"family_man"}],"createdAt":"2018-12-25T21:51:39.274Z","updatedAt":"2018-12-25T21:51:39.274Z","__v":0}]

Despite exhaustive research efforts, I haven't been able to pinpoint the issue. The formatting of the Json response received from mlab is a suspicion though. Any insights or suggestions are welcomed. Thank you in advance for your assistance.

Answer №1

When it comes to client-side operations, using JSONP is the best option available. To make a proper Ajax JSON call to the server, you'll need to enable CORS on your localhost.

If you're not sure how to do this, check out these helpful tutorials: Deadly CORS when http://localhost is the origin

You can also search for instructions by Googling "Enable CORS on localhost."

We hope this information proves useful to you!

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

Issue arises when the backend is running causing errors in the ReactJS frontend

I am encountering an issue with my React Js frontend and node express backend setup. When I run the frontend using npm start, everything works fine. However, when I also start the backend, I get this error: TypeError: Cannot read property 'map' o ...

JavaScript: Adding up whole numbers--- Reference Error: Undefined

I'm having trouble with my code because it's saying that "t1" is not defined, even though it's the name of my text box. I tried making the variable global by declaring it outside the function, but it didn't solve the issue. Interestingl ...

Different ways to automatically trigger a function in JavaScript

There are various ways to trigger a function automatically in javascript when a page loads. I am interested in knowing which method is considered the most effective and reliable. If you have a unique approach that differs from others, please share it here ...

instructions for creating a hover effect where one div vanishes when hovering over another div

Is there a way to make the line visible when hovering over my circular div? #line { display: none } <div id='circle'> <div id= 'line'> ...

When the credentials flag is set to true, the use of a wildcard '*' in the 'Access-Control-Allow-Origin' header is not allowed, as per Stormpath's guidelines

Currently, I am integrating Stormpath into my project and I want to keep the API separate from the client code (Angular, utilizing Stormpath's angular-sdk). This means that the API will be hosted on a different sub-domain compared to the client. Howev ...

Design a recurring report using an endless JavaScript cycle

I am in the process of creating a brand new scheduled report and have encountered an issue. How can I incorporate a script that includes a loop to run a specific function every 10 seconds? Here's what I have so far: var count = 1; while(count > 0 ...

a dilemma involving syntax and database connectivity issues within a node.js environment

Here is the code I am using for connecting to my database in Node.js: var express = require('express') var mongoose = require('mongoose') var cors = require('cors') var morgan = require('morgan') require('dot ...

Optimal technique for adding elements to the DOM using ngFor

My application features a websocket connected to an ngFor loop that populates data from approximately 100 records. Each entry in the list has a button with a click event attached, triggering the creation of a loading spinner via a 'div' element w ...

When the FileReader reads the file as readAsArrayBuffer, it ensures that the correct encoding is used

Currently, I am developing a script in JavaScript to read uploaded .csv/.xlsx files and convert the data into an array containing each row. Using FileReader along with SheetJs, I have successfully managed to achieve this by implementing the following code: ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

Choose a numeric value and then adjust it to display with exactly two decimal places

My goal is to create a code that achieves the following tasks: Add an ID to every nth child Round the number in each nth child to 2 decimal places Prefix the numbers with a pound sign (£) Loop through until all the nth children in a table are processed ...

Assigning the style of the parent element based on the child element

Currently, I am attempting to develop a customized dropdown field and here is the code I have come up with: const list = document.querySelector('.list'); const listItems = list.getElementsByTagName('p'); document.querySelector('# ...

What methods can I use to differentiate between requests initiated by RenderAction and those sent through AJAX?

When working with ASP.NET MVC, I often use the helpful Request.IsAjaxRequest method to check if a request is initiated via AJAX. However, I have noticed that the RenderAction method also triggers the controller/action call via AJAX. My goal is to have cal ...

Click on the input to add or remove a value

I have written a code where, on click, I insert an email address into a field. However, what I am trying to achieve is that upon the next click on the same field, it will remove the email if one already exists in the input. Below is my current code snippe ...

When using file_get_contents(), you can expect to see text displayed instead of an image

I've been working on this code to extract and display an image from a URL. It seems to be functioning correctly as it's not throwing any errors. <?php $url = $_GET['image']; $image = imagecreatefromstring(file_get_contents( ...

Scroll horizontally through the number field in Chrome

I have configured a number input field with the text aligned to the right. Scenario: While testing, I discovered that selecting the entire text or using the middle mouse button to scroll within the input field allows for a slight leftward scrolling of ab ...

Utilize HTTPS and HTTP with Express framework in node.js

Currently, I am utilizing the express (3.0) framework on node.js to handle routing in my application. While most of the application makes use of the http protocol, there is a specific route that I intend to serve exclusively via https. This particular par ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...

What is the process for capturing a window screenshot using Node.js?

I am currently conducting research to discover a way to capture a screenshot of a window using Node.js. I have been attempting to achieve this with node-ffi, but I am facing some difficulties at the moment: var ffi = require('ffi'); var user32 ...

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...