I don't get why my API Request is not working - javascript

I'm working on a weather app, on top of having the option to get his geolocation the user can also input a city to get the weather info.
I've been stuck for a while, I'm trying to get the info of the weather using the input of the user, using my api request(which is working on codepen // I'm working on VSCode). Im using the same url of my geoLocation but changing it to taking the city instead of the lon and lat as input, but I always get a ERROr 400, but I can't seem to locate the source of my error.
// Get weather from input
function getVal() {
var val = document.querySelector('#search-city').value;
const url = 'https://api.openweathermap.org/data/2.5/weather?q=' + val + '&appid={API key}&units=metric';
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: (data) => {
$('#city').text(data.name)
$('#condition').text(data.weather[0].main);
$('h1').text(Math.round(data.main.temp));
backgroundChange(data.weather[0].main);
},
error: () => {
return false
}
});
};
// Get weather using location
function geoLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
let lat = position.coords.latitude;
let long = position.coords.longitude;
let url = 'https://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + long + '&appid={API Key}&units=metric';
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: (data) => {
$('#city').text(data.name)
$('#condition').text(data.weather[0].main);
$('h1').text(Math.round(data.main.temp));
backgroundChange(data.weather[0].main);
},
error: () => {
return false
}
});
})
};
});
I would really appreciate your help !
Thank you very much!!
// RESOLVED
At first I created the function outside of my onlick event and the API Call was made even before the event was called, so I think the input couldn't make it's way to the URL.
Here is the modify version which is now working :
$('.search-icon').click(
function getVal() {
var city = document.querySelector('#search-city').value;
const url = 'https://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=dc8c9152e8adaad0ec8bf635818c0d42&units=metric';
$.ajax({
url: url,
type: "GET",
dataType: 'json',
success: (data) => {
$('#city').text(data.name)
$('#condition').text(data.weather[0].main);
$('h1').text(Math.round(data.main.temp));
backgroundChange(data.weather[0].main);
},
error: () => {
return false
}
});
});

I believe in this part of API's url "ppid={API Key}" you are passing as a string. You should inform your API key in order to fetch the data.

Thanks for your responses but I found the solution ! Instead of creating an event using the function, I put the function in the event.

Related

Trouble replacing handlebars variable with input from API

