What is the best way to extract the value from a JSON URL?

Using AngularJS, I am looking to dynamically retrieve the price value from a URL's JSON data. Is this feasible?

Here is the URL JSON: link

Below is my controller:

angular.module("myApp",['zingchart-angularjs']).controller('MainController', ['$scope', '$http', function($scope, $http) {

  $scope.cities =[{
    "name": "city A",
        "elements": [{
          "id": "c01",
          "name": "name1",
          "price": "15",//I want to get this price from the url json: [url][1]. Get  it from the value of prix_diesel attribute 
          "qte": "10" //I want to get this price from the url json. Get it from the value of prix_essence attribute 
        }, {
          "id": "c02",
          "name": "name2",
          "price": "18",
          "qte": "11"
        }, {
          "id": "c03",
          "name": "name3",
          "price": "11",
          "qte": "14"
        }],
        "subsities": [{
          "name": "sub A1",
          "elements": [{
            "id": "sub01",
            "name": "nameSub1",
            "price": "1",
            "qte": "14"
          }, {
            "id": "sub02",
            "name": "nameSub2",
            "price": "8",
            "qte": "13"
          }, {
            "id": "sub03",
            "name": "nameSub3",
            "price": "1",
            "qte": "14"
          }]
        }, {
          "name": "sub A2",
          "elements": [{
            "id": "ssub01",
            "name": "nameSsub1",
            "price": "1",
            "qte": "7"
          }, {
            "id": "ssub02",
            "name": "nameSsub2",
            "price": "8",
            "qte": "1"
          }, {
            "id": "ssub03",
            "name": "nameSsub3",
            "price": "4",
            "qte": "19"
          }]
        }, {
          "name": "sub A3",
          "elements": [{
            "id": "sssub01",
            "name": "nameSssub1",
            "price": "1",
            "qte": "11"
          }, {
            "id": "sssub02",
            "name": "nameSssub2",
            "price": "2",
            "qte": "15"
          }, {
            "id": "sssub03",
            "name": "nameSssub3",
            "price": "1",
            "qte": "15"
          }]
        }]
      }, {
        "name": "city B",
        "elements": [{
          "id": "cc01",
          "name": "name11",
          "price": "10",
          "qte": "11"
        }, {
          "id": "cc02",
          "name": "name22",
          "price": "14",
          "qte": "19"
        }, {
          "id": "cc03",
          "name": "name33",
          "price": "11",
          "qte": "18"
        }]
      }, {
        "name": "city C",
        "elements": [{
          "id": "ccc01",
          "name": "name111",
          "price": "19",
          "qte": "12"
        }, {
          "id": "ccc02",
          "name": "name222",
          "price": "18",
          "qte": "17"
        }, {
          "id": "ccc03",
          "name": "name333",
          "price": "10",
          "qte": "5"
        }]
      }]

  $scope.extractSubsities = function(itemSelected) {
    if(itemSelected && itemSelected.elements){
        $scope.data = itemSelected.elements;
    }

  }

  $http.jsonp("http://total.smarteez.eu/submit/?station=101507")
  .then(function(data) {
      if($scope.cities && $scope.cities[0] && $scope.cities[0].elements && $scope.cities[0].elements[0]){
      $scope.cities[0].elements[0].price = data.data.prix.prix_diesel;
        $scope.cities[0].elements[0].qte = data.data.prix.prix_essence;
      }
    });

 }]);

I have set up a demonstration in Plunker:example

Note: total.smarteez.eu is not hosted on my server.

Can someone assist me in loading data from the URL JSON source?

UPDATE:

Upon running my code, I encountered an error that reads:

Uncaught SyntaxError: Unexpected token ?station=101507:1

EDIT:

This is not a duplicate query as I am specifically asking about extracting data from an external URL's JSON format, which may require cross-domain requests.

Answer №1

When attempting to retrieve information using angular services, the console in Chrome is displaying the following error:

XMLHttpRequest cannot load http://total.smarteez.eu/submit/?station=101507. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://<<MYIPADDRESS>>' is therefore not allowed access. The response had HTTP status code 401.

This indicates that the smarteez server does not allow CORS, meaning external connections cannot retrieve data.

If the smarteez server is not yours and you need a workaround, one suggestion could be to fetch the content into a PHP variable using the file_get_contents() function, convert it to JSON, and then return it to the angular controller.

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

Having trouble accessing a JSON object with Typescript in an Angular 2 project

