Retrieve the JSON object with an AJAX request that contains three arrays, then transfer these arrays to JavaScript

A web page I designed generates the following content:

<script>
  var JSONObject = { "groups":['1210103','1210103','1210103','1210405'],
                     "prices":['279,00','399,00','628,00','129,00'],
                     "titles":['','','','']
                    }; 
</script>

This page gets called through an ajax request:

$.ajax({url:plink,success: function(result) { }

Now, I am looking to receive the JSON arrays and convert them into regular JavaScript arrays. How can I accomplish this?

I have attempted:

result = jQuery.parseJSON(data);
mygroups = result.groups;
myprices = result.prices;
mylabels = result.titles;

Answer №1

Modify your webpage to exclusively generate JSON:

{"groups":["1210103","1210103","1210103","1210405"],
 "prices":["279,00","399,00","628,00","129,00"],
 "titles":["","","",""]
}

Remember, when working with JSON, always use " for string quoting, not '.

Ensure the Content-Type header of your response is set to application/json. If you encounter issues setting the header, you can specify dataType: 'json' in your jQuery ajax call to interpret the response as JSON, although it's preferable to set the correct Content-Type header.

Following this, in the success callback of your ajax call, the result will already be a deserialized object with three properties (groups, prices, titles), presented as JavaScript arrays for manipulation.

See Live Example | View Source


As mentioned in the comments, your page is a complete HTML page embedded with a script tag, and you have limited control over its content due to the CMS in use.

It is highly recommended to consider transitioning to a more adaptable CMS.

If transitioning is not an immediate option, you can acquire the page as text and parse the JSON. Revise your script tag as seen below:

<script>
var JSONObject = /*XXX_JSONSTART_XXX*/{"groups":["1210103","1210103","1210103","1210405"],
 "prices":["279,00","399,00","628,00","129,00"],
 "titles":["","","",""]
}/*XXX_JSONEND_XXX*/;
</script>

Utilize the markers to extract the JSON section between them, and implement $.parseJSON for processing. Here's an example:

(function($) {

  $.ajax({
    url: "http://jsbin.com/ecolok/1",
    dataType: "text",
    success: function(result) {
      var startMarker = "/*XXX_JSONSTART_XXX*/";
      var endMarker   = "/*XXX_JSONEND_XXX*/";
      var start, end;

      start = result.indexOf(startMarker);
      if (start === -1) {
        display("Start marker missing");
      }
      else {
        start += startMarker.length;
        end = result.indexOf(endMarker, start);
        if (end === -1) {
          display("End marker missing");
        }
        else {
          result = $.parseJSON(result.substring(start, end));
          display("result.groups.length = " + result.groups.length);
          display("result.prices.length = " + result.prices.length);
          display("result.titles.length = " + result.titles.length);
        }
      }
    }
  });

  function display(msg) {
    $("<p>").html(String(msg)).appendTo(document.body);
  }

})(jQuery);

View Live Copy | View Source

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

Clicking outside the div will cause the div to be hidden

Looking for some help with a jQuery issue. I have a pop-up that opens when a div is clicked, but I want it to close when clicking outside of the div instead of just on the close button. <a class="close-up" href="#" onclick="popup('popUpDiv')" ...

Storing numeric values as strings while using mysqli_fetch_assoc or PDO fetch assoc may pose some potential issues

Today, I searched high and low for the solution but came up empty-handed. I've noticed that mysqli_fetch_assoc seems to be treating my numbers as strings. Typically, this wouldn't bother me much. However, since my site relies heavily on ajax an ...

Utilizing JavaScript Callbacks in HTML Image Tags

Currently I am working on a small application and looking to include a YouTube section. I have come across a method for obtaining the user's YouTube icon: This is included in the head section of my code: <script type="text/javascript" src="http:/ ...

The ajax function is malfunctioning when called from an external JavaScript file

I am having an issue with a Registration page that only has UserName and Password fields. When I click on the Submit button, I want to be able to submit the new User Details using an ajax call with jQuery. I have tried defining an Insert function on butt ...

The successful JSON response in an Ajax request is not functioning as expected

I've set up a data table that allows users to add rows by clicking the "plus" button. This triggers an ajax request to a URL with the rowId as a parameter (which corresponds to the specific row where the button was clicked). I expect to receive a JSON ...

Tips for utilizing rowspan and colspan in BootstrapTable

I am creating a table using bootrapTable and would like to know how I can use rowspan or colspan to achieve a table layout similar to the one shown in this image: Click here for image description $table.bootstrapTable({ columns: [{ ...

Utilizing ElementRef in Angular 4 to close dropdown when clicking outside of it

I recently came across this helpful tutorial, but I'm having trouble grasping how it actually functions. Here's the code snippet I've incorporated into my TypeScript file: @Component({ host: { '(document:click)': 'onOuts ...

How can we improve the Promise.all syntax for cleaner code?

Recently diving into Node.JS, I find the syntax of Promise.all returning an array to be quite frustrating. For example: const requiredData = await Promise.all([ getFirst(city), getSecond(hubIds), getThird(city, customerCategoryKey ...

The state remains unchanged when useState is invoked

I am currently designing a unique restaurant website template. As part of the project, I have implemented a modal box with two arrow buttons to navigate between pages. The issue I am facing is that the value of the pageNumber variable, tracked using useSta ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

I am facing an issue with my react-app where it compiles successfully without any errors, but it is not rendering any elements

JavaScript file to run with npm start: import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import Routes from './routes'; ReactDOM.render( <R ...

Like button for Facebook located at the bottom of a static webpage

I am facing an issue with my web application where it does not scroll properly, especially when there is a Facebook button at the bottom. The behavior in Chrome and Firefox is inconsistent and causing some trouble. In Chrome, the div repositions correctly ...

Using Javascript to dynamically flash-highlight text on a webpage when it first loads

I am looking to create a special highlight effect that activates when the page loads on specific text. Let's focus on the element with id="highlight me". The highlight should glow twice around the selected container before fading out. For a clear unde ...

An error was encountered: SyntaxError - An unexpected token '!' was found

I am having trouble creating a react cluster map. I encountered a SyntaxError, and I'm not sure what went wrong. Initially, my map was working fine, but after using the use-supercluster npm package, it started showing an Uncaught SyntaxError: Unexpect ...

AngularJS testing typically involves the use of the inject module injection process

Currently, I am working on testing a service called documentViewer, which relies on another service named authService. angular .module('someModule') .service('documentViewer', DocumentViewer); /* @ngInject */ function Do ...

What is the process of creating a global variable in Node.js?

My task involves calling an API that will return a JSON object stored in a variable. I need to print part of this JSON object on the console. However, I am facing an issue where I can't load the data to the console outside of the request{} loop. How c ...

Is there a way to properly set a JsonNode in Mongo without converting it to a String using Jackson in Java?

After receiving a Json response from my server, I process it like a JsonNode { "results": [], "metadata": { "total_hits": 0, "max_score": 0 } } I then convert it into a String and store it in the MyProccesResponse field of my mongo database. How ...

Searching for the optimal way to uncover the longest sequence of characters at the tail end of an array that match those at the start of the array

Is there a way to write code in PHP that can identify the maximum sequence of characters at the end of an array that match the beginning of the array? I am unsure about how to achieve this with PHP. Can you help me out? Here's an example to clarify: ...

Flask Modal fails to function properly in the absence of table data

I'm currently troubleshooting an issue with my modal on a Flask web app that utilizes a SQLite database. When trying to add new rows to the table using some JavaScript code, everything works perfectly unless the table is empty. In that case, I am unab ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...