how can I resolve sweetalert background distortion? - javascript

enter image description here
Upper image is the Sign-in page.
I added sweetalert, and it goes wrong like below.
(the alert set in the middel, and my sign-in form goes up! It should be located in the middle!)
(I added the alert appear when the ID or password value is null or empty.)
login equals sign-in
what's wrong with my code?
Here is my full code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9"></script>
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
<meta name="generator" content="Hugo 0.101.0">
<title>Floating labels example · Bootstrap v4.6</title>
<!-- Bootstrap core CSS -->
<!-- <link href="/css/bootstrap.min.css" rel="stylesheet">-->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/product/">
<!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="/css/floating-labels.css" rel="stylesheet">
</head>
<body>
<div class="form-signin" style="max-width: 520px">
<div class="text-center mb-4">
<!-- TODO 로그인페이지 로고 추가할 자리 -->
<!-- <img class="mb-4" src="/brand/bootstrap-solid.svg" alt="" width="72" height="72">-->
<h1 class="h3 mb-3 font-weight-normal">로그인 </h1>
</div>
<div class="form-label-group">
<input id="user_id" class="form-control" placeholder="id" required autofocus>
<label for="inputId">ID를 입력하세요</label>
</div>
<div class="form-label-group">
<input type="password" id="password" class="form-control" placeholder="Password" required>
<label for="inputPassword">Password를 입력하세요</label>
</div>
<div>
<button class="btn btn-outline-primary form-control" id="loginBtn" onclick="login()">로그인</button>
</div>
<hr class="mb-4">
<div class="btn-group row" style="width:100%; --bs-gutter-x: 0">
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;">아이디
찾기
</button>
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;">비밀번호
찾기
</button>
<button class="btn btn-sm btn btn-outline-secondary btn-block col-4" type="button" style="font-size:16px;"
onclick="joinBtn()">회원가입
</button>
</div>
<p class="mt-5 mb-3 text-muted text-center">© 2017-2022</p>
</div>
</body>
</html>
<script>
var input = document.getElementById("password");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
document.getElementById("loginBtn").click();
}
});
var passwordForm = document.querySelector("#password");
function login() {
let userIdValue = document.querySelector("#user_id").value;
let passwordValue = document.querySelector("#password").value;
if (userIdValue == null || userIdValue == "") {
document.querySelector("#user_id").focus();
Swal.fire(
'ID가 비었습니다!',
'로그인 할 계정의 ID를 입력해주세요!',
'question'
)
return;
}
if (passwordValue == null || passwordValue == "") {
document.querySelector("#password").focus();
Swal.fire(
'비밀번호가 비었습니다!',
'로그인 할 계정의 비밀번호를 입력해주세요!',
'question'
)
return;
}
let info = {
userId: userIdValue,
password: passwordValue
}
$.ajax({
url: "/login/check/api",
method: "POST",
contentType: "application/Json",
data: JSON.stringify(info),
success: function (a) {
location.href = "/"
},
error: function (a, b) {
let errorA = a
Swal.fire({
icon: 'error',
title: '로그인 실패',
text: errorA.responseText,
})
//alert(a.responseText);
}
})
}
function joinBtn() {
location.href = "/join/form"
}
</script>
let me know how can I solve this problem
Before the alert comes out, I think the HTML should be on the screen first to solve the problem, but I don't know what to do.

Related

html & javascript enter button redirects to error page - otherwise duplicates text to chat (only when enter is pressed)

