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>
Related
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();
function ispisProizvoda(nizProizvoda){
// console.log(nizProizvoda)
let html = "";
let divIspis = document.querySelector("#ispis-proizvoda");
if(nizProizvoda.length == 0){
html = `<div class="row">
<div class="col-12">
<p class="alert alert-danger">Trenutno nema proizvoda.</p>
</div>
</div>`;
}
else{
for(let objProizvod of nizProizvoda){
html += `<div class="row my-3 border">
<div class="col-4">
<img src="${objProizvod.slika}" alt="${objProizvod.naziv}" />
</div>
<div class="col-8">
<h2>${objProizvod.naziv}</h2>
<p>${ispisNaziva(objProizvod.kategorijaID, kategorije)}</p>
<p class="alert alert-primary">${ispisNaziva(objProizvod.brendID, brendovi)}</p>
<hr />
${ispisDostave(objProizvod.besplatnaDostava)}
<div class="popust">
<div class="cena">
**${shipping(objProizvod.price)}**
</div>
</div>
<div class="specifikacije pt-4">
<p>Specifikacije</p>
<ul>
</ul>
</div>
</div>
</div>`
}
}
divIspis.innerHTML = html;
}
function shipping(getPrice){
let html = "";
if(dostava){
html = `<p class="alert alert-success">Besplatna dostava</p>`;
}
else{
html = `<p class="alert alert-danger">Nema besplatne dostave</p>`;
}
return html;
}
I have a problem, function call shipping() is not senind any data, if I console log getPrice in function it says it is undefined, I tested varable in function call and has value, so that is not the problem.I used ajax to fetch data and data is stored in local storage, I don't know why this function is not working. Other functions are working. Is it beacuse I called function before it is declared?
Hi I am using django and Vue to make an webapp. I am rendering data using v-for and fetching the data from a restful API using XMLHttprequest
This is my custom js file. I am not using Vue CLI I am using a CDN:
$(document).ready(function () {
function fetchData(){
Vue.component('postcontainer', {
props:['obj'],
template:
`<div>
<div v-for="data in obj" class="ui mt-3 card">
<div class="content">
<div class="right floated meta">{{data.date_posted}}</div>
<img class="ui avatar image" src="https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_960_720.jpg">
{{data.author}}
</div>
<div v-if="data.image" class="image">
<img v-bind:src="[[data.image]]">
</div>
<div v-if="data.video">
<video controls v-bind:src="[[data.video]]" class="embed-responsive"></video>
</div>
<div class="content">
<div v-if="data.title">
<a class="text-dark" :href="data.id"><h3 class="header">{{data.title}}</h3></a>
</div>
<div class="description my-2">
<div v-if="data.caption">
<a class="text-dark" :href="data.id"><p>{{data.caption}}</p></a>
</div>
</div>
</div>
<div class="extra content">
<span class="right floated">
<i class="heart outline like icon"></i>
17 likes
</span>
<a :href="data.id"><i class="comment icon"></i></a>
</div>
</div>
</div>
`
})
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var app = new Vue({
el: '#postCard',
component:['postconatiner'],
data: {
obj: JSON.parse(this.responseText),
}
})
}
}
xhr.open('GET', '/data/', true);
xhr.LOADING
xhr.send()
}
fetchData()
});
I want add an additional url before data.id example - ":href = 'detail/data.id'". My problem is when I try to add this the url becomes 'localhost:8000/NaN'. Please some help me. Also I want to if it's the right way to render html using VueJS.
Use the binded property href like this:
:href="'details/'+data.id"
I want the button with the id #show-text-area execute the postButton(); function only once so it won't create a second elements whenever clicked (i want it to create it for only one time and won't work again until clicked another button).
Hope my question was clear enough.
HTML
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post" id="post">
<button onclick="postButton();">Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>
Javascript
let postButton = function() {
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
}
You could disable the button after activation, this has the benefit of informing the user that further clicks won't do anything.
let postButton = function() {
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
document.getElementsByTagName("button")[0].disabled = true;
}
Otherwise you could simply have the function short-circuit if it has already been called.
// alreadyPosted is scoped outside of the function so it will retain its value
// across calls to postButton()
let alreadyPosted = false;
let postButton = function() {
// do nothing if this isn't the first call
if (alreadyPosted) { return; }
// mark the function as called
alreadyPosted = true;
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
document.getElementsByTagName("button")[0].disabled = true;
}
The following works.
let postButton = function(event) {
event.target.disabled = true;
let textarea = document.createElement('textarea');
textarea.setAttribute('class', 'post-data');
textarea.setAttribute('placeholder', 'Text (optional)');
document.querySelector('.post-content').appendChild(textarea);
};
document.getElementById('post').addEventListener('click', postButton);
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post" id="post">
<button>Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>
You can also use hide show function on textarea if you do not want to create one.
let postButton = function() {
let d = document.getElementById('post_data').style.display;
if(d=='none'){
document.getElementById('post_data').style.display = 'block';
}
}
document.getElementById('post_data').style.display = 'none';
document.getElementById('post_btn').addEventListener('click', postButton);
<div id="post-creator" class="creator-container">
<div class="post-type">
<div class="text-post">
<button id="post_btn">Post</button>
</div>
<div class="media-post">Image & Video</div>
<div class="link-post">Link</div>
</div>
<div class="post-title">
<input type="text" class="title-text" name="post-title" placeholder="Title">
</div>
<div class="post-content">
<textarea class="post-data" id="post_data" placeholder="Text (optional)"></textarea>
</div>
<div class="post-footer">
<div class="spoiler">Spoiler</div>
<div class="nsfw">NSFW</div>
<button class="post">post</button>
</div>
</div>
I have developed one to one chat with ajax and php now please can any one tell me how can I upload a file using move_uploaded_file function in php. I am getting file variable doc = document.getElementById('doc').value; but files in not uploading and fake path address showing
JavaScript
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type ="text/javascript">
function setfilename(val){
var fileName = val.substr(val.lastIndexOf("\\")+1, val.length);
document.getElementById("msg").value = fileName;
document.getElementById("msg").readOnly = true;
}
function getmsg(){
document.getElementById("msg").readOnly = false;
lol = document.getElementById('msg').value;
doc = document.getElementById('doc').value;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("suggestion").innerHTML=xmlhttp.responseText;
document.getElementById('msg').value = '';
var msgList = document.getElementById("mess");
msgList.scrollTop = msgList.scrollHeight;
document.body.scrollTop = document.body.scrollHeight;
}
}
if(lol==''){
xmlhttp.open("GET","chat",true);
xmlhttp.send();
}else{
xmlhttp.open("GET","chat?message="+doc,true);
xmlhttp.send();
}
}
</script>
html
<div id="chat_box" class="chat_window">
<div class="top_menu">
<div class="buttons">
<div class="button close"></div>
<div class="button minimize"></div>
<div class="button maximize"></div>
</div>
<div class="title">Messaging about order-id: ODR-46</div>
</div>
<div id="your_div">
<ul class="messages" id="mess" style="overflow:scroll;" >
<li id="suggestion"></li>
</ul>
</div>
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" onkeydown="if (event.keyCode == 13) document.getElementById('send').click()" id="msg" placeholder="Type your message here..." />
</div>
<a id="send" onclick="return getmsg();">
<input type="file" onchange="setfilename(this.value);" id="doc">
<div class="send_message">
<div class="icon"></div>
<div class="text" >Send</div>
</div>
</a>
</div>
</div>
<div class="message_template">
<div class="avatar"></div>
<div class="text_wrapper">
<div class="text"></div>
</div>
</div>
php code
// move_uploaded_file(get variable from javascript that is doc,'document/');
If you really want to upload file without using move_uploaded_file function,use this instead:You can use this
http://fineuploader.com/
This uploads the files in a directory you specify using chunking.