0

I'm answering a certain request to my Django server with a JSON object:

return HttpResponse(json.dumps(geojson), mimetype="application/json")

But I don't know how to get it at the HTML/javascript. I have gone through lots of similar questions and tutorials, but they all start defining an string variable with an example of JSON to use it. But I haven't been able to find how to get the JSON the server is answering me.

Any help or tutorial link?

EDIT: I tried using jQuery.ajax as suggested, but the function is never being executed:

Content of map-config.js:

var jsondata;
var lon = 5;
var lat = 40;
var zoom = 5;
var map, layer;

function init(){
    map = new OpenLayers.Map( 'map' );
    layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", 
            "http://vmap0.tiles.osgeo.org/wms/vmap0",
            {layers: 'basic'} );
    map.addLayer(layer);
    map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);

    var geojson_format = new OpenLayers.Format.GeoJSON();
    var vector_layer = new OpenLayers.Layer.Vector(); 
    map.addLayer(vector_layer);
    vector_layer.addFeatures(geojson_format.read(jsondata)); // Feeding with the json directly
}

$.ajax({
  url: "localhost:8000/form/",
  type: "POST",
  dataType: "json"
}).done(function (data) {
  $("#dialog").dialog('Hello POST!');
  console.log(data);
  jsondata = data; // Saving JSON at a variable so it can be used with the map
});

I also have another js file for a form, which works properly. And the HTML file is this one:

<html>
<head>  
    <script src="{{STATIC_URL}}js/jquery-1.9.1.js"></script>
    <script src="{{STATIC_URL}}js/jquery-ui-1.10.3.custom.js"></script>
    <script src="{{STATIC_URL}}js/OpenLayers.js"></script>
    <script src="{{STATIC_URL}}js/form.js"></script>
    <script src="{{STATIC_URL}}js/map-config.js"></script>
    <link rel="stylesheet" href="{{STATIC_URL}}css/jquery-ui-1.10.3.custom.css">
    <link rel="stylesheet" href="{{STATIC_URL}}css/style.css" type="text/css">
</head>

<body onload="init()">
    <div id="form" class="form-style">
        <p>Start Date: <input type="text" id="id_startDate"></p>
        <p>
            <label for="amount">Interval:</label>
            <input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
        </p>
        <p> <div id="id_interval"></div> </p>

        <p>
          <button id="id_okButton">OK</button>
        </p>
        </p>
    </div>

    <div id="map" class="smallmap">
</body>

So, when the POST request is received with the json coming from server, the jQuery.ajax method should execute, and the map should show some data (draw polygons over it to be exact). That POST is arraiving OK as stated at FireBug (the snapshot is not showing the whole json object, which is big):

JSON response snapshot at FireBug

Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207
  • possible duplicate of [Reading Server Side file with Javascript](http://stackoverflow.com/questions/3567369/reading-server-side-file-with-javascript) – Quentin Jun 06 '13 at 11:19
  • I don't think that question has anything to do with this one – Roman Rdgz Jun 07 '13 at 10:43
  • You have an HTTP resource. You want to read it with JavaScript. That question has everything to do with this one. – Quentin Jun 07 '13 at 10:51
  • No, I disagree, because it's talking about a csv which is an accesible static resource, meanwhile I'm dealing with a dynamic resource which comes into a POST request response. Accepted answer there has even nothing to do with porposed answers here. – Roman Rdgz Jun 07 '13 at 10:54
  • It's data available via a URL. That fact that it is dynamic instead of static is irrelevant (the client can't tell the difference). The fact that is is JSON instead of CSV isn't relevant (at least in so far as your question is expressed since you were only asking about getting the data, not parsing it). Until you edited the question a few minutes ago, there was no mention of it being POST. – Quentin Jun 07 '13 at 10:57
  • It is true that I didn't mention the POST, and that's my fault, once settled that, there do is a difference, otherwise it would be working now – Roman Rdgz Jun 07 '13 at 11:01

2 Answers2

1

Did you serialize your object to json format ?

    $.ajax({
        url: //your_url,
        type: "POST",
        success: function (data) {
              // write your parsing code..
            }
        },
        error: function (err) {

        }
    });

exp json from w3schools.com

{
"people": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

parsing exp (in jquery ajax success function ):

$.each(data.people, function (i, person) {
  console.log(person.firstName + " " + person.lastName)
});
erkan demir
  • 1,386
  • 4
  • 20
  • 38
  • Please use a comment for questions. – aggsol Jun 06 '13 at 11:23
  • I don't know if I need to: It is a geoJSON generated with django libraries, I guess it is already serialized, isn't it? Anyway that's not the problem I'm trying to solve now – Roman Rdgz Jun 06 '13 at 11:27
  • 1
    First write your request url to browser address bar to see json data. If it is ok you can use jquery ajax function for parsing json data. – erkan demir Jun 06 '13 at 11:40
  • @erkandemir how can I do that? – Roman Rdgz Jun 06 '13 at 13:43
  • @erkandemir Ok I think I understand the problem: this function SENDS a POST request to the server, and IF SUCCEEDS, then does something with the response data. But I already have the first part coverend in a different way. I just need to catch the response. Is there any function that executes whenever a post request is received without having to send anything before? – Roman Rdgz Jun 07 '13 at 12:25
0

You could use jQuery for the request on the browser side.

$.ajax({
  url: "example.com/data",
  dataType: "json"
}).done(function (data) {
  // data is the javascript object from the json response
});

Edit: Linked to the wrong jQuery call.

See details

aggsol
  • 2,343
  • 1
  • 32
  • 49
  • I've tried this using localhost:8000/form as my url and just using console.log(data), but nothing is being printed. Doesn't seem to work – Roman Rdgz Jun 06 '13 at 11:32
  • @Roman Rdgz: Does your browser show the JSON when you open `localhost:8000/form`? For suggest that the server expects a POST request, as the default method for `$.ajax` is GET. – aggsol Jun 06 '13 at 11:37
  • The server is receiving the POST for sure. And I can see the JSON response at firebug, so it arrives to the browser. But I see no way of accesing it. I'm afraid it has to be with the javascript mix I've got between the script brackets I'm afraid – Roman Rdgz Jun 06 '13 at 13:28
  • @Roman Rdgz: When setting a breakpoint into the done function, is done called? How does data look like? Is the HTTP status 200? – aggsol Jun 06 '13 at 13:33
  • I don't know how to set breakpoints when developing javascript. But I did put a console.log() entry at done function, and it is never printed. So it's not working at all – Roman Rdgz Jun 07 '13 at 10:43