Creating a class in JavaScript following an AJAX request

After receiving an AJAX response, the class "navtex-message" doesn't work properly when I create HTML with JavaScript.

function formatNtxMessage( m ) {
    return '<div class="row">' +
        '<div class="col-lg-9">' +
            '<div class="navtex-message">' +
                JSON.stringify(m.content).replace(/\"/g, "")  + 
            '</div>' +
        '</div>' +          
    '</div>';
}

function format ( d ) {
    var div = $('<div/>')
     .addClass( 'loading' )
     .text( 'Loading...' );

     $.ajax( {
         type: "GET",
         url: '/api/ntxMessage/' + d.id,
         success: function ( json ) {
             div
                 .html(formatNtxMessage(json.data))
                 .removeClass( 'loading' );
         }
     } );

    return div;
}

The ".navtex-message" class is causing text to break into new lines instead of displaying \r\n:

.navtex-message {
    white-space: pre-line;
}

Here is the string that I receive:

ZCZC QE02\r\n050640 UTC MAR\r\n\r\nSPLIT RADIO\r\n\r\nWEATHER BULLETIN FOR ADRIATIC\r\n\r\nISSUED BY THE MARINE METEOROLOGICAL CENTER SPLIT ON 05/03/2018 AT 0400 UTC\r\n\r\n1. WARNING:\r\n\r\nISOLATED GUST OF SE / NE WIND, IN THE EVENING NW 35-45 KTS, IN VELEBIT STRATE NW TO 55 KTS. POSSIBLE SUDDEN STORMS. \r\n\r\n2. SYNOPSIS:\r\n\r\nTROUGH WITH FRONTAL DISTURBANCE APPROACHED TOWARD ADRIATIC FM THE WEST.\r\n\r\n3. FORECAST FOR THE NEXT 24 HOURS VALID UNTIL 06/03/2018. AT 0400 UTC\r\n\r\nN-ERN ADRIATIC:\r\n\r\nNE, OFFSHORE AT FIRST SE, IN THE EVENING AND OVERNIGHT NW...

Why am I getting line breaks instead of \r\n?

Answer №1

JSON.stringify() will convert the content in m.content to a single-lined json format.

This means that setting white-space: pre-line will have no effect.

To achieve a pretty print of the JSON output, you can add a third parameter (number of spaces) when using stringify.

$('pre').html(
  JSON.stringify({'a': 1, 'b': 'c'}, null, 4)
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

Answer №2

I successfully resolved the following issue:

function formatNtxMessage( message ) {
return '<div class="row">' +
    '<div class="col-lg-9">' +
        '<div class="navtex-message">' +
            message.content + 
        '</div>' +
    '</div>' +          
'</div>';
}

The problem I encountered was that "message.content" is a string value from JSON data :) Thank you for your assistance.

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

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

Does the triple equal operator in JavaScript first compare the type of the value?

When using the triple equal operator, it not only measures the value but also the type. I am curious about the order in which it compares the value and returns false if they do not match, or vice versa. ...

Upgrade your project from Angular 5 to Angular 9 using webpack

I want to share my experience, not ask a question! To upgrade dependencies in package.json: -Update all Angular dependencies to version 9 -Add these dependencies: "@angular-devkit/build-angular": "^0.900.4", "@angular-builders/cu ...

"Enhance your website with dynamic uploader forms and AJAX scripts - Railscast #383 shows you

I've successfully implemented the uploader functionality from Railscast #383, but I'm wondering if it's possible to dynamically add and remove the uploader link using ajax? Additionally, I'd need to include the "service" instance id wh ...

Seasonal selection tool

I need a quarterly date picker feature, ideally using Angular. I am interested in something similar to the example shown below: https://i.stack.imgur.com/9i0Cl.png It appears that neither Bootstrap nor (Angular) Material have this capability. Are there a ...

Whenever I use Vue JS, I notice that it displays [Object object] on console.log and returns Undefined when

Currently, I'm developing Vue.JS code to showcase data fetched by PHP from a server. The PHP sends a JSON object to the Vue for display. Below is my existing code snippet: axiosPost(); } function axiosPost() { axios.post( './Conver ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...

unable to gather information from suppliers

I'm currently building a login page with nextjs and spotify js, but I've run into the following error https://i.sstatic.net/cKiM8.png Here is the code snippet that is causing the issue: import React from 'react' import { getProviders ...

Executing four concurrent requests in JMeter

I'm looking for guidance on how to handle 1 usual request and 3 additional requests that need to be executed concurrently with the first one: Usual request: URL=.../search?folder_Id=${folder_id} Parallel requests: URL=.../search?folder_Id=${folder ...

Performing a Sisense logout by making an API call

I've encountered an issue with logging out a user from Sisense. I successfully log in using JWT and can access my dashboard using SisenseJS. Now, I'm attempting to call the logout endpoint (). Sisense is hosted on another server within the same l ...

Ensure accurate detection of invalid values for SVG Elements in React using jest testing framework

When testing my react app, I am attempting to capture any errors that are thrown or logged to the console. If a regular HTML element such as <p> contains invalid attributes like <p color={false}></p>, react will display an error via cons ...

Unlock the lightbox and send the user to the parent page

Is there a way to simultaneously launch a lightbox popup and redirect the parent page? I have an AJAX script that retrieves HTML content as a response. My goal is to display this content in a lightbox popup while also directing the parent window to a des ...

Following the 'GoRails' tutorial, I have successfully integrated notifications into my Rails application

Recently, I've been working on implementing a notification system following a tutorial. Everything was going smoothly until I started writing Coffeescript. The specific script causing the issue is as follows: class Notifications constructor: -> ...

Utilize a CSS selector to target all deleted nodes using the MutationObserver in the HTML5 API

Is there a way to retrieve all removed nodes from the DOM that have specific classes using CSS selectors? Below is an example of how it can be done with some complexity, but is there a simpler and more general approach? new MutationObserver(mut =& ...

What is the process for generating a "See More" button for the hidden outcomes of a mySQL query?

I've implemented a search engine on my webpage using PHP. Currently, all the results are displayed on a single result page. To improve user experience, I am now looking to limit the number of results to 20 per page and add a "Next Page" link... If I ...

Encountering a problem with the JavaScript promise syntax

Using pdfjs to extract pages as images from a PDF file and then making an AJAX call to send and receive data from the server is proving to be challenging. The implementation for iterating through the pages in the PDF was sourced from: The issue lies in pr ...

Received an empty response while making an AJAX request - ERR_EMPTY_RESPONSE

I am trying to fetch real-time data from my database using Ajax, but I keep encountering an error. Here is the code snippet: <script> window.setInterval( function() { checkCustomer(); //additional checks.... }, 1000); function che ...

angular express cycle without end

I'm experiencing an issue with my express/angular app where the index page is causing an infinite loop. Here's how I have set up my app: app.configure(function() { // setting up our express application app.use(express.logger('dev& ...

When attempting to reload a single page application that utilizes AJAX, a 404 error is encountered

Recently, I've been working on coding my personal website and have successfully created a single page application using ajax. The content is dynamically loaded between the header and footer whenever a navigation bar link is clicked. To enable the back ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...