ERR_NAME_NOT_RESOLVED in OpenWeather Api Call - ajax

I'm putting together my first Api project and I'm using OpenWeather to request conditions for a city. When I run my code, I get "ERR_NAME_NOT_RESOLVED." I've checked and rechecked my URL formatting and I'm not getting any errors when running my code. Could anyone point me in the right direction?
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script defer src="./js/script.js"></script>
<title>Weatherd</title>
</head>
<body>
<h1>Weatherd</h1>
<form>
<input type="text" placeholder="Search by city"/>
<input type="submit" value="Search"/>
</form>
<main>
<p>Weather for</p>
<p id="weatherFor"></p>
<p>Temperature: </p>
<p id ="temp"></p>
<p>Currently feels like: </p>
<p id="feelsLike"></p>
<p>Conditions: </p>
<p id="desc"></p>
</main>
</body>
</html>
My JS
const $weatherFor = $('#weatherFor');
const $temp = $('#temp');
const $feelsLike = $('#feelsLike');
const $desc = $('#desc');
const $input = $('input[type="text"]');
let weatherData, userInput;
$('form').on('submit', handleGetData);
function handleGetData(event) {
event.preventDefault();
userInput = $input.val();
$.ajax({
url: 'https://www.api.openweathermap.org/data/2.5/weather?q='+userInput+'&APPID=15ff99dd07f18bda25869ab24d06891e'
}).then(
(data) => {
weatherData = data;
render();
},
(error) => {
console.log('bad request', error);
}
);
}
function render() {
$weatherFor.text(weatherData.weatherFor);
$temp.text(weatherData.temp);
$feelsLike.text(weatherData.feelsLike);
$desc.text(weatherData.desc);
}

It's been a while since the question was asked, but given the amount of visits this question has had so far, this answer might help someone.
const url = "api_url_here";
const result = await axios
.get(url)
.then((res) => {
const { status } = res;
return status && status == 200
? { ...res.data, status: 200 } // return data + status 200
: { status: 400 }; // create and return status 400 on error
})
.catch((err) => {
return { status: 400 }; // create and return status 400 on error
});
// work with the returned status
if(result.status == 200) {
// success
} else {
// error
}
I used axios, but the idea is very much transferable to Fetch Api or Ajax.

Related

Laravel Vue Axios - Axios DELETE Request becomes GET Request

