Reputation: 2711
I use a free api in order to gather informationfrom the users Ip-adress.
This is the method:
public JsonResult GetIp()
{
string url = "http://ip-api.com/json";
dynamic googleResults = new Uri(url).GetDynamicJsonObject();
return Json(googleResults, JsonRequestBehavior.AllowGet);
}
The method is supposed to get called when the page is rendered so I am thinking something like this:
$(document).ready(function () {
$.ajax({
type: "POST",
url: '@Url.Action("GetIp", "Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
//Here i need code that receives the Json from the controller...
});
});
Also, is this the best way to go about a task like this? I've been reading that Json could also be passed as a simple string? Any tips on best practice appreciated. Thanks.
Upvotes: 0
Views: 47
Reputation: 7067
You won't be getting the client ip this way, you'll get the server ip, because that's the machine making the call.
What you want is to make that call directly, in javascript, so the request ip is the client's.
If you look at the response headers from that api, Access-Control-Allow-Origin = *, so you should be able to use that url directly.
And as Amin mentioned, just add a success method to handle the response, like this:
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://ip-api.com/json',
dataType: "json",
success: function(resp){
//resp.query
}
});
});
Upvotes: 1
Reputation: 7207
$(document).ready(function () {
$(window).load(function(){
$.ajax({
type: "POST",
url: '@Url.Action("GetIp", "Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(resp){
//resp is the returned json variable from the server side
//you can use it like "resp.id" or "resp.anyOtherValue"
}
});
});
});
Upvotes: 2