0

I am pulling marker objects off of database using the folowing standard XHR request

  //retrieve markerData from JSON                                                     
    function retrieveMarkers(){                                                       
      var markersXMLhttp = new XMLHttpRequest();                                      
  //open the request and store parameters for the request.  GET (or POST) is method to send,
  //the pathway or url of the data is specified, and whether or not the request is asynchronous
      markersXMLhttp.open("GET", "../../map/json/myMapMarker.json", false);           
  //send the request                                                                  
      markersXMLhttp.send();                                                          
  //there conditions allow the request to wait until the server respondes that it is ready.
      if(markersXMLhttp.readyState == 4 && markersXMLhttp.status == 200){             
    //the response is stored in a variable                                            
        var XMLmarkersResult = markersXMLhttp.responseText;                           
      }                                                                               
  //convert JSON string to javascript object                                          
      var markersResult = JSON.parse(XMLmarkersResult);                               
      return markersResult;                                                           
    }                     

I have Asynchronous set to false and so I get the following error

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.

I agree Mozilla! So lets change my Asynch to true. O snap, now I get this error.

  SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

What the hell is going on, my JSON file isnt any different. Does asynchronous handle json differently? Id love to resolve this to the point where I am not getting any errors on my request. Following I will post a sample of my JSON code in case the problem lies there.

  {                                                                                         
    "myMarkers" : [                                                                         
      {                                                                                     
        "index" : "000",                                                                     
        "position" : {                                                                      
          "lat" : 45.5,                                                                     
          "lng" : -122.61                                                                   
        },                                                                                  
        "description" : "Portland OR",                                                      
        "infoWindow" : "The origin of the journey, where my roots are, and were many great people live"
      },                                                                                    
      {                                                                                     
        "index" : "001",                                                                    
        "position" : {                                                                      
          "lat" : 44.5,                                                                     
          "lng" : -121.61                                                                   
        },                                                                                  
         "description" : "A New Place",                                                      
        "infoWindow" : "The duplicat will carry for the replicons... until the safe find the fires of the fury"
      }                                                                                     
    ]                                                                                       
  } 
Ry-
  • 218,210
  • 55
  • 464
  • 476
DMrFrost
  • 903
  • 2
  • 13
  • 33

2 Answers2

1

Asynchronous means that the request happens in the background while your code continues to run. You would use a callback with onreadystatechange to wait to be notified that the request is complete so you can process the response.

markersXMLhttp.onreadystatechange = function() {
    // Check the readyState and status in here, then process the
    // response if they're 4 and 200 respectively

};

https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

Your code contains the following comment (which I've edited slightly):

// these conditions allow the request to wait

That isn't true, they don't cause any waiting to happen. They simply check the values and then continue. The callback itself is called whenever something changes, which doesn't necessarily mean that it is finished. Inside the callback those conditions are used to check whether the request has completed successfully.

skirtle
  • 27,868
  • 4
  • 42
  • 57
  • Thanks for the explanation with the answer. Im trying to understand the mechanics and reasoning behind the code, and this definitely helped me see what is happening. – DMrFrost Sep 13 '17 at 01:48
1

When using an asynchronous request your script continues to execute whilst the request is happening. So your, simply, your JSON has not been returned by the time you try to run JSON.parse() on it.

In order to handle this. You must define a call back method and assign it to the 'onload' property of the XMLHttpRequest...

function retrieveMarkers(callbackFunction){
  var markersXMLhttp = new XMLHttpRequest();

  // This gets called once the request is complete.
  markersXMLhttp.onload = function() {
    if(markersXMLhttp.readyState == 4){
      // Parse the JSON and call the function passed in as a parameter.
      callbackFunction(JSON.parse(markersXMLhttp.responseText));
    }
  };

  markersXMLhttp.open("GET", "../../map/json/myMapMarker.json", false);
  markersXMLhttp.send();
}

// Elsewhere in your code call your method and pass in a function....
retrieveMarkers((markers) => {
  // Do some work with your markers here...
  console.log(markers);
});

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

If this is the first time you are using async requests, call backs and the like than this may be a little bit 'mind boggling' at first. I suggest you read around on the topic and look at a good number of examples.

You will need to fundamentally adjust your thinking / design to the fact that your code is no longer running 'top to bottom'.

TSR
  • 141
  • 7