passing ajax data to backend javascript - javascript

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:

To anyone who else who is looking at this question, you may also use javascript within the Ajax function. It may not be the proper way, but it does work.
<script>
$.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);
console.log(location)
var locaionValues = location;
var countryNameLocation = location.country_name;
var stateNameLocation = location.state;
var cityNameLocation = location.city;
fetch('/locationTracker', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
locaionValues,
countryNameLocation,
stateNameLocation,
cityNameLocation,
})
})
}
});
this works great, and in my nodejs code, I am logging the code like so:
app.post('/locationTracker', (req, res) => {
var country = req.body.countryNameLocation
var state = req.body.stateNameLocation
var city = req.body.cityNameLocation
console.log("country is " + country)
console.log("state is " + state)
console.log("city is " + city)

Related

Issues with make jQuery ajax call to a rest api

I am trying to use jquery ajax to make a post request that returns some response but it does not seem to work properly. Sometimes it works after a long wait, other times it does not work at all.This is my code.
<script type="text/javascript">
const id = $('#auth').val();
$("#set").click(function(){
$('.spinner-grow').show();
$.post("https://ravesandboxapi.flutterwave.com/v2/gpx/transactions/escrow/settle",
{
id: id,
secret_key: "FLWSECK-25*******************0628-X"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
$('.spinner-grow').hide();
});
});
</script>
what might be the issue here?
The following is a complete example of a AJAX post is handled via jQuery. Just sharing it for reference.
var url = "api/path/to/your/controller";
var data = {};
data.id = id;
data.secret = 'your-secret';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (resultObject) {
console.log(resultObject);
},
error: function (err) {
console.log('An error occured');
}
});
If you are getting a 404 error, better check the path to the API. You can use a tool like Postman to validate your requests and then try implementing the same in code.
Also make sure that there is no CORS issue as from your code we cannot understand if your post is triggered from the same domain.

OpenWeatherMap Starting

I have just created an account with OpenWeatherMap
I want to get the current weather for location by City ID API Call:
http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey
On my html page, how do I go about using this so that I can show my users what the weather is for the specific location?
I have used Yahoo Weather API, but want to try something different. Is the process similar? I don't see where I would call a callbackfunction like in yahoo weather api.
Do I have to write something like this?
<script src="http://api.openweathermap.org/data/2.5/weather?id=2172797&mode=html&appid=myapikey"></script>
I have tried this and it is not working.. and I couldn't find any examples on the website on how to integrate this into my html page.
Any help is appreciated.
UPDATE:
I have tried:
<img id="Weather-Image" src="http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myapikey" />
This uploads a black x.. not the picture of the current weather.
UPDATE:
I have found that I need to use ajax.. here is what I have so far:
<script>
$(document).ready(function () {
var request = $.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
method: "GET",
data: { id: '2172797', appid: 'myapikey' },
success: function (response) {
var dataArray = JSON.parse(response);
var weatherIcon = dataArray.weather.icon;
var iconUrl = "http://openweathermap.org/img/w/" + weatherIcon + ".png";
document.getElementById('Weather-Image').src = iconUrl;
}
});
});
</script>
The data returned from http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey is described in the documentation of OpenWeatherMap.
You can't use it directly in a <script> or <img> tag as the response is JSON.
If you must use JavaScript to fetch the weather data, you will need AJAX (or any AJAX wrapper like $.ajax from jQuery) to call the API url then use JSON.parse to create an array with all the given data.
This is how it could look like:
var request = $.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
method: "GET",
data: { id : '2172797', appid: 'myAPIKey'},
success: function(response) {
// response from OpenWeatherMap
var dataArray = JSON.parse(response); // create an array from JSON element
}
});

Ajax jquery making web api call

I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.

Can't read JSON data correctly by $.each jquery

I am trying to use $.getJSON to get data from the NHTSA recall API and append the Component object from the Results array to a div with the id="data". Here is the URL I am trying to get JSON for:
http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json
Here is the snippet that I am using:
`var url = 'http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json';
$.getJSON( url, function(data) {
console.log(data.Results);
$.each(data.Results, function(i,Results){
var component = this.Component;
$('#data').append('<h4>' +component+ '</h4>');
}
}
I have used this similar format for a few other API's and it worked so I am not sure why the call isn't going through.
I ran into a cross origin request problem using $.getJSON (as I often do), so I tried jsonp and succeeded. Please give it a try and let me know if you have questions.
$(document).ready(function() {
var http = 'http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json';
$.ajax({
url: http,
dataType: 'jsonp',
jsonpCallback: "callback",
type: "GET",
success: function (data) {
var div = $('#data');
for(var i = 0; i < data.Results.length; i++) {
$(div).append('<div>' + data.Results[i].Component + '</div>');
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>

Javascript pull search completion from web service

I'm a bit new to Javascript and I want to do something I feel like should be pretty simple. I have a web completion service built and I just need to get those completions into the page. I basically want something like this:
<script>
function(search_string){
http.request('www.fake.com/search_complete/' + search_string, function(response) {
response = JSON.parse(response);
//do something with parsed data
});
}
</script>
<input type="search" placeholder="Search..." />
Are you just trying to make a request and use the data returned? If so, just make an ajax request and update the html with the data you get back
var request = new XMLHttpRequest();
request.open('POST','http://www.fake.com/whatever.php?val1='+search_string,true);
request.send();
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status=200){
//The request has been completed, handle the data
var data = JSON.parse(request.responseText);
}
}
This must help. Example integration of jQuery UI autocomplete from remote web service.
http://salman-w.blogspot.in/2013/12/jquery-ui-autocomplete-examples.html
Use jquery:
$.ajax({type: "GET", dataType: 'json', contentType: "application/json", url: "yoururl", success: function (data) {
//data is a javascript object that contains the data returned by your webservice json
}, error: function(xhr, status, error) {
// Display a generic error for now.
alert("Error: " + xhr + " " + status + " " + error);
}});
This code will make a call to a webservice using ajax and javascript. It will return the data from the webservice in the data object.

Categories

Resources