Whenever I click on the enter button, it seems the page either shows me
Bad Request
Did not attempt to load JSON data because the request Content-Type was not 'application/json'.
or rarely if enter is pressed it creates duplicates each chat by itself and adds it to the div
I have removed the key event of enter but for some odd reason the enter function still works, I presume this is due to bootstrap but im not too certain.
<!DOCTYPE html>
<html lang="en" style="height: 500px">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lexend" rel="stylesheet" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/stylesheet.css') }}">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://www.unpkg.com/spltjs#1.1.0"></script>
<script src="https://releases.jquery.com/git/jquery-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeit/5.0.2/typeit.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<!-- Navbar content -->
<button type="button" class="btn btn-light" style="height:34px">click me</button>
<p style="color:white; font-family: Lexend;font-size: 15px;font-weight: 400;text-align: center;">AI for a healthier you</p>
<button type="button" class="btn btn-light" style="height:34px">click me</button>
</nav>
<br>
<center>
<div class="container" style="background-color:white ; border-radius: 20px;height:80%;-webkit-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);-moz-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);">
<p style="color:black" id="hello"></p>
<form method="post">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Type here...." aria-label="Recipient's username" aria-describedby="basic-addon2" name="userid" id="textinput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" value="hello world" id="button">Submit</button>
</form>
</div>
</div>
</div>
</center>
<script>
document.getElementById("button").addEventListener("click", insertText);
// CREATES A DIV AND SENDS THE USERS TEXT
function insertText() {
let div = document.createElement("div");
let usertext = document.getElementById('textinput').value;
const usertext2 = 'Patient: ' + usertext;
let text = document.createTextNode(usertext2);
div.appendChild(text);
document.getElementById("hello").appendChild(div);
/////////////// submit JSON TO APP
var json_entry = usertext
fetch('/dashboard', {
method: 'POST',
body: JSON.stringify({
user_text: json_entry
}),
headers: {
'Content-Type': 'application/json'
}
});
let apiData;
fetch('/dashboard/api').then((response) => response.json()).then((data) => {
apiData = data;
let div = document.createElement('div');
let robot_reply = document.createTextNode(apiData);
div.appendChild(robot_reply);
document.getElementById("hello").appendChild(div);
});
////// ENTER BUTTON ////
///////////////////////
/////////////////////// allows the ability to hit the enter button
var input = document.getElementById("textinput");
}
</script>
</div>
</div>
</body>
</html>
When you hit enter, it triggers the submit event on the <form>, which will cause a page refresh. This is basically baked in browser functionality. Any enter keypress in a field inside a <form> tag, causes a form submission. If that form submission is not handled, it will attempt to POST the form to the current URL.
You need to attach everything to the submit event on the <form>, not the button click. And you also need to call e.preventDefault to prevent the browsers default form action handling.
Additionally, you need type="submit" on the button so the click on that button also submits the form.
Using form submit event is also better for accessibility. It means users can press enter in a field or click the button, and it will be handled.
<!DOCTYPE html>
<html lang="en" style="height: 500px">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lexend" rel="stylesheet" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/stylesheet.css') }}">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://www.unpkg.com/spltjs#1.1.0"></script>
<script src="https://releases.jquery.com/git/jquery-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeit/5.0.2/typeit.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<!-- Navbar content -->
<button type="button" class="btn btn-light" style="height:34px">click me</button>
<p style="color:white; font-family: Lexend;font-size: 15px;font-weight: 400;text-align: center;">AI for a healthier you</p>
<button type="button" class="btn btn-light" style="height:34px">click me</button>
</nav>
<br>
<center>
<div class="container" style="background-color:white ; border-radius: 20px;height:80%;-webkit-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);-moz-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);">
<p style="color:black" id="hello"></p>
<form method="post" id="form">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Type here...." aria-label="Recipient's username" aria-describedby="basic-addon2" name="userid" id="textinput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit" value="hello world" id="button">Submit</button>
</form>
</div>
</div>
</div>
</center>
<script>
document.getElementById("form").addEventListener("submit", insertText);
// CREATES A DIV AND SENDS THE USERS TEXT
function insertText(e) {
e.preventDefault();
let div = document.createElement("div");
let usertext = document.getElementById('textinput').value;
const usertext2 = 'Patient: ' + usertext;
let text = document.createTextNode(usertext2);
div.appendChild(text);
document.getElementById("hello").appendChild(div);
/////////////// submit JSON TO APP
var json_entry = usertext
fetch('/dashboard', {
method: 'POST',
body: JSON.stringify({
user_text: json_entry
}),
headers: {
'Content-Type': 'application/json'
}
});
let apiData;
fetch('/dashboard/api').then((response) => response.json()).then((data) => {
apiData = data;
let div = document.createElement('div');
let robot_reply = document.createTextNode(apiData);
div.appendChild(robot_reply);
document.getElementById("hello").appendChild(div);
});
////// ENTER BUTTON ////
///////////////////////
/////////////////////// allows the ability to hit the enter button
var input = document.getElementById("textinput");
}
</script>
</div>
</div>
</body>
</html>

