I'm trying to log my users location using some Ajax code I was able to gather from online. I am trying to pass it to the backend code where I can store the data in my db for analytics. I have never used Ajax before and am not familiar with the syntax for passing through to backend.
Here's my code.
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function (location) {
$("#country").html(location.country_name);
$("#state").html(location.state);
$("#city").html(location.city);
}
});
I basically need to pass $('#country').html(location.country_name); $('#state').html(location.state); $('#city').html(location.city); to my nodejs code. I've used fetch before in js but not sure if thats the syntax to include the Ajax code in it. Appreciate the help.
If you have some data to be sent to the server using AJAX and if you have something like the HTML that you have got, you can very well use the textContent or .text() (using jQuery) of the element. Here's how you do it.
// Sending data to the server...
var data = {
country: $("#country").text(),
state: $("#state").text(),
city: $("#city").text()
};
console.log("Data to be sent!");
console.log(data);
console.log("Serialised data!");
console.log($.param(data));
// Send data to end point and get JSON value.
$.getJSON("/endpoint?" + $.param(data), function (res) {
console.log(res);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Country: <span id="country">India</span>
<div>State: <span id="state">Tamil Nadu</span>
<div>City: <span id="city">Chennai</span>
In the above example, the contents of the HTML will be sent to the server. Check out the console and network for what is been sent.
Here's from the Network tab of Google Chrome:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With