I'm attempting to create a simple weather API that replaces handlebars placeholder variables with user input of a city name linked to an api. It works very strangely, it will display the correct data after the next input is submitted. I.E. I submit "Dayton" and the placeholder data shows up again, then I submit "New York" and Dayton's correct info pops up. If I were to submit a third city, New York would display. Any ideas on why? Here's my code:
var currentWeather = {
cityName: "London",
temperature: 86,
description: 'cloudy'
};
var addCurrentWeather = function(data) {
var weather = {
cityName: data.name,
temperature: data.main.temp,
description: data.weather[0].main
}
};
var renderCurrentWeather = function () {
var weather= currentWeather;
var source = $('#weather-template').html();
var template = Handlebars.compile(source)
var weatherHTML = template(currentWeather);
$('#city').append(weatherHTML);
};
// fetch applying user input to grab data from api
var fetchCurrentWeather = function (query) {
$.ajax({
method: "GET",
url: "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&APPID=MYKEY",
dataType: "json",
success: function (data) {
addCurrentWeather(data);
renderCurrentWeather();
currentWeather = {
cityName: data.name,
temperature: data.main.temp,
description: data.weather[0].main
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
};
$('#search').on('click', function () {
var search = $('#search-query').val();
console.log(search);
fetchCurrentWeather(search);
});
renderCurrentWeather();
I will assume that you expect from your code to do following in the success handler.
Update your global weather object
Use that global object to render your template
That does not happen because your function addCurrentWeather does essentially nothing as it updates a local variable and discards it.
So make sure that this function instead updates the global variable.
var addCurrentWeather = function(data) {
currentWeather = {
cityName: data.name,
temperature: data.main.temp,
description: data.weather[0].main
}
};
and in the success handler you should have then only
addCurrentWeather(data);
renderCurrentWeather();
Reason why it then currently works the way it does is because after you call the render function you later update the global variable directly hence why this data is then used on next api fetch.
As a suggestion, try to avoid using global variables as it is easy to create bugs like this. Instead try to use pure functions as it will also help if you start unit test your code.
In your case have addCurrentWeather function accept data and return a weather object. And similarly have the render method accept weather object instead of reading it from global var.
Something like this
function getCurrentWeather(data) {
return {
cityName: data.name,
temperature: data.main.temp,
description: data.weather[0].main
}
};
function renderCurrentWeather(weather) {
var source = $('#weather-template').html();
var template = Handlebars.compile(source)
var weatherHTML = template(currentWeather);
$('#city').append(weatherHTML);
};
function fetchCurrentWeather(query) {
$.ajax({
method: "GET",
url: "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&APPID=MYKEY",
dataType: "json",
success: function (data) {
const weather = getCurrentWeather(data);
renderCurrentWeather(weather);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
};
$('#search').on('click', function () {
var search = $('#search-query').val();
console.log(search);
fetchCurrentWeather(search);
});
fetchCurrentWeather('London');

Failed to load resource: the server responded with a status of 500 using Ajax

I know this question has been asked previously, but I cannot find out what is the exact problem with my code.
function viewcalldetails(obj) {
alert("clicked");
var id = $(obj).attr("id");
$(".style-table-tab input[type='text']").val('');
setTimeout(function () {
$('.preloader-circle').show();// or fade, css display however you'd like.
}, 1000);
$.ajax({
type: 'POST',
url: pageUrl+"/LoadCallDetails",
data: '{LeadID: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: OnValuecall,
failure: function (response) {
alert(response.d);
}
});
}
function OnValuecall(response) {
$(".preloader-circle").hide();
$("#ctl00_ContentPlaceHolder1_lbrfullname").text(response.d.FirstName);
$("#ctl00_ContentPlaceHolder1_lbrphonenumber").text(response.d.MobileNo);
$("#ctl00_ContentPlaceHolder1_lbraddress").text(response.d.Address1);
$("#ctl00_ContentPlaceHolder1_lbrorganization").text(response.d.OrganizationName);
$("#ctl00_ContentPlaceHolder1_lblremail").text(response.d.PrimaryEmail);
}
Web Method:
public static UserAjax3 LoadCallDetails(string LeadID)
{
//System.Threading.Thread.Sleep(3000);
UserAjax3 oUserAjax = new UserAjax3();
//BD_CommonEmail[] ocall = BD_CommonEmail.GetEmailAll(Convert.ToInt32(LeadID)).ToArray();
BD_Leads[] ocall = BD_Leads.getCallDetails(Convert.ToInt32(LeadID)).ToArray();
if (ocall.Length == 1)
{
// oUserAjax.LeadID = oLeads.LeadID.ToString();
oUserAjax.LeadID = ocall[0].LeadID.ToString();
oUserAjax.FirstName = ocall[0].FirstName;
oUserAjax.MobileNo = ocall[0].MobileNo;
oUserAjax.OrganizationName = ocall[0].OrganizationName;
oUserAjax.Address1 = ocall[0].Address1;
oUserAjax.PrimaryEmail = ocall[0].PrimaryEmail;
}
return oUserAjax;
There are many things in question:
Where does "pageUrl" comes from?
You're awaiting a JSON result, but your method seems to return a normal object. Where do you convert to JSON?
Did you try running with a debugger in single-step mode trhough your web method?
Why is your web method static?

Send form data to client side function to retrieve a page title

I'm attempting to pull the title from the metadata of a URL on the client side so it appears in real time (much like pasting a link on FB / Twitter). However I am struggling to load the url from an input and send the data to a function to make it read on console.log without having to submit the form yet.
Jade
form(method='post' action='/submit', class='plans', id='plans')
.form-group
label Do you have a link?
input.form-control(name='link', type='url', required='required', onchange='scrapeMetadata();', onkeyup='this.onchange();', onpaste='this.onchange();', oninput='this.onchange();')
JS
function scrapeMetadata(link) {
var url = link;
console.log(url)
};
Server-side, have the browser send the url via ajax and display that.
Like in this fiddle: https://jsfiddle.net/mo0qa8yk
function getTitle(url) {
try {
return new window.URL(url).host;
} catch(ex) {
console.error(ex);
return 'N/A';
}
}
window.scrapeMetadata = function () {
var url = $('#url').val();
$.ajax({
type: 'GET',
url: '//jsfiddle.net/echo/jsonp/',
data: {
url: url,
title: getTitle(url) //cheat , the server sould return {title:'...'}
},
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: show_response,
error: function(e) {
console.error(e.message);
}
});
};
show_response = function(obj) {
var result = $('#post');
result.html("");
result.append('<li>' + obj.title + '</li>')
};

jQuery autocomplete using data pulled from SharePoint list using ajax REST

I need to add autocomplete to an input textbox. The data needs to be fetched from SharePoint using AJAX / REST.
This what I've done so far:
JS
var myData = [];
var requestHeaders = {
"accept": "application/json;odata=verbose"
}
$.ajax({
url: "https://my-URL/sites/RMA-GFPLC/_api/web/lists/GetByTitle('AD_DB')/items? $select=Title,Regional_x0020_Office,Commodity,Commodity_x0020_Year,StateLookUp/Title&$expand=StateLookUp",
type: 'GET',
dataType: 'json',
async: false,
headers: requestHeaders,
success: function (data) {
$.each(data.d.results, function (i, result) {
myData.push(result.Title);
});
myDataSource(myData);
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
function myDataSource(myData){
$('#myAutoCompleteSearch').autocomplete({
source: myData,
minLength: 3
});
}
So far my code is not working, and I'm getting "Uncaught TypeError: Cannot read property 'label' of null " error in my console. I;m wonder what am I doing wrong here? Thanks!
This error occurs when a source for Autocomplete function contains an element(s) with a null value.
Solution
Add the condition for checking if value is not null:
$.each(data.d.results, function (i, result) {
if(result.Title) {
myData.push(result.Title);
}
});
Jast insert your code in
$(document).ready(function () {
//your code here
}

setting a jquery ajax request to async = false doesn't work

I'm attempting to get started with google wallet and am generating a jwt token via an ajax request.
When a user hits the purchase button it fires the purchase() function which in turn sends off some data to get the jwt using the get_jwt_token_for_user() function. I've set the ajax request to not be asynchronous to ensure that the jwt is sent to the google payments handler.
However the purchase() function seems to continue before the jwt is returned by the get_jwt_token_for_user() function. The log output shows that the numbers 1 and 2 are printed to console before the jwt is printed to the console from the get_jwt_token_for_user() function.
function get_jwt_token_for_user(the_key)
{
var JwtTokenURL = "/get_jwt_token";
var the_user_name = $('#user_name').val();
var the_user_email = $('#user_email').val();
var the_user_number = $('#user_number').val();
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
async: false,
success: function(result) {
var myObject = JSON.parse(result);
console.log(myObject.jwt_token);
return myObject.jwt_token
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key)
{
console.log("1");
var jwt_token = get_jwt_token_for_user(the_key);
console.log("2");
if (jwt_token !== "")
{
console.log(jwt_token);
goog.payments.inapp.buy({
parameters: {},
'jwt' : jwt_token,
'success' : successHandler,
'failure' : failureHandler
});
}
}
Any idea what I can do to ensure that the ajax request has returned the data before the purchase() function marches on without the jwt value?
Your get_jwt_token_for_user function doesn't return anything, you need something more like this:
function get_jwt_token_for_user(the_key) {
//...
var myObject;
$.ajax({
//...
success: function(result) {
myObject = JSON.parse(result);
},
//...
});
return myObject ? myObject.jwt_token : '';
}
Returning something from your success callback doesn't cause that value to be returned by $.ajax and JavaScript functions do not return the value of their last expressions, you must include an explicit return if you want your function to return something.
You should also stop using async:false as soon as possible, it is rather user-hostile and it is going away. Your code should look more like this:
function get_jwt_token_for_user(the_key, callback) {
//...
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
success: function(result) {
var myObject = JSON.parse(result);
callback(myObject.jwt_token);
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key) {
get_jwt_token_for_user(the_key, function(jwt_token) {
if (jwt_token !== "") {
//...
}
});
}

Categories