2

I have a .json file that I'm trying to import as a text string.

This is the exact file contents:

{ "type": "Polygon", "coordinates": [ [ [ 1.5887868, 50.8315241 ], [ 1.5830702, 50.8466931 ].......  ] ] ] }

I'm trying to import it using this:

jsonString = jQuery.get('./polygons/1.json', function(data) {    
  console.log(data);            
}); 

However, console.log(data) is coming across as an array, and I don't want it to - I just want the literal text string, just as it is in the file.

enter image description here

How do I accomplish this?

Update

So my entire code is:

jsonString = jQuery.get('./polygons/1.json', function(data) {    

  return JSON.stringify(data);

});

enter image description here

But now I get this screenshot below:

I guess it's the responseText that I'm trying to get out. Why is jQuery.get adding all this additional info into my file? What am I doing wrong?

Second Update

I always feel bad when someone takes their time to explain something to me, and I don't understand it. So, this whole thing exists so that I can pull dynamic data into jsonString, depending on what the user wants.

Right now though, I'm having to accomplish this feat by making individual files with the geodata coordinates, then utilizing it using map.data.loadGeoJson('./maps_polygons/' + territory + '.json');

function mapClick(data) {

territory = data; //the section of the map that the user clicks on, e.g. `california` or `texas`

var mapOpt = {
  center:new google.maps.LatLng(50.477971, 0.482999),  
  zoom:8,  
  };

map = new google.maps.Map(document.getElementById("googleMap"),mapOpt);

map.data.loadGeoJson('./maps_polygons/' + territory + '.json');


google.maps.event.addDomListener(window, 'load', initialize);

}

Now, this WORKS, but I felt that it must be incredibly inefficient, so I wanted to hold all of the coordinates in a single file, and bring them in dynamically as the main input from function mapClick(data) changed. This has GOT to be possible, and from what you've all shown me, I can write an ajax query, or use jQuery.get from within a function, and that will bring the json string in, but that does me no good, because it's stuck inside of that function and I can't get to it.

This is my frustration...

Final Update

Okay - shout-out to this page and this page, as well as @Lye-Fish for finally helping me understand how this all works.

In searching SO tonight, I found tons of posts about aspects of this topic, so I wanted to die it all in how I finally got these two things to work:

  1. The idea of getting something out of an ajax call (the original reason for my post)
  2. How to tie that back into the Google Maps API.

The HTML

<area shape="poly" coords="..." href="#" alt="california" onClick="mapClick(alt)"/>

The Javascript

function mapClick(data) {

territory = data;

function getPolygons(territory, passTodoWork) {
    jQuery.get('./maps_polygons/'+ territory +'.json', function(data, status, jqXHR) {    
        var coordinates = JSON.parse(jqXHR.responseText);
        passTodoWork(territory,coordinates);
    });
}
function drawMap(firstItem, secondItem) {
    var mapOpt = {
    center:new google.maps.LatLng(50.367247, 2.745326),  
    zoom:8,  
    };

  map = new google.maps.Map(document.getElementById("googleMap"),mapOpt);


  map.data.addGeoJson(secondItem);

  map.data.setStyle({  
    fillColor: '#2b86cc',
    strokeColor: '#1e5c8c'
  });


  google.maps.event.addDomListener(window, 'load', initialize);
}

getPolygons(territory, drawMap);

}

note, I don't utilize territory in the final drawMap function - that's part of another piece of code that made this all too long to prove the point...

1
  • console.log(JSON.stringify(data)) Commented Jun 27, 2015 at 21:20

3 Answers 3

5

First, and most importantly, your jsonString variable is not going to hold the response. It's going to hold the jqXHR object for the request, which will have the response eventually, but you need to access it inside the callback.

Second, using JSON.stringify is not a proper solution. It doesn't make sense to serialize data that's already available to you in its serialized form.

The jqXHR object holds the .responseText property that will give you the actual unparsed response body. You don't need to get it from that variable either. You can get it from the 3rd parameter to the callback.