Something strange is happening with my code. I am working with a JSON object: {"login":"admin","name":"Admin"} And this is the relevant part of my code: private _userData: User; ... private getUserData() { this._userInfoService.getUserInfo() ...

Guide to creating a type for a JSON object with nested properties in TypeScript

I have some JSON strings structured as follows: { name: 'test', url: 'http://test.org', contact: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0263636342766771762c616d6f" ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...

The collision function is currently not functioning properly, causing a hindrance in movement. There are no other codes restricting movement

const rightPressed = false; const leftPressed = false; const upPressed = false; const downPressed = false; const players = []; players[0] = new victim(1234); const arrayw = 50; const arrayh = 50; const canvas = document.getElementById("myCanvas"); const ...

Update information in a table row and store it in the database using Ajax

Looking for some guidance with ajax and javascript here. I'm not very proficient in this area, so any help would be greatly appreciated. I have a table on my page where data is displayed like this: <table class="table table-bordered"> ...

Retrieving information for Angular.js controller using resolve and $resource

I am attempting to retrieve a job by its Id from the API and then transfer it to the controller. .when('/jobs/edit/:id', { templateUrl: 'partials/jobs/edit', controller: 'JobCtrl', resolve: function($routeParams, ...

Using PHP in combination with Ajax for automatically performing an action when there is an update

My goal is to have the latest value entered in the database trigger the playing of a specific song. For instance, if someone on the other side of the world selects a song on their phone, that same song should automatically start playing on all devices with ...

Is it possible to implement H-Screen in Tailwind without causing the page size to expand? My website has a fixed navbar at the top, and I

My setup includes PanelMaster, along with Panel 1 and Panel 2 components. PanelMaster: flex Panel1: flex-col Panel2: flex-col I have a Navbar component at the top of the page with 'h-1/5' applied to it. However, I'm facing an issue where ...

Managing stream pauses and resumes in Node.js using setTimeout()

After some experimentation with Node.js (v4.4.7), I managed to create a simple program to play a sound... const Speaker = require('audio-speaker/stream'); const Generator = require('audio-generator/stream'); const speaker = new Speake ...

jQuery function duplicates row in table

I am trying to utilize jQuery to generate a table, but I seem to be encountering an issue with my code: function showGrid(url, container, columns, page) { jQuery(container).empty(); var tr = jQuery("<tr class=\"mobileGridHeader\"> ...

Error with Ant Design Autocomplete functionality when searching for a number

I am currently using ant design to develop a more advanced autocomplete component that will display data from multiple columns. In this particular scenario, I have two columns named tax_id and legal_name that users can search by. Everything works smoothly ...

Generate Pagination in JavaScript using an Array of Elements

Is there a way to implement a Pagination System using JavaScript? Specifically, I need to display 10 products per page. I currently have an Array containing various products and my goal is to iterate through these products to display the first 10 on one p ...

Animate CSS with Javascript in reverse direction

Forgive me if this is a silly question, but I'm having trouble. I need a slide-in navigation menu for smaller screens that is triggered by JavaScript. Here is what I currently have: HTML <nav class="responsive"> <ul class="nav-list unstyl ...

Solving Problems with Inline Tables using Angular, Express, and Mongoose's PUT Method

For the past few days, I've been struggling to figure out why my PUT request in my angular/node train schedule application isn't functioning properly. Everything else - GET, POST, DELETE - is working fine, and I can successfully update using Post ...

Hey there, I'm looking to use different CSS fonts on Windows and Mac for the same page on a web application. Can someone please guide me on how to accomplish this?

In order to tailor the font based on the operating system, the following criteria should be followed: For Windows: "Segoe UI" For Mac: "SF Pro" Attempts have been made using the code provided below, but it seems to load before the DOM and lacks persisten ...

Utilizing R and Weather Underground: Discovering the Nearest Airport Station Using Longitude and Latitude

Is there a way to locate the closest Airport station using longitude and latitude coordinates? Suppose I have this json data stored in my database: "location" : { "long" : "Devon, 8 Market Road, Plympton, Plymouth PL7 1QW, United Kingdom", "stre ...

What is the best way to pass a VueJS object to be stored in a Laravel controller?

I am facing an issue with my methods where the data is not getting stored in the database. I am unsure why the information is not being sent to the controller. Even though I input the correct data, it fails to load into the database. However, it does pass ...

Issue with converting valid JSON to XML using XSLT 3.0 json-to-xml() function

The following JSON appears to be valid, but when attempting to transform it using XSLT 3.0's json-to-xml() function, an error related to the JSON syntax is encountered. { "identifier": { "use": "<div xmlns=\"http://www ...

After the main page is loaded, the div will be dynamically populated with HTML content. How can we confirm that it has finished

I recently took over a project where a page loads and then code attached to that page populates a div with dynamically generated html – essentially filling an existing div with a string of html elements. Within this string are links to images, among oth ...

Anticipated the presence of a corresponding <div> within the server's HTML nested in another <div>

I've encountered a troubling error on my website while using Next.js. The error is causing layout issues and upon investigation, it seems that the device detection hook is at fault. Here's the hook in question: const isBrowser = typeof window !== ...