I am having a problem of getting values from my JSONP string which I am getting via AJAX request which looks like:
result({"respond":1,"paging":{"stillmore":0,"perpage":10,"callpage":1,"next":2,"previous":0,"pages":1,"result":"4"},"message":"","result":[{"ID":"1","user_email":"[email protected]","custom_fields":{"user_longitue":"51.5081","user_latitude":"0.0878"}},{"ID":"2","user_email":"[email protected]","custom_fields":{"user_longitue":"51.9081","user_latitude":"0.2878"}},{"ID":"3","user_email":"[email protected]","custom_fields":{"user_longitue":"51.6081","user_latitude":"0.1878"}}]})
My javascript should take values of user_latitude and user_longitue but for some reasons cannot make it.
var myData = JSON.parse(jsonString);
$(document).ready(function () {
var distanceObj = [],
i = 0;
$.each(myData.result, function (a, b) {
distanceObj[i] = { distance: hesapla(51.41140000, -0.22600000, b.custom_fields.user_longitude, b.custom_fields.user_latitude), location: a };
++i;
});
distanceObj.sort(function(a,b) {
return parseInt(a.distance) - parseInt(b.distance)
});
$.each(distanceObj, function(a, b) {
$('#groups').append('<li>' + b.location + ': ' + b.distance + 'm</li>');
});
console.log(distanceObj);
function hesapla(meineLongitude, meineLatitude, long1, lat1) {
erdRadius = 6371;
meineLongitude = meineLongitude * (Math.PI / 180);
meineLatitude = meineLatitude * (Math.PI / 180);
long1 = long1 * (Math.PI / 180);
lat1 = lat1 * (Math.PI / 180);
x0 = meineLongitude * erdRadius * Math.cos(meineLatitude);
y0 = meineLatitude * erdRadius;
x1 = long1 * erdRadius * Math.cos(lat1);
y1 = lat1 * erdRadius;
dx = x0 - x1;
dy = y0 - y1;
d = Math.sqrt((dx * dx) + (dy * dy));
return Math.round(d * 1000);
};
});
Please help me with my JSFIDDLE here:
EDIT: Here is the code of the AJAX call:
$.ajax({
url: 'mydomain.com/api',
async: false,
jsonpCallback: 'callback',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
timeout: 2000,
success: function (data, response) {
if (response === 'success') {
if (data !== undefined && data.result !== undefined) {
$.each(data.result, function (i, item) {
})
}
}
}
});
json.parsethat...dataType: 'jsonp'or something. jQuery will handle all the "parsing" for you, you just need to tell it how to.