RDX RDX - 3 months ago 16
Ajax Question

Sending JSON having dynamic values in POST body request

New to Javascript and had a basic query

For a POST AJAX request , I need to send following data in JSON format in the body parameter, however the longitude, latitude and radius values are dynamic, i.e. will be fed based on current location.

{
"inGeoFence" : {
"gpsCircle" : {
"longitude": 122.2620,
"latitude": 37.4996,
"radius": 180000
}
}
}


The static way to write this is

"data": "{\r\n \"inGeoFence\" : {\r\n \"gpsCircle\" : {\r\n \"longitude\": 77.348235,\r\n \"latitude\": 28.533938,\r\n \"radius\": 100\r\n }\r\n }\r\n}\r\n"


Above data works fine since all are static values and a string is formed.

Can you please suggest me to write the same JSON so that dynamic values can be fed. Also what is the best/proper way to send JSON?

Thanks

Answer

Just construct JS object and that stringify it:

"data": JSON.stringify({
    inGeoFence: {
        gpsCircle: {
            longitude: getLong(),
            latitude: getLat(),
            radius: getRadius()
        }
    }
});

You can also send data as JS object and in server side read it as array:

$.ajax({
     data: {
      inGeoFence: {
        gpsCircle: {
          longitude: $('#long').val(),
          latitude: $('#lat').val(),
          radius: $('#radius').val()
        }
      }
    }
});

[server side, e.g. PHP]
$_POST['inGeoFence']['gpsCircle']['longitude']