I'm getting a particular error and can't understand where the problem is.
No more explanations, code will illustrate it better than me :
Here are my routes :
Route::get('/', 'HomeController#index')->name('home');
Route::delete('home/{home}', 'HomeController#destroy')->name('home.destroy');
Here is my homeController :
class HomeController extends Controller
{
public function index()
{
return view('view');
}
public function destroy()
{
ddd('Hello World');
}
}
Here is my view 'view.blade.php' :
#extends('layouts.layout')
#section('content')
<component></component>
#endsection
Here is my layout :
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="base-url" content="{{ url('/') }}">
<title>{{ config('app.name', 'Laravel') }}</title>
#yield('styles')
</head>
<body>
<div id="app">
#yield('content')
</div>
<!-- Scripts -->
<script src="{{ mix('js/app.js') }}"></script>
#yield('scripts')
</body>
</html>
Here is my bootstrap.js :
window._ = require('lodash');
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token)
{
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
}
else
{
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
Here is my app.js :
require('./bootstrap');
window.Vue = require('vue');
Vue.prototype.baseUrl = document.head.querySelector('meta[name="base-url"]').content;
Vue.component('component', require('./components/ComponentComponent.vue').default);
const app = new Vue({
el: '#app',
});
And here is my component :
<template>
<button v-on:click="delete()">BUTTON</button>
</template>
<script>
export default {
methods: {
delete()
{
if ( confirm('Confirm ?') )
{
axios.delete(`${this.baseUrl}/home/6`)
.then( (response) =>
{
console.log('Succeeded');
})
.catch( (error) =>
{
console.log('Failed');
});
}
}
},
created()
{
this.$nextTick( () =>
{
});
}
}
</script>
What I actually have is a console.log message : "Succeeded" but as a response I get a page full of Ignition elements giving the error :
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods:
DELETE.
When I change delete into get in my route : I get the error
DELETE http://test.test/home/6 404 (Not Found)
Like I'm really sending a DELETE Request but at a given time, it changes in a GET request Type... Inexplicable...
No need to say that I need serious help here, thank you for helping !
Have you tried using a resource controller?
https://laravel.com/docs/5.7/controllers#resource-controllers
Also you should follow the rules of the REST API.
So a get request would be: http://test.test/home?id=6
A delete request would be: http://test.test/home/6
So in axios you want to use parameters when you send the get request to
axios.get('/home', {
params: {
id: 6
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
But a delete request would go to
'http://test.test/home/' + id
https://github.com/axios/axios
I believe that because when you change the
DELETE request http://test.test/home/6 to a GET request
Laravel is looking for PUT, PATCH, DELETE
this is why you are getting this error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: PUT, PATCH, DELETE.
In your index method here:
public function index()
{
$id = $request->input('id');
# DO SOMETHING WITH THIS ID HERE
return view('view')->with(['data' => 'WHATEVER YOU DID ABOVE']);
}
Is where you would handle this id parameter to fetch the id of 6.
https://laravel.com/docs/5.7/requests#retrieving-input
OR
You could add this to your controller:
public function show($id)
{
}
and than route to it:
Route::get('/{id}', 'HomeController#show')->name('home');
https://laravel.com/docs/4.2/routing#route-parameters
// Have you tried this way of doing the Axios delete?
axios({
method: 'delete',
url: '/home/6'
}).then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});

Load Vue Componet via AJAX

I'd like to load Vue Component via AJAX dynamically and render its template.
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
alert(url);
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
var mainContent;
fetch('/vue/actions/?content_type=json&action='+action).then((response) => {
if(response.ok) {
return response.json();
}
throw new Error('Network response was not ok');
}).then((json) => {
this.$router.push({ path: '/vue/actions/', query: { action: json.action }});
// this.mainContent = json.template;
console.log(json.template);
this.dynamicComponent = json.template;
}).catch((error) => {
console.log(error);
});
}
},
created: function () {
this.actions();
}
})
Initial Page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />
<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>
<script type="text/javascript" src="/js/vue.min.js"></script>
<script src="/js/vue-router.js"></script>
</head>
<body>
<template><div><component :is="dynamicComponent"></component></div></template>
<div id="mainContainer" v-html="mainContent"></div>
<script type="text/javascript" src="/js/main.js"></script>
</body>
</html>
Component I'd like to load via AJAX:
Vue.component('dynamicComponent', {
template: '<div>Dynamic Component!</div>'
});
Is it possible to load such Vue Componet and render its template (with an ability to use Vue data bindings in the Component template)?
Here is how I got what I need:
Main Vue Instance:
const router = new VueRouter({
path: '/vue/actions/',
mode: 'history'
});
var app = new Vue({
el: '#mainContainer',
router,
data: {
mainContent: ''
},
methods: {
action: function (url) {
this.$router.push({ path: '/vue/actions/?'+url});
console.log(this.$route.query);
},
actions: function () {
var action;
if (!this.$route.query.action || this.$route.query.action == 'main') {
action = 'index';
} else {
action = this.$route.query.action;
}
Vue.component('dynamic-component', (resolve) => {
import('/vue/actions/?content_type=javascript&action='+action).then((component) => {
resolve(component.default);
});
});
}
},
created: function () {
this.actions();
}
})
Main/Initial Page Body:
<body>
<div id="mainContainer">
<dynamic-component></dynamic-component>
</div>
<script type="text/javascript" src="{{.__web_root_folder}}/js/main.js"></script>
</body>
Component code that I'm loading when needed:
export default {
template: '<div>Async Component! {{.test}}</div>',
data () {
return {
test: 'Works!'
}
}
}
Thanks to #MazinoSUkah !

renderToString with Redux store renders populated without props (server side)