Why doesn't e.preventDefault() stop my page from Refreshing?

I just can't figure out, why my site is loading when pushing the submit-btn. Even though I tried to prevent this with e.preventDefault() in my function. Maybe someone can open my eyes.. I'm sitting next to this (small) problem since 2 Days.
class Einkauf {
constructor(produkt, anzahl){
this.produkt = produkt;
this.anzahl = anzahl;
}
};
class UI {
static showItems () {
const items = [{
Produkt: "Butter",
Anzahl: 2
},{
Produkt: "Käse",
Anzahl: 1
}];
items.forEach(item => UI.addItems(item));
}
static addItems (item) {
const container = document.getElementById('grocery-list');
const newItem = document.createElement('tr');
newItem.innerHTML =
`<td>${item.Produkt}</td>
<td>${item.Anzahl}</td>
<td><a class="btn btn-danger btn-sm delete">x</a></td>`
container.appendChild(newItem);
}
};
document.addEventListener('DOMContentLoaded', UI.showItems());
//Neues Produkt einpflegen:
document.getElementById('btn').addEventListener('submit', (e) => {
e.preventDefault();
//Inputs definieren:
const produkt = document.getElementById('produkt').value;
const anzahl = document.getElementById('anzahl').value;
const einkauf = new Einkauf(produkt, anzahl);
UI.addItems(einkauf);
});
<!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.0">
<title>Einkaufsliste</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch#4.5.2/dist/yeti/bootstrap.min.css" integrity="sha384-mLBxp+1RMvmQmXOjBzRjqqr0dP9VHU2tb3FK6VB0fJN/AOu7/y+CAeYeWJZ4b3ii" crossorigin="anonymous">
</head>
<body>
<div class="container mx-auto">
<h1 class="text-center my-5 display-6">
<span class="text-primary m-0">Einkaufs</span>
liste
</h1>
<form id="form">
<div class="form-group">
<label for="produkt">Was fehlt?</label>
<input type="text" id="produkt" class="form-control">
</div>
<div class="form-group">
<label for="anzahl">Wie viel fehlt?</label>
<input type="number" id="anzahl" class="form-control">
</div>
<input id="btn" type="submit" value="Hinzufügen" class="btn btn-primary btn-block">
</form>
<table class="table table-striped mt-5">
<thead class="text-primary font-weight-bold">
<td>Marke:</td>
<td>Menge:</td>
<td></td>
</thead>
<tbody id="grocery-list">
</tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Maybe someone can figure the problem out and give me a short advice.
Best regards, Philipp.
You should instead be listening to the submit event on the form:
document.getElementById('form').addEventListener('submit', function(e) {
e.preventDefault()
const produkt = document.getElementById('produkt').value;
const anzahl = document.getElementById('anzahl').value;
const einkauf = new Einkauf(produkt, anzahl);
UI.addItems(einkauf);
})
class Einkauf {
constructor(produkt, anzahl) {
this.produkt = produkt;
this.anzahl = anzahl;
}
};
class UI {
static showItems() {
const items = [{
Produkt: "Butter",
Anzahl: 2
}, {
Produkt: "Käse",
Anzahl: 1
}];
items.forEach(item => UI.addItems(item));
}
static addItems(item) {
const container = document.getElementById('grocery-list');
const newItem = document.createElement('tr');
newItem.innerHTML =
`<td>${item.Produkt}</td>
<td>${item.Anzahl}</td>
<td><a class="btn btn-danger btn-sm delete">x</a></td>`
container.appendChild(newItem);
}
};
document.addEventListener('DOMContentLoaded', UI.showItems());
<!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.0">
<title>Einkaufsliste</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch#4.5.2/dist/yeti/bootstrap.min.css" integrity="sha384-mLBxp+1RMvmQmXOjBzRjqqr0dP9VHU2tb3FK6VB0fJN/AOu7/y+CAeYeWJZ4b3ii" crossorigin="anonymous">
</head>
<body>
<div class="container mx-auto">
<h1 class="text-center my-5 display-6">
<span class="text-primary m-0">Einkaufs</span> liste
</h1>
<form id="form">
<div class="form-group">
<label for="produkt">Was fehlt?</label>
<input type="text" id="produkt" class="form-control">
</div>
<div class="form-group">
<label for="anzahl">Wie viel fehlt?</label>
<input type="number" id="anzahl" class="form-control">
</div>
<input id="btn" type="submit" value="Hinzufügen" class="btn btn-primary btn-block">
</form>
<table class="table table-striped mt-5">
<thead class="text-primary font-weight-bold">
<td>Marke:</td>
<td>Menge:</td>
<td></td>
</thead>
<tbody id="grocery-list">
</tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Maybe someone can figure the problem out and give me a short advice. Best regards, Philipp.

