Unable to access attributes of the object

I'm facing an issue with my ajax call, which fetches a PHP file generating JSON output like this:

{
    "Pittsburg\/Bay Point - SFIA\/Millbrae": ["PITT", "NCON", "CONC", "PHIL", "WCRK", "LAFY", "ORIN", "ROCK", "MCAR", "19TH", "12TH", "WOAK", "EMBR", "MONT", "POWL", "CIVC", "16TH", "24TH", "GLEN", "BALB", "DALY", "COLM", "SSAN", "SBRN", "SFIA", "MLBR"],
    "Millbrae\/SFIA - Pittsburg\/Bay Point": ["MLBR", "SFIA", "SBRN", "SSAN", "COLM", "DALY", "BALB", "GLEN", "24TH", "16TH", "CIVC", "POWL", "MONT", "EMBR", "WOAK", "12TH", "19TH", "MCAR", "ROCK", "ORIN", "LAFY", "WCRK", "PHIL", "CONC", "NCON", "PITT"]
}

Subsequently, I am executing the following JavaScript code to process it:

    $.ajax({
    url: "build-routes.php",
    dataType: 'json',
    success: function(routesAndStations){

      var i;
      for (var name in routesAndStations){ // this gets the route names
        routes[name] = new array();
        i = 0;

        // this gets all the stations for each route
        for(var station in routesAndStations[name]){ 
            routes.name[i] = routesAndStations[name][station];
            alert(routes.name[i]);
            ++i;
        }
      }

      for(var name in routes){
        var str = "";
        str += name + ": "+routes.name[1];
        alert(str);
      }

    },
    error: function(){
      alert("fail");
    }
  });

The problem lies in the fact that both alert functions inside the success function are not displaying. There seems to be some mistake in setting up the JavaScript object 'routes', which also contains an array.

Answer №1

In my local setup, I have the ability to interpret and exhibit station names in the following manner:

var routesAndStations = {"Pittsburg\/Bay Point - SFIA\/Millbrae":["PITT","NCON","CONC","PHIL","WCRK","LAFY","ORIN","ROCK","MCAR","19TH","12TH","WOAK","EMBR","MONT","POWL","CIVC","16TH","24TH","GLEN","BALB","DALY","COLM","SSAN","SBRN","SFIA","MLBR"],"Millbrae\/SFIA - Pittsburg\/Bay Point":["MLBR","SFIA","SBRN","SSAN","COLM","DALY","BALB","GLEN","24TH","16TH","CIVC","POWL","MONT","EMBR","WOAK","12TH","19TH","MCAR","ROCK","ORIN","LAFY","WCRK","PHIL","CONC","NCON","PITT"]};

for(name in routesAndStations)
{
    for(var i=0;i<routesAndStations[name].length;i++)
    {
        var station = routesAndStations[name][i];
        alert(station);
    }
}

However, as Mangiucugna pointed out, it's important to check if your ajax call is visible in the console log.

Answer №2

Hopefully this meets your requirements

    $.ajax({
    url: "build-routes.php",
    dataType: 'json',
    success: function(routesAndStations){

      var i;
      for ( var name in routesAndStations){
    // This section retrieves the route names
       var routes = new Array();
       routes.push(name);
        routes[name] = new Array();
        i = 0;

        // This part gathers all the stations for each route
        for(var station in routesAndStations[name]){

            routes[name][i] = routesAndStations[name][station];
            alert(routes[name][i]);
            ++i;
        }
      }

     for(var name in routes){
        var str = "";
        str += name + ": "+routes[name][1];
        alert(str);
      }

    },
    error: function(){
      alert("fail");
    }
  });

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

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...

Send a variety of variables through AJAX when the select element changes

I came across this script on W3schools.com (Ajax, PHP and Mysql) http://www.w3schools.com/php/php_ajax_database.asp <html> <head> <script type="text/javascript"> function showUser(str) { if (str=="") { document.getElementById("txtHin ...

MAMP experiencing internal server error when calling PHP function using jQuery ajax