Although the story id properly prefilled, renderToString() still renders the app without the state being filled in via mapStateToProps().
I use selectors to get data from state.
The problem is, that the props are not being populated. On the client, everything works.
Anyone ideas?
THANKS!
Here's the code for the server side operation:
app.use('*', (req, res) => {
// // Create a new Redux store instance
const sagaMiddleware = createSagaMiddleware();
let middleware = applyMiddleware(sagaMiddleware);
// middleware = compose(middleware,thunkMiddleware)
const initialState = {};
const store = createStore(reducers,initialState,middleware);
store.runSaga = sagaMiddleware.run;
store.close = () => store.dispatch(END);
const routes = getRoutes(store.getState)
const tres = res;
const url = req.originalUrl;
const urlSplit = url.split('/');
match({ routes: routes, location: req.url }, (err, redirect, props) => {
if (err) {
tres.status(500).send(err.message)
} else if (redirect) {
tres.redirect(redirect.pathname + redirect.search)
} else if (props) {
if(urlSplit[1]==='story'){
let slug = urlSplit[2];
store.runSaga(waitAll([[getStoryBySlug,host,slug], [getAbout, host]])).done.then(() => {
res.end(renderPage(store,props,tres));
});
}else{
store.runSaga(waitAll([[getAbout, host], [getHome, host]])).done.then(() => {
res.end(renderPage(store,props,tres));
});
}
} else {
tres.status(404).send('Not Found')
}
})
});
And here are the actual renderPage and renderFullPage functions:
const renderPage = (store,props,res) => {
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<RouterContext {...props}/>
</Provider>
)
let head = Helmet.rewind();
const preloadedState = fromJS(store.getState());
return renderFullPage(html, preloadedState, head);
}
const renderFullPage = (html, preloadedState, head) => {
return `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
<script src="https://use.typekit.net/yzi3zgu.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
<link href="/assets/fonts/GillSans/stylesheet.css" rel="stylesheet"/>
<link href="/assets/vendors/fullpage/jquery.fullPage.css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous" />
<link rel="shortcut icon" href="/assets/icons/favicon-inv.png" />
<link rel="stylesheet" href="/styles.css" />
</head>
<body>
<div id="root">${html}</div>
<script>
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)}
</script>
<script src="/vendor.js"></script>
<script src="/main.js"></script>
</body>
</html>
};

Username availability checking using Ajax in JSP and stopping form submission

I am new to ajax and I am trying to create a gmail type username availability check by using Ajax and JavaScript in JSP.
My code works well for username availability check but I am not able to stop the form submission when a username is not available.
For checking username availability I used onkeyup() which checks each character, but for preventing the form submission I used onsubmit() in form tag.
For execution flow check I used alert statements in this code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return formValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>
Ajax is asynchronous so your call to returnFunction , need not return the correct flag, it will return false always as most probably success function will be triggered only after method is completed(onresponse).
So you need to ensure that response of Ajax cal is recieved using a completed boolean, and continuously checking it until it is true.
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
var completed = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
returnFunction(username);
while(!completed) {
//wait for ajax response
}
if(flag)
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
var flag = new Boolean(false);
function returnFunction(str)
{
alert("1");
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
document.f1.submit();
}
else{
alert("caught flage:false");
alert("Username chossen by u is already taken.Please choose different Username");
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" >
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>
make changes like this it will work .if any prob let be know.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function getXMLHttpRequest(){
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
};
function usernameValidation(str)
{
if (str.length==0)
{
document.getElementById("uname").innerHTML="should not be empty";
return false;
}
else if(str.length<=4)
{
document.getElementById("uname").innerHTML="need more than 4 charachers";
return false;
}
else{
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange =function()
{
if (xmlHttpRequest.readyState < 4 && xmlHttpRequest.readyState > 0)
{
document.getElementById("uname").innerHTML = "<img src='images/load.gif' alt='checking...' width=16 height=16/>";
}
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
if(xmlHttpRequest.responseText=="available")
{
document.getElementById("uname").innerHTML = "<img src='images/ok.png' alt='username available' width=16 height=16/>";
document.getElementById("uname1").innerHTML = ".";
}
else
{
document.getElementById("uname").innerHTML = "username not available";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
};
function userSubmitValidation(){
var msg = document.getElementById("uname1").innerHTML;
if(msg=='.'){
return true;
}
else{
return false;
}
};
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return userSubmitValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="usernameValidation(this.value)" onblur="usernameValidation(this.value)"></div>
<span id="uname" style="color: red"></span><span id="uname1" style="color: white"></span>
<input type="submit" value="register">
</form>
</body>
</html>
i am new at ajax too and i am kind of trying to do the same thing as you are doing. I have successfully checked the username availability using ajax and jsp. Then the thing i stuck at that even if a username is not available the page still submit after clicking submit button. Then I used javascript to solve this problem. I compared the returned text with another text declared before. If check successful then it will go to next page otherwise not. For details please check this page->"Ajax based username availablity checking and then generating some username to use in jsp". There check out the sample.jsp code. In that code a i did the checking part in the function named "conditions()". In that function the variable "checkvalue" hold the returned text which is generated by availability check. Then i compare it with the text "available". If matches then the page will submit other wise not. I am not sure is this what you wanted to know or not and if it is then my answer helps you or not. Thank you and good luck..

Ajax Code To Display Data

I wrote this code in javascript to disply information in this page (Normal_Info.php),
but unfortunately it did not work. If anyone can help me I will be grateful
<html>
<head>
<script language="javascript">
function ajaxFunction()
{
return window.XMLHttpRequest ?
new window.XMLHttpRequest :
new ActiveXObject("Microsoft.XMLHTTP");
}
function Go_there()
{
var httpObj = ajaxFunction();
httpObj.open("GET","Normal_Info.php", true);
httpObj.send();
httpObj.onreadystatechange = ChangedState()
{
if (httpObj.readyState == 4 && httpObj.status == 200)
{
document.getElementById("result").innerHTML=httpObj.responseText;
}
}
}
</script>
</head>
<body>
<form id=ff>
<input type=button value=Hi OnClick=Go_there() />
</form>
<div id=result>
</div>
</body>
</html>
i suggest using jquery http://jquery.com/
<script src="jquery.js"></script>
<script language="javascript">
$('#ff').submit(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('#result').html(data);
// alert('Load was performed.');
}
});
});
</script>
no need to click event

Resources