I have a card in my web page that reads in Automation Data and displays it in the card my the page. I am about to read in all the needed data except for the URL to the automation test summary.
Here is my code:
function Cox() {
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function(data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxFailed" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxPassed" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
<div id="coxRunTime" class="mr-5">
<script type="text/javascript">
Cox();
</script>
</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
When I try to load the URL into the HMTL like I did for the other 4 variables it does not seem to work correctly. Any ideas?
UPDATE:
Thank you for the helpful comments on how to clean up my code. I have aded it in and it has made it a lot cleaner. I have also found the following post that has provided a solution to my issue. Thanks
document.getElementById to include href
You will get the error message as "Uncaught ReferenceError: Cox is not defined" because you are calling 'Cox()' function before define it. DOM will process line by line and during that time, the function does not exist.
I changed your code and mentioned below. it will work as you expected. :)
I called 'Cox()' function after definition. You can change the place where ever you want but after definition.
<html>
<body>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5"></div>
<div id="coxFailed" class="mr-5"></div>
<div id="coxPassed" class="mr-5"></div>
<div id="coxRunTime" class="mr-5"></div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function Cox()
{
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function (data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
Cox();
</script>
</body>
</html>
You should only call Cox() once: when the page loads as it targets all the divs anyway. Also, Cox() is undefined because you call it before you define it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function Cox() {
jQuery.ajax({
method: "POST",
dataType: "JSON",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function(data) {
console.log(data);
var total = data[0];
var passed = data[1];
var failed = data[2];
var time = data[3];
var url = data[4];
document.getElementById('coxTotal').innerHTML = "Total tests: " + total;
document.getElementById('coxFailed').innerHTML = "Failed tests: " + failed;
document.getElementById('coxPassed').innerHTML = "Passed tests: " + passed;
document.getElementById('coxRunTime').innerHTML = "Run Time: " + time;
document.getElementById('coxUrl').innerHTML = "url " + url;
}
});
}
window.onload = function(){
Cox();
}
</script>
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div id="coxTotal" class="mr-5">
</div>
<div id="coxFailed" class="mr-5">
</div>
<div id="coxPassed" class="mr-5">
</div>
<div id="coxRunTime" class="mr-5">
</div>
</div>
<a class="card-footer text-white clearfix small z-1" href="#">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
</div>
Related
I would like to implement such logic:
User clicks on "Plus" or "Minus" button.
If the user don't click at any of those buttons for 2 seconds, then we assume that current quantity should be sent to the server.
Right now, I have three buttons:
"Plus" - increments quantity by 1 and changes the value at page.
"Minus" - decreases quantity by 1 and changes the value at page.
"Confirm" - The button that sends request with current quantity parameter to Spring Boot controller and changes quantity on server side.
I would prefer to avoid this button, because it adds complexity.
Is there a convenient way to get rid of the confirm button?
The only way I know how we can do this is by sending request to controller on each "Plus" or "Minus" button click.
But it seems that this approach will be inefficient.
$(document).ready(function () {
//include csrf for every ajax call
$(function () {
let token = $("meta[name='_csrf']").attr("content");
let header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function (event, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
$(".plusForm").submit(function (event) {
event.preventDefault();
let $prodCount = $(this).parent().parent().parent().find(".prodCount span");
let currentQuantity = parseInt($prodCount.text());
$prodCount.text(++currentQuantity);
});
$(".minusForm").submit(function (event) {
event.preventDefault();
let $prodCount = $(this).parent().parent().parent().find(".prodCount span");
let currentQuantity = parseInt($prodCount.text());
$prodCount.text(--currentQuantity);
});
$(".changedQuantityForm").submit(function (event) {
event.preventDefault();
let $prodCount = $(this).parent().parent().parent().find(".prodCount span");
let quantity = parseInt($prodCount.text());
let productId = $(this).parent().parent().parent().parent().find(
'.product-id').val();
changeQuantityAjax(productId, quantity);
});
function changeQuantityAjax(id, quantity) {
console.log("quantity changed on server side");
/* $.ajax({
type: "PUT",
contentType: "application/json",
url: "/rest/cart/" + id + "?quantity=" + quantity,
data: {
"quantity": quantity
},
success: function () {
console.log('SUCCESS ' + id + ' ' + quantity);
// alert(name + ' was deleted')
},
error: function () {
console.log('ERROR ' + id + ' ' + quantity);
}
}); */
}
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
rel="stylesheet" media="screen"/>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css">
<div class="row justify-content-center">
<div class="col mb-4 prodItem">
<div class="card border-primary" style="height: 34rem; width: 26rem;">
<div class="view overlay">
<img class="card-img-top img-fluid"
src="https://cdn.pixabay.com/photo/2018/10/05/23/24/chicken-3727097_1280.jpg"
style="height : 18rem;" alt="Card image cap">
<div class="mask rgba-white-slight"></div>
</div>
<div class="card-body">
<h3><span>Chicken</span></h3>
<div class="float-right">
<h2 class="card-title"><span>1000</span> $</h2>
</div>
<br>
<br>
<br>
<div class="form-control">
<div class="row prodCount" style="margin: auto; font-size: 17px">
<p> In cart :  </p>
<span>0</span>
<div class="row float-right" style="margin: auto">
<form class="plusForm">
<button type="submit" class="btn-sm">
<i class="fas fa-plus-circle fa-w-16 fa-3x text-danger"></i>
</button>
</form>
<form class="minusForm">
<button type="submit" class="btn-sm">
<i class="fa fa-minus-circle fa-w-16 fa-3x" aria-hidden="true"></i>
</button>
</form>
<form class="changedQuantityForm">
<button type="submit" class="btn-sm">
<i class="fas fa-check fa-w-16 fa-3x text-success"></i>
</button>
</form>
</div>
</div>
</div>
<br>
</div> <!-- card-body -->
</div> <!-- card -->
</div>
Fiddle
PC: It seems that my question is related to this topic(https://stackoverflow.com/a/7762539/14308420).
But I'm not sure if I should apply it in my case and how to do it.
I extracted the logic of submit button to function updateQuantityOnServer(button). And after adding this line:
changedQuantityTimeout = setTimeout(updateQuantityOnServer(this), 1000);
I got a warning:
Argument type void is not assignable to parameter type TimerHandler Type void is not assignable to type string | Function Type void is not assignable to type Function.
As I understand, it's caused because I send button as parameter. But I use this button to get parameters...
Look at the changeQuantityAjax function for the implementation of clearTimeout and setTimeout together, making a "minimal" delay of 2 seconds after the last user action.
From each button click, this was passed to the getIdandQuantity function.
It does not change much things in the logic, but notice the .parents() instead of parent().parent().parent().
$(document).ready(function() {
//include csrf for every ajax call
$(function() {
let token = $("meta[name='_csrf']").attr("content");
let header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(event, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
$(".plusForm").submit(function(event) {
event.preventDefault();
let $prodCount = $(this).parents(".prodCount").find("span");
let currentQuantity = parseInt($prodCount.text());
$prodCount.text(++currentQuantity);
getIdandQuantity(this);
});
$(".minusForm").submit(function(event) {
event.preventDefault();
let $prodCount = $(this).parents(".prodCount").find("span");
let currentQuantity = parseInt($prodCount.text());
$prodCount.text(--currentQuantity);
getIdandQuantity(this);
});
// That is the function to retreive the id and quantity from the clicked button
function getIdandQuantity(btn) {
let $parent = $(btn).parents(".prodCount");
let quantity = parseInt($parent.find("span").text());
let productId = $parent.find('.product-id').val();
changeQuantityAjax(productId, quantity);
}
// A variable to store the refence to the pending setTimeout
let ajaxTimeout
function changeQuantityAjax(id, quantity) {
// Clear any existing setTimeout
clearTimeout(ajaxTimeout)
// Set a 2 seconds timeout
ajaxTimeout = setTimeout(function() {
console.log("quantity changed on server side");
/* $.ajax({...}) */
}, 2000)
}
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" media="screen" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css">
<div class="row justify-content-center">
<div class="col mb-4 prodItem">
<div class="card border-primary" style="height: 34rem; width: 26rem;">
<div class="view overlay">
<img class="card-img-top img-fluid" src="https://cdn.pixabay.com/photo/2018/10/05/23/24/chicken-3727097_1280.jpg" style="height : 18rem;" alt="Card image cap">
<div class="mask rgba-white-slight"></div>
</div>
<div class="card-body">
<h3><span>Chicken</span></h3>
<div class="float-right">
<h2 class="card-title"><span>1000</span> $</h2>
</div>
<br>
<br>
<br>
<div class="form-control">
<div class="row prodCount" style="margin: auto; font-size: 17px">
<p> In cart :  </p>
<span>0</span>
<div class="row float-right" style="margin: auto">
<form class="plusForm">
<button type="submit" class="btn-sm">
<i class="fas fa-plus-circle fa-w-16 fa-3x text-danger"></i>
</button>
</form>
<form class="minusForm">
<button type="submit" class="btn-sm">
<i class="fa fa-minus-circle fa-w-16 fa-3x" aria-hidden="true"></i>
</button>
</form>
</div>
</div>
</div>
<br>
</div>
<!-- card-body -->
</div>
<!-- card -->
</div>
Additionnally! You could easilly merge the 4 functions above (2 click handlers, getIdandQuantity and changeQuantityAjax) into one single click handler.
$(document).ready(function() {
//include csrf for every ajax call
$(function() {
let token = $("meta[name='_csrf']").attr("content");
let header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(event, xhr, options) {
xhr.setRequestHeader(header, token);
});
});
// A variable to store the refence to the pending setTimeout
let ajaxTimeout
$(".plusForm, .minusForm").submit(function(event) {
event.preventDefault();
// Get the elements needed, the product is and the quantity shown
let $parent = $(this).parents(".prodCount");
let id = $parent.find('.product-id').val();
let $prodCount = $parent.find("span")
let currentQuantity = parseInt($prodCount.text());
// Increment OR decrement the quantity
let quantity = ($(this).hasClass("plusForm")) ? ++currentQuantity : --currentQuantity
// Update the shown quantity
$prodCount.text(quantity)
// Clear any existing setTimeout
clearTimeout(ajaxTimeout)
// Set a 2 seconds timeout
ajaxTimeout = setTimeout(function() {
console.log("quantity changed on server side");
/* $.ajax({...}) */
}, 2000)
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" media="screen" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css">
<div class="row justify-content-center">
<div class="col mb-4 prodItem">
<div class="card border-primary" style="height: 34rem; width: 26rem;">
<div class="view overlay">
<img class="card-img-top img-fluid" src="https://cdn.pixabay.com/photo/2018/10/05/23/24/chicken-3727097_1280.jpg" style="height : 18rem;" alt="Card image cap">
<div class="mask rgba-white-slight"></div>
</div>
<div class="card-body">
<h3><span>Chicken</span></h3>
<div class="float-right">
<h2 class="card-title"><span>1000</span> $</h2>
</div>
<br>
<br>
<br>
<div class="form-control">
<div class="row prodCount" style="margin: auto; font-size: 17px">
<p> In cart :  </p>
<span>0</span>
<div class="row float-right" style="margin: auto">
<form class="plusForm">
<button type="submit" class="btn-sm">
<i class="fas fa-plus-circle fa-w-16 fa-3x text-danger"></i>
</button>
</form>
<form class="minusForm">
<button type="submit" class="btn-sm">
<i class="fa fa-minus-circle fa-w-16 fa-3x" aria-hidden="true"></i>
</button>
</form>
</div>
</div>
</div>
<br>
</div>
<!-- card-body -->
</div>
<!-- card -->
</div>
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have a php script that executes a query against a mySQL database and returns an array. Here is the output:
[["185","177","8","10h:43m:54s","http:\/\/localhost\/toastReport\/cd7bf9ae-c21d-4746-bdd9-6934f8e5924e_ed13cfdc-403b-4a82-8f71-0da41a466e62_report\/feature-overview.html"]]
I am using ajax to call the PHP script and am then trying to load the data into a javascript array and then print out different values later in my HMTL page. Here is the javascript script I have in my page header:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function myfunction() {
var automation = [];
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function (jsonData) {
automation = jsonData;
console.log(automation);
}
});
}
</script>
I am trying to use the array data in a card at the top of my page:
<div class="card text-white bg-primary o-hidden h-100">
<a class="card-header text-white clearfix small z-1" href="#">
<span class="float-left">COX Sanity Run </span>
</a>
<div class="card-body">
<div class="card-body-icon">
<i class="fa fa-fw fa-tasks"></i>
</div>
<div class="mr-5">Total tests: <script type="text/javascript"> myfunction(); </script></div>
<div class="mr-5">Failed tests:</div>
<div class="mr-5">Passed tests:</div>
<span class="float-right"><div class="mr-5">Run Time:</div></span>
</div>
<a class="card-footer text-white clearfix small z-1" href="http:\//localhost\/toastReport\/cd7bf9ae-c21d-4746-bdd9-6934f8e5924e_ed13cfdc-403b-4a82-8f71-0da41a466e62_report\/feature-overview.html">
<span class="float-left">View Details</span>
<span class="float-right">
<i class="fa fa-angle-right"></i>
</span>
</a>
I am confused on how to make this work and any info or links to pages with a guide on how to make this work would be greatly appreciated. Thanks!
Simply use the data when it's returned from ajax().
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/sanityTestDataCox.php",
success: function (data) {
console.log(data);
var total = data[0];
var failed = data[1];
var passed = data[2];
var time = data[3];
document.getElementById('total').innerHTML = "Total tests: " + total;
document.getElementById('failed').innerHTML = "Failed tests: " + failed;
document.getElementById('passed').innerHTML = "Passed tests: " + passed;
document.getElementById('runTime').innerHTML = "Run Time: " + time;
}
});
}
HTML
<div id="total" class="mr-5">Total tests: <script type="text/javascript"> myfunction(); </script></div>
<div id="failed" class="mr-5">Failed tests:</div>
<div id="passed" class="mr-5">Passed tests:</div>
<span id="runTime" class="float-right"><div class="mr-5">Run Time:</div></span>
I have this function that returns when an an ajax has been called, however the function returns only the id of the first div in the post and repeats the same id number for the next elements or div tags. However, when the function is used on click with specified $(this) it returns the unique div of the other elements. Please help. Here's the code.
$(document).on("click", ".likeTypeAction", function () {
var reaction_id = $('.likeTypeAction');
var reactionType = $(this).attr("data-reaction");
var reactionName = $(this).attr("original-title");
var rel = $(this).parent().parent().attr("rel");
var x = $(this).parent().parent().attr("id");
var sid = x.split("reaction");
var id_post = sid[1];
var htmlData = '<i class="' + reactionName.toLowerCase() + 'IconSmall likeTypeSmall" ></i>' + reactionName;
var dataString = 'id_post=' + id_post + '&rid=' + reactionType;
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {"done": 1, "id_post": id_post, "rid": reactionType},
beforeSend: function () {
alert(id_post);
},
success: function (data) {
displayReaction();
},
});
});
function displayReaction() {
a = $("#reactionEmoji");
var cls = $(this.a).parent().attr('class');
var n = cls.split("reaction");
var reactionNew = n[1];
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {
"getReaction": 1, "reactionNew": reactionNew
},
beforeSend: function () {
alert(reactionNew);
},
success: function (data) {
}
})
}
myInstance = new displayReaction();
echo '<div id="reaction" class="reaction' . $id_post . '">
<div id="reactionEmoji">nothing</div>
</div>';
echo'<div class="reaction-action">';
echo '<div rel="unlike" c="undefined" id="reaction' . $id_post . '" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType"></i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType"></i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType"></i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);"></span>
<span style="border-color:rgb(255, 255, 255);"></span>
</div>
</div>';
There are a couple issues with your code.
I suppose the PHP code you provided is in some kind of loop : $id_post suggests your looping through some data and printing this HTML for each post.
If it is inside a loop, you are going to have, in your document, for each loop :
<div id="reaction" class="reaction' . $id_post . '">
<div id="reactionEmoji">nothing</div>
</div>
You can't have several HTML elements with the same id.
And since you are using the reactionEmoji id in your displayReaction function, you may want to fix that :
function displayReaction() {
a = $("#reactionEmoji");
var cls = $(this.a).parent().attr('class');
var n = cls.split("reaction");
var reactionNew = n[1];
/* .... */
alert(reactionNew);
}
In the snippet below :
I replaced your PHP code with 3 HTML generated codes
I added some labels to replace your icon (we didn't have your CSS)
I made both divs ids unique
I corrected your displayReaction function so that it takes the id of the reaction you want to display as a parameter.
I'm not sure it does what you want it to do, but it should help you solve your issues.
$(document).on("click",".likeTypeAction",function()
{
var reaction_id = $('.likeTypeAction');
var reactionType=$(this).attr("data-reaction");
var reactionName=$(this).attr("original-title");
var rel=$(this).parent().parent().attr("rel");
var x=$(this).parent().parent().attr("id");
var sid=x.split("reaction");
var id_post =sid[1];
var htmlData='<i class="'+reactionName.toLowerCase()+'IconSmall likeTypeSmall" ></i>'+reactionName;
var dataString = 'id_post='+ id_post +'&rid='+reactionType;
displayReaction(id_post);
/*
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {"done":1, "id_post":id_post, "rid":reactionType},
beforeSend: function(){alert(id_post);},
success: function(data){
},
});*/
});
function displayReaction(id_post){
a = $("#reactionEmoji" + id_post);
var cls = $(this.a).parent().attr('class');
var n = cls.split("reaction");
var reactionNew = n[1];
$.ajax({
url: 'ajaxReaction',
type: "post",
data: {
"getReaction":1,"reactionNew":reactionNew
},
beforeSend: function(){
alert(reactionNew);
},
success: function(data){
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reaction" class="reaction1">
<div id="reactionEmoji1">nothing</div>
<div class="reaction-action">
<div rel="unlike" c="undefined" id="reaction1" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType">like</i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType">Amei</i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType">Haha</i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType">Uau</i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType">Triste</i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType">Grr</i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);;"/>
<span style="border-color:rgb(255, 255, 255);"/>
</div>
</div>
</div>
</div>
<div id="reaction" class="reaction2">
<div id="reactionEmoji2">nothing</div>
<div class="reaction-action">
<div rel="unlike" c="undefined" id="reaction2" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType">like</i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType">Amei</i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType">Haha</i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType">Uau</i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType">Triste</i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType">Grr</i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);;"/>
<span style="border-color:rgb(255, 255, 255);"/>
</div>
</div>
</div>
</div>
<div id="reaction" class="reaction3">
<div id="reactionEmoji3">nothing</div>
<div class="reaction-action">
<div rel="unlike" c="undefined" id="reaction3" class="likeDiv">
<div class="tooltipster-content">
<span class="likeTypeAction" original-title="Like" data-reaction="1">
<i class="likeIcon likeType">like</i>
</span>
<span class="likeTypeAction" original-title="Amei" data-reaction="2">
<i class="ameiIcon likeType">Amei</i>
</span>
<span class="likeTypeAction" original-title="Haha" data-reaction="3">
<i class="hahaIcon likeType">Haha</i>
</span>
<span class="likeTypeAction" original-title="Uau" data-reaction="4">
<i class="uauIcon likeType">Uau</i>
</span>
<span class="likeTypeAction" original-title="Triste" data-reaction="5">
<i class="tristeIcon likeType">Triste</i>
</span>
<span class="likeTypeAction last" original-title="Grr" data-reaction="6">
<i class="grrIcon likeType">Grr</i>
</span>
</div>
<div class="tooltipster-arrow-top tooltipster-arrow" style="">
<span class="tooltipster-arrow-border" style="margin-bottom: -1px; border-color: rgb(222, 222, 222);;"/>
<span style="border-color:rgb(255, 255, 255);"/>
</div>
</div>
</div>
</div>
How to create a new div for each js response?
Message is a JSON containing all the messages sent and received.
this is my JS:
$.get("MessageServlet", function (responseJson) {
$.each(responseJson, function (index, message) {
//code to create a div for each response
});
});
My div is like:
<div id="somediv">
<li class="clearfix">
<div class="message-data align-right">
</div>
<div id ="messagesent" class="message other-message float-right">
Hello
</div>
</li>
</div>
The div should create a message like this
This was the code I tried:
var codeToInsert="<li class="clearfix"><div class="message-data align-right"><span class="message-data-time" >messaggio.timestamp</span> <span class="message-data-name" >You</span> <i class="fa fa-circle me"></i></div><div id ="messagesent" class="message other-message float-right">messaggio.body</div></li>";
var addMessage =document.getElementById('somediv');
addMessage.insertAdjacentHTML('beforeend', codeToInsert);
Your code has one serious flaw. var codeToInsert="<li class="cl... does not escape quotations.
That aside, the answer to your question is:
$.get("MessageServlet", function (responseJson) {
$.each(responseJson, function (index, message) {
$('#somediv').append(`
<li class="clearfix">
<div class="message-data align-right">
<span class="message-data-time">
${message.timestamp}
</span>
<span class="message-data-name" >
You
</span>
<i class="fa fa-circle me"></i>
</div>
<div id ="messagesent" class="message other-message float-right">
${message.body}
</div>
</li>
`);
});
});
The variable codeToInsert not defined correctly, timestamp and body should be added dynamically to codeToInsert
var responseJson = [{
"timestamp": "00001",
"body": "body 001"
}, {
"timestamp": "00002",
"body": "body 002"
}, {
"timestamp": "00003",
"body": "body 003"
}];
var codeToInsert = "";
var addMessage = document.getElementById('somediv');
$.each(responseJson, function(index, message) {
codeToInsert = "<li class='clearfix'><div class='message-data align-right'><span class='message-data-time' >" + message.timestamp + "</span> <span class='message-data-name'>You</span> <i class='fa fa-circle me'></i></div><div id ='messagesent' class='message other-message float-right'>" + message.body + "</div></li>";
addMessage.insertAdjacentHTML('beforeend', codeToInsert);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="somediv">
<li class="clearfix">
<div class="message-data align-right">
</div>
<div id="messagesent" class="message other-message float-right">
Hello
</div>
</li>
</div>
You can test with this JQuery code using the prependmethod:
JQuery:
var messageBody = "Some text",
codeToInsert = '<li class="clearfix"><div class="message-data align-right"><span class="message-data-time" >messaggio.timestamp</span> <span class="message-data-name" >You</span> <i class="fa fa-circle me"></i></div><div id ="messagesent" class="message other-message float-right">'+messageBody+'</div></li>';
var addMessage = $('#somediv');
addMessage.prepend(codeToInsert);
I'm new here and I'm a beginner in programming.
I need help with my weather app. I'm using metaweather api for displaying weather, but i need to display weather for multiple location.
This is how i display weather for only one city, but i dont know how to pass more cities?!
Please help!
Here it's code (HTML)
<main>
<section>
<div class="container">
<div id="main_panel">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/warszawa.jpg" alt="Warszawa">
<span id="warsaw">
<span class="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
</span>
<span class="weather">
<span class="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<span class="weather-icon"></span>
<h3 class="weather-state"></h3>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/berlin.jpg" alt="Berlin">
<span id="berlin">
<span class="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
</span>
<span class="weather">
<span class="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<h3 class="weather-state"></h3>
<span class="weather-icon"></span>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="app">
<img class="img-responsive img-rounded" src="images/lizbona.jpg" alt="Lizbona">
<span id="location">
Unknown
<i class="fa fa-map-marker"></i>
<span class="today">Today</span>
</span>
<span class="weather">
<span id="temperature">
0<sup>°</sup>
<span class="unit">c</span>
</span>
<h3 class="weather-state"></h3>
<span class="weather-icon"></span>
</span>
</div>
</div>
</div>
</div>
</section>
</main>
And here it is JavaScript
var temperature = [];
var cityName = 'warsaw';
var weatherSiteUrl = "http://cors-anywhere.herokuapp.com/https://www.metaweather.com/";
var weatherAPIUrl = weatherSiteUrl + "api/";
var cityLocation = weatherAPIUrl + "location/search/?query=";
var iconUrl = "https://www.metaweather.com/";
function drawWeather() {
$.getJSON(cityLocation + cityName, function(data) {
$.getJSON(weatherAPIUrl + 'location/' + data[0].woeid, function(data) {
$('.location').html(cityName + '<i class="fa fa-map-marker"></i>'); // Name of location
$('.weather-state').html(data.consolidated_weather[0].weather_state_name); //Weather state
temperature[0] = Math.floor(data.consolidated_weather[0].the_temp);
$('.temperature').html(temperature[0] + '<sup>°</sup><span class="unit">c</span>'); // Temperature
var weatherImg = iconUrl + 'static/img/weather/' + data.consolidated_weather[0].weather_state_abbr + '.svg';
$('.weather-icon').html('<img src=' + weatherImg + '>');
});
});
};
drawWeather();
Instead of hardcoding 'warsaw' pass the location to the function
var temperature = [];
var weatherSiteUrl = "http://cors-anywhere.herokuapp.com/https://www.metaweather.com/";
var weatherAPIUrl = weatherSiteUrl + "api/";
var cityLocation = weatherAPIUrl + "location/search/?query=";
var iconUrl = "https://www.metaweather.com/";
function drawWeather(cityName) {
$.getJSON(cityLocation + cityName, function(data) {
$.getJSON(weatherAPIUrl + 'location/' + data[0].woeid, function(data) {
$('.location').html(cityName + '<i class="fa fa-map-marker"></i>'); // Name of location
$('.weather-state').html(data.consolidated_weather[0].weather_state_name); //Weather state
temperature[0] = Math.floor(data.consolidated_weather[0].the_temp);
$('.temperature').html(temperature[0] + '<sup>°</sup><span class="unit">c</span>'); // Temperature
var weatherImg = iconUrl + 'static/img/weather/' + data.consolidated_weather[0].weather_state_abbr + '.svg';
$('.weather-icon').html('<img src=' + weatherImg + '>');
});
});
};
Then instead of drawWeather(); run the function using drawWeather('warsaw');, drawWeather('berlin');,...