i want to use multiple XMLHttpRequest,
However i used this code that 1st XMLHttpRequest was successfully run but the second one is not running, its simply executing the else block from code Some error occured
so help me to get this issue resolve
HTML File
<div class="container my-3">
<div class="row">
<div class="col-6">
<h3>Top News <span class="badge bg-dark">by OnDemand News</span></h3>
<hr>
<div class="accordion" id="newsAccordion"></div>
</div>
<div class="col-6">
<h3>Top News <span class="badge bg-dark">by OnDemand News</span></h3>
<hr>
<div class="accordion" id="newsAccordion1"></div>
</div>
</div>
</div>
JavaScript File
// Initialize the news api parameters
let source = 'bbc-news';
let apiKey = '---';
// Grab the news container
let newsAccordion = document.getElementById('newsAccordion');
// create an Ajax get request
const xhr = new XMLHttpRequest();
xhr.open('GET', `https://newsapi.org/v2/top-headlines?sources=${source}&apiKey=${apiKey}`, true);
// What to do when response is ready
xhr.onload = function () {
if (this.status === 200) {
let json = JSON.parse(this.responseText);
let articles = json.articles;
// console.log(articles);
let newsHtml = "";
articles.forEach(function(element, index) {
// console.log(element, index);
let news = `<div class="card">
<div class="card-header" id="heading${index}">
<h2 class="mb-0">
<button class="btn btn-link collapsed btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse${index}" aria-expanded="true" aria-controls="collapse${index}">
<b>${element["title"]}</b>
</button>
</h2>
</div>
<div id="collapse${index}" class="collapse" aria-labelledby="heading${index}" data-parent="#newsAccordion">
<div class="card-body">
${element["content"]}. Read more about this News
</div>
</div>
</div>`
newsHtml += news;
});
newsAccordion.innerHTML = newsHtml;
}
else {
console.log("Some error occured")
}
}
xhr.send();
// Initialize the news api parameters
let source1 = 'times-of-india';
let apiKey1 = '---';
// Grab the news container
let newsAccordion1 = document.getElementById('newsAccordion1');
// create an Ajax get request
const xhr1 = new XMLHttpRequest();
xhr1.open('GET', `https://newsapi.org/v2/top-headlines?sources=${source1}&apiKey=${apiKey1}`, true);
// What to do when response is ready
xhr1.onload = function () {
if (this.status === 300) {
let json = JSON.parse(this.responseText);
let articles = json.articles;
// console.log(articles);
let newsHtml1 = "";
articles.forEach(function(element, index) {
console.log(element, index);
let news1 = `<div class="card">
<div class="card-header" id="heading${index}">
<h2 class="mb-0">
<button class="btn btn-link collapsed btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse${index}" aria-expanded="true" aria-controls="collapse${index}">
<b>${element["title"]}</b>
</button>
</h2>
</div>
<div id="collapse${index}" class="collapse" aria-labelledby="heading${index}" data-parent="#newsAccordion">
<div class="card-body">
${element["content"]}. Read more about this News
</div>
</div>
</div>`
newsHtml1 += news1;
});
newsAccordion1.innerHTML = newsHtml1;
}
else {
console.log("Some error occured")
}
}
xhr1.send();
Related
I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code
const renderNote = data => {
const postListRef = ref(db, 'Notes/' +data.key);
console.log(data.key)
const newPostRef = push(postListRef);
var status = 'Pending'
var title = 'new note'
var date = '29-4-2022'
var note = 'newly added note'
let card =
`<div id="single-card" class="col-lg-4 col-md-3" data-id=${data.key} ><!--outer layer of single card-->
<div class="card card-body"><!--card body-->
<p class="badge" id="status" style="background-color: rgb(0, 81, 81);">${status}</p>
<span class="side-stick"></span> <!--side-stick color-->
<!-- note title -->
<h5 class="note-title text-truncate w-75 mb-0" >${title}<i class="point fa fa-circle ml-1 font-10"></i></h5><!--fa fa-circle is for the dot dot dot(continuity)-->
<p class="note-date font-12 text-muted mt-0">${date}</p>
<!--note description-->
<div class="note-content">
<p class="note-inner-content text-muted" >${note}<i class="point fa fa-circle ml-1 font-10"></i></p>
</div>
<button class="btn btn-del">Delete${data.key}</button>
<div id="actions" >
</div>
</div>
</div>`
prod.innerHTML += card;
const btnDelete = document.querySelector(`[data-id='${data.key}'] .btn-del`);
console.log(btnDelete);
btnDelete.addEventListener("click",()=>{
console.log('deleting');
});
}
EventListener is not working. But when I print the btnDelete(console.log(btnDelete);) it is printing correctly. But the eventlistener is not workingDoes anybody know what is wrong with the code?
Why don´t you use onclick in HTML?
<button onclick="console.log('deleting');" class="btn btn-del">Delete${data.key}</button>
You can even call a delete Function like that:
HTML:
<button onclick="deleteCard(${data.key})" class="btn btn-del">Delete${data.key}</button>
JavaScript:
function deleteCard(key) {
console.log(`Delete Card with key: ${key}`)
}
I am looping through an array of objects (rendering data coming from an API) via Vanilla JavaScript (DOM). And I want to pass more than one value (Product ID, Product Name .. etc) to a function triggered in the event of a click button. saveProduct(${proInfo}) as it shown below (proInfo is an object).
The problem is I have been able to pass ONLY ONE value to this function. I tried to pass the variable as an object but it didn't work and got the error (index):1 Uncaught SyntaxError: Unexpected end of input
var shopNcounter = 0;
const baseURL = "***";
const idsArray = [];
const divRow = document.querySelector(".row");
const buttonContainer = document.querySelector("#button-container")
//create column div
function createDiv() {
const div = document.createElement("div");
div.classList.add("col-xl-3");
div.classList.add("col-md-6");
div.classList.add("col-sm-12");
return div;
}
async function getData(id) {
shopNcounter ++;
console.log(shopNcounter);
if(shopNcounter > 5) {
getProInfo(id);
return;
} else if (shopNcounter > 4) {
getProducts(id);
return;
}
idsArray.push(id);
console.log(id);
console.log(idsArray);
if(idsArray.length > 10) {
idsArray.splice(0,6);
}
const api = `**shop=${shopNcounter}&id=${id}`;
try {
const response = await fetch(api);
const data = await response.json();
divRow.innerHTML = "";
if (shopNcounter > 1) {
buttonContainer.innerHTML = `
<button class="btn btn-lg btn-warning px-5" onclick="moveBack(${idsArray[idsArray.length-2]})">رجوع</button>
`
} else {
buttonContainer.innerHTML = "";
}
//mapping through data
data.map(item => {
const div = createDiv();
divRow.appendChild(div);
div.innerHTML+=`
<div class="card text-center h-100 mx-auto border-white shadow" style="width: 16rem;">
<img src="${baseURL + item.image}" class="card-img-top mx-auto" alt="...">
<div class="card-body">
<a onclick=handleClick(${item.id}) class="btn btn-outline-dark px-5 mt-4" id="goToItemButton">${item.name}</a>
</div>
</div>
`;
});
} catch(error) {console.log(error);}
}
getData(0);
async function getProducts(id) {
//shop > 4 = 5
console.log("Get Product is being executing");
const apiProducts = `**product?id=${id}`;
try {
const response = await fetch(apiProducts);
const data = await response.json();
console.log(data);
divRow.innerHTML = "";
//mapping through data
data.map((item, index) => {
var proInfo = {
pid: item.PID,
pname: item.PName
}
const div = createDiv();
divRow.appendChild(div);
div.innerHTML+=`
<div class="card text-center h-100 mx-auto border-white shadow" style="width: 16rem;">
<img src="${baseURL + item.image}" class="card-img-top mx-auto" alt="...">
<div class="card-body">
<h5>${item.PName}</h5>
<p class="product-price">Price: ${item.PSelPrice}</p>
<a onclick=saveProduct(${item.PID}) class="btn btn-danger px-5 mt-4"> Add to Card </a>
</div>
</div>
`;
});
} catch(error) {
console.log(error);
}
}
function moveBack(id) {
shopNcounter = shopNcounter -2;
getData(id);
}
function handleClick(id) {
let clickedButton = document.querySelector("#goToItemButton");
clickedButton.onclick = "";
getData(id);
}
function saveProduct(g) {
console.log(g);
}
your code should not result in the error you see
However you can make your life easier using delegation
do this
document.getElementById("container").innerHTML = data.map((item,i) => `<div class="card text-center h-100 mx-auto border-white shadow" style="width: 16rem;">
<img src="${baseURL + item.image}" class="card-img-top mx-auto" alt="...">
<div class="card-body">
<h5>${item.PName}</h5>
<p class="product-price">Price: ${item.PSelPrice}</p>
<a data-id="${i}" class="add btn btn-danger px-5 mt-4"> Add to Card </a>
</div>
</div>`).join("");
Have this
document.getElementById("container").addEventListener("click",function(e) {
const tgt = e.target.closest("a");
if (tgt && tgt.className.contains("add")) {
const item = data[tgt.dataset.id]
// here you can add the item
saveProduct({pid: item.PID,pname: item.PName })
}
})
I need to add a Delete button on my cards, and this is the error I get.
Try moving the deleteButton() function outside of the getComments() function.
function getComments() {
fetch(commentsUrl, { method: "GET" })
.then((res) => res.json())
.then((data) => {
data.forEach(function (post) {
const randomId = Math.random().toString().substr(2, 8);
const comment = document.createElement("div");
comment.innerHTML = `
<div class="card" id="${randomId}">
<div class="card text-center bg-info" style="width: 18rem;">
<div class="card-body ">
<h5 class="card-user ">${post.user}</h5>
<h6 class="card-id mb-2 text-muted">Id: ${post.id}</h6>
<p class="card-content">"${post.content}" </p>
<p class="card-date">${post.date}<p>
<button type="button" class="btn btn-primary btn-sm">Edit</button>
<button type="button" class="btn btn-danger btn-sm" id="deleteButton" onclick="deleteButton('${randomId}')">Delete</button>
</div>
</div>
</div>`;
document.getElementById("content").append(comment);
});
});
}
function deleteButton(id) {
var del = document.getElementById(id);
del.remove();
}
window.onload = getComments();
Functions in Javascript create a scope so functions defined within functions can only be called within that function.
You are creating a HTML element, which will try to call deleteButton() from the global scope and doesn't have access to the function declaration within getComments().
EDIT: fixed some more code
This is how it was asked to be done..
I find it above my knowledge, but in case anybody is curios, I thought I could share it.
const commentsUrl = "http://localhost:8080/comments";
let comments = [];
function getComments() {
fetch(commentsUrl, { method: "GET" })
.then((res) => res.json())
.then((data) => {
comments = data;
renderComments(comments);
});
}
const renderComments = (comments) => {
const commentsContainer = document.getElementById("content");
commentsContainer.innerHTML = "";
comments.forEach(function (post) {
const comment = document.createElement("div");
comment.innerHTML = `
<div id=${post.id} class="card">
<div class="card text-center bg-info" style="width: 18rem;">
<div class="card-body ">
<h5 class="card-user ">${post.user}</h5>
<h6 class="card-id mb-2 text-muted">Id: ${post.id}</h6>
<p class="card-content">"${post.content}" </p>
<p class="card-date">${post.date}<p>
<button type="button" class="btn btn-primary btn-sm">Edit</button>
<button type="button" class="btn btn-danger btn-sm" id="deleteBtn" onclick='remove(${post.id})'>Delete</button>
</div>
</div>
</div>`;
commentsContainer.append(comment);
});
};
function remove(id) {
fetch(`${commentsUrl}/${id}`, { method: "DELETE" }).then((comment) => {
const index = comments.findIndex(
(currentComment) => currentComment.id === comment.id
);
comments.splice(index - 1, 1);
renderComments(comments);
});
}
getComments();
Good day everyone please am trying to create a movie project using just javacript and ajax without fetch,jquery etc, i have a bug, if i enter a word in the inputbox and submit to retrieve an array of movies from the api for the first time it works but if i try searching for other movies again it doesn't work accept i reload the page. please doee anyone have a solution to this bug? thanks
document.getElementById("searchForm").addEventListener("submit", loadMovies);
function loadMovies(e) {
let input = document.getElementById("searchText");
const xhr = new XMLHttpRequest();
xhr.open("GET", `https://api.themoviedb.org/3/search/movie?api_key=b94d8dbb7dcd23af16414e00a058c9ad&language=en-US&query=${input.value}`, true);
xhr.onload = function() {
if (this.status === 200) {
let movies = document.getElementById("movies");
let res = JSON.parse(this.responseText);
res.results.forEach(function(movie) {
movies.innerHTML += `
<div class="col-md-3">
<div class="card bg-dark">
<div class="card-block">
<img src="https://image.tmdb.org/t/p/w500${movie.poster_path}" class="img-fluid">
<h4>${movie.title}</h4>
Movie Details
</div>
</div>
</div>
`;
});
} else {
console.log("Movie not found");
}
}
xhr.send();
e.preventDefault();
}
<div class="container mt-5">
<div class="jumbotron bg-dark">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movie....">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>
I didn't realize there was many results you wanted to display. In that case use += off course and just empty the result beforehand movies.innerHTML = ''
document.getElementById("searchForm").addEventListener("submit", loadMovies);
function loadMovies(e) {
let input = document.getElementById("searchText");
const xhr = new XMLHttpRequest();
xhr.open("GET", `https://api.themoviedb.org/3/search/movie?api_key=b94d8dbb7dcd23af16414e00a058c9ad&language=en-US&query=${input.value}`, true);
xhr.onload = function() {
if (this.status === 200) {
let movies = document.getElementById("movies");
let res = JSON.parse(this.responseText);
movies.innerHTML = '';
res.results.forEach(function(movie) {
movies.innerHTML += `
<div class="col-md-3">
<div class="card bg-dark">
<div class="card-block">
<img src="https://image.tmdb.org/t/p/w500${movie.poster_path}" class="img-fluid">
<h4>${movie.title}</h4>
Movie Details
</div>
</div>
</div>
`;
});
} else {
console.log("Movie not found");
}
}
xhr.send();
e.preventDefault();
}
<div class="container mt-5">
<div class="jumbotron bg-dark">
<h3 class="text-center">Search For Any Movie</h3>
<form id="searchForm">
<input type="text" class="form-control" id="searchText" placeholder="Search Movie....">
</form>
</div>
</div>
<div class="container">
<div id="movies" class="row"></div>
</div>