jQuery.get('./polygons/1.json', function(data, status, jqXHR) {    
    console.log(jqXHR.responseText);
});

The return statement you had does nothing at all, so I dropped it. The jQuery.get does not block execution, which means you need to pick it up inside the callback.


If you truly don't want it parsed, then I'd recommend changing your response headers so that jQuery doesn't realize it's JSON data. I'm pretty sure that's why it's parsing it for you automatically.

If you change your header from this:

Content-Type: application/json

to this:

Content-Type: text/plain

It should work.


Or you could just make a jQuery.ajax request, and specify "dataType: text", and that may work too. The jQuery.get does give you another argument you can pass to override the guesswork, but it seems it's limited to xml, json, html or script.


To deal with the asynchronous nature of the code, you need to pick up the execution inside the callback. Since you probably don't want a whole bunch of application code in there, you can put it in a different function and invoke it, passing it the data.

jQuery.get('./polygons/1.json', function(data, status, jqXHR) {    
    console.log(jqXHR.responseText);
    // do some other stuff in here

    doWork(jqXHR.responseText);
});

function doWork(data) {
    console.log("Now we have it here: ", data);
}

If this same type of request will be made for different purposes, you can put it inside another function and pass a callback function to be invoked for the different situations.

function getPolygons(callback) {
    jQuery.get('./polygons/1.json', function(data, status, jqXHR) {    
        console.log(jqXHR.responseText);
        // do some other stuff in here

        callback(jqXHR.responseText);
    });
}

function doWork(data) {
    console.log("Now we have it here: ", data);
}

function doOtherWork(data) {
    console.log("And now it's here: ", data);
}

getPolygons(doWork);

// ...some other part of the app...

getPolygons(doOtherWork);

If you're having trouble still with jQuery doing stuff you don't want, just make the XHR request yourself.

function getPolygons(callback) {
    var xhr = new XMLHttpRequest()
    xhr.open("GET", "./polygons/1.json", true);
    xhr.onreadystatechange = function() {
        if (this.readyState === 4) {
            console.log(this.responseText);
        // do some other stuff in here

            callback(this.responseText);
        }
    };
    xhr.send(null);
}

You can also check the this.status in the callback for HTTP response codes if they're meaningful to you. FYI, this is the same object held by the xhr variable.

Sign up to request clarification or add additional context in comments.

9 Comments

First off - I really appreciate you taking the time to explain this to me. My issue here is that I'm trying to get this .json file and assign it to the jsonString variable, so I have jsonString = jQuery.get..... But it's still returning the entire thing, and not jqXHR.responseText because that's happening inside the function. How do I get jqXHR.responseText to be applied to my actual variable that I can then use OUTSIDE of the function?
That's fine - I can change it to an ajax request, but I still don't get how to access it outside of the ajax success call then...
@JohnWu: You can't. This is the nature of asynchronous programming. Your flow of execution continues inside the callback.
You could put the rest of the code inside another function and invoke it from inside the callback if you wish. That way you can separate the code logically. I'll update with a couple examples.
@JohnWu: Frankly, you don't need jQuery to make these requests. It's simple to just do it yourself and you're not stuck with their API trying to do things you don't want. I'll give another update that shows how.
|
5

Use JSON.stringify like so

console.log(JSON.stringify(data));

3 Comments

@JohnWu: You shouldn't stringify it. Just change the response headers so you're sending text/plain. Guessing right now you're sending Content-Type: application/json. This just doubles the work being done.
@JohnWu: Or if you can't change the headers, get the .responseText property from the XHR object. Should be available on the object passed as the 3rd parameter to the callback.
Lye - I updated my original question before I read your response... crazy. How do I get responseText out of what jQuery.get returns?
1

I think that you can use $.ajax as .get is using that under,, and define the dataType like this,, so no double parsings..

$.ajax({
  url: './polygons/1.json',
  method: "POST",
  dataType: "text"
});

1 Comment

api.jquery.com/jquery.ajax says I should be able to use dataType: "text" but it's still coming back as the exact same parsed json....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.