JS form validation / new element is created when it shouldnt be

I'm new to js and for learning purposes I'm creting an application, where you can add and delete comments. I added a validation on the text input field and it displays an error when you try to submit an empty comment. Error message appears as it should, but the li element still gets created, when it shouldnt. It should only be added when the input is not empty. Can anyone help me with identifying my mistake?
let form = document.getElementById('form');
let commentList = document.getElementById('allComments');
const errorElement = document.getElementById('error');
// form submit event
form.addEventListener('submit', addComment);
// delete comments
commentList.addEventListener('click', removeComment);
//
// add comment to the list
function addComment(e) {
e.preventDefault();
// get input value
let newComment = document.getElementById('comment').value;
// create new li element
let li = document.createElement('li');
// add a class
li.className = 'list-group-item d-flex justify-content-between';
// add a text node with input value
li.appendChild(document.createTextNode(newComment));
// create delete button element
let deleteButton = document.createElement('button');
// add classes on delete button
deleteButton.className = 'btn btn-danger btn-sm float-right delete';
// append text node
deleteButton.appendChild(document.createTextNode('X'));
// append button to li
li.appendChild(deleteButton);
// append li to list
commentList.appendChild(li);
// add error text if input field is empty when submitting
let messages = [];
if (newComment.value === '' || newComment.value == null) {
messages.push('You cannot submit an empty comment')
}
if (messages.length > 0) {
errorElement.innerText = messages.join(', ');
}
else {
}
}
// remove comment
function removeComment(e) {
if (e.target.classList.contains('delete')) {
if(confirm('Are you sure you want to remove this comment?')) {
let li = e.target.parentElement;
commentList.removeChild(li);
}
}
}
body {
/* font-family: 'Kumar One', cursive; */
font-family: 'Mukta', sans-serif;
}
header {
background-color: rgb(68, 139, 66);
}
header h1 {
font-size: 40px;
font-weight: 400;
}
form {
margin-bottom: 20px;
}
.form-control {
margin-bottom: 5px;
}
<!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.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Kumar+One&family=Mukta:wght#200;400&display=swap"
rel="stylesheet">
<title>Document</title>
</head>
<body>
<header class="text-white p-4 mb-3">
<div class="container">
<div class="col-md-6">
<h1>Adding items</h1>
</div>
</div>
</header>
<div class="container">
<div class="card card-body">
<h2 class="title">Add a comment</h2>
<form class="form-inline col-3 row" id="form">
<input type="text" class="form-control" id="comment">
<div id="error" class="text-danger"></div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<h2 class="title">All comments</h2>
<ul id="allComments" class="list-group">
<li class="list-group-item d-flex justify-content-between">comment 1 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
<li class="list-group-item d-flex justify-content-between">comment 2 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
<li class="list-group-item d-flex justify-content-between">comment 3 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
<li class="list-group-item d-flex justify-content-between">comment 4 <button class="btn btn-danger btn-sm float-right delete">X</button></li>
</ul>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
You should use the following validation at the top of the addComment and return if you find comment is empty so the next statements do not execute.
if (newComment.value === '' || newComment.value == null) {
messages.push('You cannot submit an empty comment')
// Add return to exit from function
return;
}