My apologies if this question seems repetitive or redundant, but I have been searching through numerous queries regarding calling a PHP function via ajax, yet I am unable to make it work. I am working with MAMP and below is a snippet of my code: index.htm ...

Node.js is being utilized to send an abundance of requests to the server

Here is my setup: var tempServer=require("./myHttp"); tempServer.startServer(8008,{'/fun1':fun1 , '/fun2': fun2 , '/fun3':fun3 , '/fun4':fun4},"www"); This code creates a server on localhost:8008. If I enter th ...

Creating data structures for visualizing in vis.js (Converting PHP to JavaScript)

Attempting to transfer information from a GraphDB (Neo4J) using PHP to interact with JavaScript and display the data with vis.js. Here's my progress so far: Retrieving data from Neo4J and storing it in a PHP array: Array ( [0] => Arra ...

Tips for Guaranteeing a Distinct Email and Username are Stored in MongoDB with Mongoose

db.UserSchema = new db.Schema({ user: {type:String, unique:true, required:true,index:true}, email: {type:String, unique:true, required:true,index:true}, password: {type:String, required:true}, phon ...

Guide to managing .glb model animations in A-FRAME using Three.js

Can someone assist me with playing a glb animation in A-FRAME using Three.js? The animation works for a second and then stops. Here is my current code: <script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script> <scrip ...

Choosing the number of items for each cartItem in KnockoutJS: A comprehensive guide

Greetings! I am new to using knockout and I am attempting to automatically select the quantity for each item in my cart from a dropdown menu. Below is the code I have written: VIEW <div data-bind="foreach: cartItems"> <h3 data-bind="text: ful ...

The Cascade of Ajax Dropdown Menus

I am currently working on implementing a cascading dropdown list using ajax. The idea is that when a user selects a degree from the first dropdown, the second dropdown should populate with schools offering that particular degree. However, I'm facing a ...

Trigger the underlining effect to appear beneath the link when it is hovered

I need assistance in creating an effect where a line shoots across below a link when hovered over and disappears when the mouse is not hovering. I hope my description makes sense, please let me know if it doesn't. I suspect that using an actual underl ...

Having trouble with charts not appearing on your Django website?

I am working on a Django project where I need to integrate bar-charts using Django-nvd3. Although I have successfully displayed the bar-charts in separate projects, I am facing an issue with integrating them into my current project. Below is the code snipp ...

Best practice for filling an array using a promise

I am completely new to the world of modern JavaScript. My goal is to fill an array with data that I receive from a promise in a helperService. export class PeopleTableComponent implements OnInit { people: Array < Person > = []; constructor( ...

Radio button triggers an ajax call once, but then fails to function

How can I troubleshoot an issue where the ajax function only works once when clicking on a radio button to change its value from 0 to 1, but not back to 0? The form contains a table with radio buttons for each record, and clicking on them triggers the aj ...

Tips for inserting a component into a div selector using Angular 2

Could someone please help me figure out how to inject a component into a div selector using a class or id? I'm familiar with injecting components into other components, but not sure how to do it specifically within a div. Any guidance would be greatly ...

Instant urban locator

Is there a way to automatically populate the visitor's city in the membership form? Member Register Form Name: Emre Email:--- Pass:--- City: Istanbul // Automatically detected location How can I implement automatic location detection for the ...

How to set a cookie within an iframe while using Safari browser

Despite searching extensively on Stackoverflow and various other sources, I have not been able to find a solution that works for my specific case. The scenario is as follows: we have an application on domain A that we do not have control over, and an appl ...

How can I prevent the same function from being triggered in an AJAX call and a .scroll event when I click on another div with an onclick attribute

I have encountered an issue with my code where two div tags each contain a different onclick function call. The problem arises when I click on one of them and then proceed to click on the other - the .scroll(function() seems to be triggered by both functio ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

Sails.js navigating through sessions

What is a rolling session in Sails.js? A rolling session is a session that expires after a set amount of time without user activity, except for websockets live updating data. If the user navigates to a different part of the site before the session expires, ...