implement JavaScript callback

I'm a beginner in Javascript I have an api which I need to execute asynchronously or I need a request to be executed only after the previous one is completed.
Researching I found that with Callback it is possible to do this, however I cannot implement it in my script.
Below is my HTML:
<!DOCTYPE html>
<html class="loading" lang="en" data-textdirection="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="description" content="Chameleon Admin is a modern Bootstrap 4 webapp & admin dashboard html template with a large number of components, elegant design, clean and organized code.">
<meta name="keywords" content="admin template, Chameleon admin template, dashboard template, gradient admin template, responsive admin template, webapp, eCommerce dashboard, analytic dashboard">
<meta name="author" content="Niklausec">
<title></title>
<link rel="apple-touch-icon" href="../../theme-assets/images/ico/apple-icon-120.png">
<link rel="shortcut icon" type="image/x-icon" href="theme-assets/images/logo/logo.png">
<link href="https://fonts.googleapis.com/css?family=Muli:300,300i,400,400i,600,600i,700,700i%7CComfortaa:300,400,700" rel="stylesheet">
<link href="https://maxcdn.icons8.com/fonts/line-awesome/1.1/css/line-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body class="vertical-layout vertical-menu 2-columns menu-expanded fixed-navbar" style="background: #0f1321;" data-open="click" data-menu="vertical-menu" data-color="bg-chartbg" data-col="2-columns">
<div class="container mt-4" style="margin-bottom: 100px;">
<div class="text-center mb-3">
<div class="text-center ">
<h1 class="text-light"><b></b> </h1>
<div class="text-center ">
</div>
<textarea class="form-control bg-dark text-light" style="resize: none;text-align: center;margin: auto;" rows="12" id="lista" placeholder="Informe sua lista"></textarea>
</fieldset>
<center>
<div class="mb-3">
<button type="button" class="btn btn-light btn-min-width mr-1 mb-1" id="testar" onclick="enviar()">INICIAR</button>
<button type="button" class="btn btn-light btn-min-width mr-1 mb-1" id="parar" disabled="true">PARAR</button>
VOLTAR
</div>
</center>
<center>
<div class="badge badge-success badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-check"></i>
<span style="font-size: 15px;"> Aprovados</span>
<span style="font-size: 15px;" id="cLive">0</span>
</div>
<div class="badge badge-danger badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-close"></i>
<span style="font-size: 15px;"> Reprovados</span>
<span style="font-size: 15px;" id="cDie">0</span>
</div>
<div class="badge badge-primary badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-clock-o"></i>
<span style="font-size: 15px;"> Testados</span>
<span style="font-size: 15px;" id="total">0</span>
</div>
<div class="badge badge-info badge-pill" style="padding: 10px 10px;margin: 5px;">
<i class="la la-cloud-upload"></i>
<span style="font-size: 15px;"> Carregados</span>
<span style="font-size: 15px;" id="carregadas">0</span>
</div>
</center>
<center>
<div class="text-center text-light mt-3">
<h4 class="text-light" id="status_ccs">AGUARDANDO INICIO...</h4>
</div>
</center>
<div class="col-md-12 mt-3 p-0">
<div class="card bg-dark text-light">
<div style="position: absolute;top: 0;right: 0;">
<button id="mostra" class="btn btn-primary" style="padding: 2px 5px;"><i class="la la-external-link-square" style="font-size: 30px;"></i></button>
</div>
<div class="card-body">
<h6 style="font-weight: bold;" class="card-title text-light">Aprovados - <span id="cLive2" class="badge badge-success">0</span></h6>
<div id="bode"><span id=".aprovadas" class="aprovadas"></span></div>
</div>
</div>
</div>
<div class="col-md-12 mt-3 p-0">
<div class="card bg-dark text-light">
<div style="position: absolute;top: 0;right: 0;">
<button id="mostra2" class="btn btn-primary" style="padding: 2px 5px;"><i class="la la-external-link-square" style="font-size: 30px;"></i></button>
</div>
<div class="card-body">
<h6 style="font-weight: bold;" class="card-title text-light">Reprovados - <span id="cDie2" class="badge badge-danger">0</span></h6>
<div id="bode2"><span id=".reprovadas" class="reprovadas"></span></div>
</div>
</div>
</div>
</div>
<!-- BEGIN VENDOR JS-->
<script src="theme-assets/vendors/js/vendors.min.js" type="text/javascript"></script>
<!-- BEGIN VENDOR JS-->
<!-- BEGIN PAGE VENDOR JS-->
<script src="theme-assets/vendors/js/charts/chartist.min.js" type="text/javascript"></script>
<!-- END PAGE VENDOR JS-->
<!-- BEGIN CHAMELEON JS-->
<script src="theme-assets/js/core/app-menu-lite.js" type="text/javascript"></script>
<script src="theme-assets/js/core/app-lite.js" type="text/javascript"></script>
<!-- END CHAMELEON JS-->
<!-- BEGIN PAGE LEVEL JS-->
<script src="theme-assets/js/scripts/pages/dashboard-lite.js" type="text/javascript"></script>
<!-- END PAGE LEVEL JS-->
<script type="text/javascript">
$(document).ready(function(){
$("#bode").hide();
$("#esconde").show();
$('#mostra').click(function(){$("#bode").slideToggle();});
});
$(document).ready(function(){
$("#bode2").hide();
$("#esconde2").show();
$('#mostra2').click(function(){$("#bode2").slideToggle();});
});
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
if (total > 500) {
alert("Limite: 500 GERADEX POR TESTE!");
return;
}
var ap = 0;
var rp = 0;
$('#testar').attr('disabled', 'disabled');
$('#parar').attr('disabled', null);
var callBackFn = function(index) {
if (index >= linhaenviar.length) {
return;
}
var value = linhaenviar[index];
var ajaxCall = $.ajax({
url: 'afa.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("APROVADO")) {
removelinha();
ap++;
aprovadas(resultado + "");
$('#status_ccs').html('APROVADO');
} else {
removelinha();
rp++;
reprovadas(resultado + "");
$('#status_ccs').html('');
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
if (fila == total) {
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
// audio.play();
document.getElementById("status_ccs").innerHTML = "FINALIZADO";
setTimeout(function() {
document.getElementById("status_ccs").innerHTML = "AGUARDANDO INICIO...";
}, 6000);
}
index++;
callBackFn(index);
}
});
$('#parar').click(function() {
ajaxCall.abort();
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
var st = 'PAUSADO';
$('#status_ccs').html(st);
});
}
callBackFn(0);
}
});
}
function aprovadas(str) {
$(".aprovadas").prepend(str + "<br>");
}
function reprovadas(str) {
$(".reprovadas").prepend(str + "<br>");
}
function removelinha() {
var lines = $("#lista").val().split('\n');
lines.splice(0, 1);
$("#lista").val(lines.join("\n"));
}
</script>
</body>
</html>
Expected Result:
I need only another call to be made in the API after the end of the later one and so on.
I changed your enviar function so that each ajaxCall is executed just after previous has finished.
Notice:
I created a variable "callBackFn". This is function that will be used as callback.
At the end of ajax success I executed this callBackFn.
function enviar() {
var linha = $("#lista").val();
var linhaenviar = linha.split("\n");
var total = linhaenviar.length;
if (total > 500) {
alert("Limite: 500 GERADEX POR TESTE!");
return;
}
var ap = 0;
var rp = 0;
$('#testar').attr('disabled', 'disabled');
$('#parar').attr('disabled', null);
var callBackFn = function(index) {
if (index >= linhaenviar.length) {
return;
}
var value = linhaenviar[index];
var ajaxCall = $.ajax({
url: 'afa.php?lista=' + value,
type: 'GET',
async: true,
success: function(resultado) {
if (resultado.match("APROVADO")) {
removelinha();
ap++;
aprovadas(resultado + "");
$('#status_ccs').html('APROVADO');
} else {
removelinha();
rp++;
reprovadas(resultado + "");
$('#status_ccs').html('');
}
$('#carregadas').html(total);
var fila = parseInt(ap) + parseInt(rp);
$('#cLive').html(ap);
$('#cDie').html(rp);
$('#total').html(fila);
$('#cLive2').html(ap);
$('#cDie2').html(rp);
if (fila == total) {
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
// audio.play();
document.getElementById("status_ccs").innerHTML = "FINALIZADO";
setTimeout(function() {
document.getElementById("status_ccs").innerHTML = "AGUARDANDO INICIO...";
}, 6000);
}
index++;
callBackFn(index);
}
});
$('#parar').click(function() {
ajaxCall.abort();
$('#testar').attr('disabled', null);
$('#parar').attr('disabled', 'disabled');
$('#lista').attr('disabled', null);
var st = 'PAUSADO';
$('#status_ccs').html(st);
});
}
callBackFn(0);
}
By the way, if you intend to process audio I would suggest using https://howlerjs.com/

Did I correctly set-up my API for this weather app?

I am working with a weather app api and I am trying to display weather Data based off what the users inserts in the form. For some reason the data is not displaying. I have gone through the code 10 times, and I cant seem to find the error.
Can anyone take a look at point out where I have gone wrong?
Thank you
$(document).ready(function() {
$('submitWeather').click(function() {
var city = $('#city').val();
if (city != '') {
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=_MY_API_KEY_",
type: "GET",
dataType: "jsonp",
success: function(data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val('');
}
});
} else {
$("#error").html('Field cannot be empty');
}
});
});
function show(data) {
return '<h3><strong>Weather<strong>: ' + data.weather[0].main + ' </h3>' +
'<h3><strong>Weather<strong>: ' + data.weather[0].description + ' </h3>';
}
console.log('hello')
.mainArea {
background-color: lightgray;
}
.day1,
.day2,
.day3,
.day4,
.day5 {
width: 220px;
height: 200px;
background-color: blue;
position: relative;
color: white;
}
.input {
text-align: center;
}
input[type='text'] {
height: 50px;
width: 200px;
background: #e7e7e7;
}
input[type='submit'] {
height: 50px;
width: 100px;
background: blue;
}
<!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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Weather Dashboard</title>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-light bg-light jumbotron">
<div class="navbar-brand">Weather Guide</a>
<!-- <form class="form-inline">
<input class="inputValue form-control mr-sm-2" type="text" placeholder="Search City" aria-label="Search">
<button class="button btn btn-outline-success my-2 my-sm-0" value="submit" type="submit">Search</button>
</form>-->
</nav>
<div class="container">
<div class="row">
<h3 class="text-center text-primary">Enter City Name</h3>
</div>
<div class='row form-group form-inline'>
<input tyepe='text' name='city' id="city" class="form-control" placeholder="city name">
<button id="submitWeather" class="btn btn-primary">Search</button>
</div>
<div id="show">
</div>
</div>
<!-- Main Content -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
$('submitWeather') should be $('#submitWeather')
Here's how to do it without jquery incase anybody wants it:
const getCity = () => document.querySelector('input#city').value || "austin"
document.querySelector("#getWeather").addEventListener('click', function () {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${getCity()}&units=metric&APPID=_MY_API_KEY_`
loadDataRequest(url, displayJSON)
})
function loadDataRequest(url, cb) {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
cb(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function displayJSON(xhttp) {
document.querySelector("#show").textContent = JSON.stringify(JSON.parse(xhttp.response), null, 2);
}
<input id="city" name="city" placeholder="city"/>
<button id="getWeather" type="button" >Get</button>
<div id="show" style="white-space:pre"></div>

Categories

Resources