How to send data from API to another HTML file - javascript

Im using a TMDB API to search for movies and add them to a watchlist.
In this javascript function im getting movie details based on user input and rendering the results to html using bootstrap.
const searchMovie = async (searchInput) => {
try {
axios.get(`https://api.themoviedb.org/3/search/movie?api_key={API_KEY}&language=en-US&query=${searchInput}&page=1&include_adult=false `)
.then((response) => {
console.log(response);
let movies = response.data.results;
let displayMovies = '';
$.each(movies, (index, movie) => {
displayMovies += `
<div class="col-md-3">
<div class="well text-center">
<img src="https://image.tmdb.org/t/p/original${movie.poster_path}">
<h5>${movie.title}</h5>
<h4>${movie.release_date}<h4>
<a class="btn btn-primary" href="#">Add to watchlist</a>
</div>
</div>
`;
});
$('#movies').html(displayMovies);
})
}catch(error) {
console.log(error)
}
}
I have another html file called watchlist.html that i want to send the movie selected from the search results to that file and build a watchlist.

Please try this one before stringify
var obj = JSON.parse(movie);
localStorage.setItem('selectedMovie', JSON.stringify(obj));

Related

I want to display a pokemon image that I get from the API, but I only get the url of the image and I don't know how to do it

I'm new to programming and need some help.
I successfully get a random pokemon from the API and get its data: id, name and picture.
The most important thing for me is to show the image of that pokemon in the modal I made.
The problem is that I get the url of the image and I don't know how to display it
In addition, I would like someone to help me so that when I enter the name of that pokemon in the input, it can check for me and if it is identical, I have some kind of alert or message feedback that I guessed.
Thank you very much in advance
1]1
This is function in store.js to get one Pokemon from Api :
async getOnePokemon() {
try {
let id = Math.floor(Math.random() * 151) + 1;
let response = await axios.get(`${apiLink}/pokemon/${id}`)
if(response.data){
let pokemon = {
id: response.data.id,
name: response.data.name,
image: response.data.sprites.front_default
}
return pokemon
}
} catch (error) {
console.log(error)
}
},
this is function that I call to get pokemon from store.js:
async function GetPokemons() {
try {
let response = await PokemonStore.getOnePokemon();
pokemonId.value = response;
console.log(pokemonId.value)
} catch (error) {
throw error;
}
}
this is header component where i have my modal where I want to show the image of pokemon where is {{ pokemonId.image }}
<el-dialog v-model="game" title="Who's that pokemon?" width="35%" height="50%" center>
<div class="modalHeader">
{{ pokemonId.image }}
</div>
<div class="footer">
<div class="inputDiv">
<input class="pokeNameInput" type="text" placeholder="Search pokemon" />
</div>
<span>
<el-button id="submitBtn" #click="LogInModalVisible = false">Submit</el-button>
<el-button id="skipBtn" #click="LogInModalVisible = false;">Skip
<el-icon class="el-icon--right"><ArrowRight /></el-icon></el-button>
<el-button id="pokedexGameBtn" #click="LogInModalVisible = false">Pokedex</el-button>
</span>
</div>
</el-dialog>
You need to put it in img tag
<img :src="pokemonId.image" />

Post from React to Ruby (not rails)

I have created a Twitter clone using Ruby in the backend and React in the front end. I have managed to fetch all tweets and I am trying to post a tweet. It is connected but it is posting nothing. Literally an empty tweet.
Below is the React code.
const TweetsFeed = () => {
const [tweet, setTweet] = useState("");
const tweetChangeHandler = (event) => {
event.preventDefault();
setTweet(event.target.value);
};
const postTweet = async () => {
const postRequest = {
method: "POST",
params: tweet,
};
fetch("http://127.0.0.1:9292/tweets", postRequest).then((response) =>
response.json().then((data) => {
console.log(data);
})
);
fetchTweets();
};
Below is the Ruby route and create method code
post '/tweets' do
Tweet.create(tweet: params[:tweet])
end
def self.create(tweet:)
result = DatabaseConnection.query("INSERT INTO tweets (tweet) VALUES ('#{tweet}') RETURNING id, tweet;")
Tweet.new(
id: result[0][0],
tweet: result[0][1]
)
end
Below is the form
<form className="new-tweet-form" action="/tweets" method="post">
<div className="pp-input">
<img src="./images/pp1.jpg" alt="" />
<input
type="text"
name="tweet"
placeholder="What's happening?"
onChange={tweetChangeHandler}
/>
</div>
<div className="extras-button">
<Extras />
<Button type="button" onClick={postTweet}>
Tweet
</Button>
</div>
</form>
It does post to the database, but an empty tweet everytime.

How do I display every products from a SQLite database on my website

I'm trying to make a web shop with a SQLITE database for a school project. The problem i'm currently encountering is that I can't manage to display all the products from the database on the website. To do so, I'm not allowed to use PHP so I need to do it through javascript. To generate each items, I'm using Mustache.
Here is my code :
HTML :
{{#items}}
<div class="col-12 col-md-6 col-xl-4">
<a class="shop-item" href="#">
<div class="item-details">
<div>
<h5> {{Product_Name}}</h5>
<p>{{Product_Desc}}</p>
</div>
<div class="item-price"><span class="unit">$</span>{{Product_Price}}</div>
</div>
<!-- <img src="#" alt="product"> -->
</a>
</div>
{{/items}}
Controller :
module.exports = {
'render' : render,
}
function getProduct(){
const db = require('./../models/models').shopping;
return db.getItems();
}
async function render(req, res){
const products = await getProduct();
res.status(200).render('shopping', {
//tableProduct : true,
items : products
})
}
Model :
const db = require('./../../bin/dataBase');
const SELECT_PRODUCT_SQL ="SELECT Product_Price, Product_Name, Product_Desc FROM Product";
function getItems(){
return new Promise((resolve, reject) =>{
db.all(SELECT_PRODUCT_SQL, (err,row) =>{
if(err) return reject();
if(row) return resolve(row);
else return reject();
})
})
}
module.exports = {
'getItems' : getItems
}
The error I'm currently having is : Error : UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getItems' of undefined.

How to make a post request to a protected Laravel API route with JavaScript using the API token?

Description
I have a table, where i collect values from checkboxes with JavaScript. This values should be send to a protected API route in a Laravel backend.
I use the standard Laravel auth setup (out of the box).
Question
What do I have to send with the JavaScript post request for authentication and how do i do that? Can i add a auth token or something like that to the headers?
At the moment i get the reponse:
"This action is unauthorized".
exception: "Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException"
Edit
At the current point of my research the api token seems to be a simple solution for my case. But i can't figure out how to attach the api token to the JavaScript post request.
Thats the JavaScript function for collecting the values storing them in objects.
import SaveData from "../api/SaveData";
export default async function SaveMultipleReports() {
const table = document.getElementById("reports-dashboard");
const rows = table.querySelectorAll("div[class=report-tr]");
let reports = [];
for (const row of rows) {
const checkbox_visible = row.querySelector("input[name=visible]")
.checked;
const checkbox_slider = document.querySelector(
"input[name=show_in_slider]"
).checked;
const report = {
id: row.id,
visible: checkbox_visible,
show_in_slider: checkbox_slider
};
reports.push(report);
}
console.log(reports);
const response = await SaveData("/api/reports/update", reports);
console.log(response);
}
And that is the SavaData function:
export default async function SaveData(api, data) {
const token = document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content");
const url = window.location.origin + api;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": token,
Accept: "application/json"
},
body: JSON.stringify(data)
});
const result = await response.json();
return result;
}
And thats the line in the api.php:
Route::middleware("can:administration")->post("reports/update", "ReportsController#UpdateAll");
The whole repo is here.
Thanks for your time in advance :)
Edit 2
For now i managed it without JavaScript. Put all the values, i want to update in form and load a hidden input for the ID of every object (the ID is needed for the controller afterwards).
Thanks to this post.
{!! Form::open(["route" => ["admin.reports.multiupdate"], "method" => "PUT", "class" => "report-table"]) !!}
... // some HTML
#foreach ($reports as $report)
<div class="report-tr">
<input type="hidden" name="reports[{{$loop->index}}][id]" value="{{$report->id}}">
<div class="td-name">
<p class="td-text">{{$report->name}}</p>
</div>
<div class="td-flex">{{$report->body}}</div>
<div class="tr-wrapper">
<div class="checkbox-visible">
<div class="checkbox-container">
<input class="checkbox" type="checkbox" name="reports[{{$loop->index}}][visible]" value="1" checked>
<span class="checkmark"></span>
</div>
<label class="table-label" for="visible">Sichtbar</label>
</div>
<div class="checkbox-slider">
<div class="checkbox-container">
<input class="checkbox" type="checkbox" name="reports[{{$loop->index}}][show_in_slider]" value="1"
{{($report->show_in_slider == 1 ? "checked" : "")}}>
<span class="checkmark"></span>
</div>
<label class="table-label" for="show_in_slider">Im Slider</label>
</div>
<div class="td-buttons">
...
#endforeach
<button class="floating-save">
#svg("saveAll", "saveAll")
</button>
{!! Form::close() !!}
And a snippet from the Controller:
public function MultipleUpate(ReportUpdate $request)
{
$reports = $request->input("reports");
foreach ($reports as $row) {
$report = Report::find($row["id"]);
// giving the checkbox 0, if it isn't checked
$isVisible = isset($row["visible"]) ? 1 : 0;
$inSlider = isset($row["show_in_slider"]) ? 1 : 0;
$report->visible = $isVisible;
$report->show_in_slider = $inSlider;
$report->new = false;
if ($report->save()) {
$saved = true;
}
}
if ($saved == true) {
$request->session()->flash("success", "Ă„nderungen gespeichert!");
} else {
$request->session()->flash("error", "Das hat nicht geklappt!");
}
return back();
The ReportUdpate function contains only that:
public function authorize()
{
return true;
}
public function rules()
{
return [
"visible" => "nullable",
"show_in_slider" => "nullable"
];
}
You are talking about authentication but using an authorization middleware. There is a difference between the two.
Read about it here: https://medium.com/datadriveninvestor/authentication-vs-authorization-716fea914d55
With that being said, what you are looking for is an authentication middleware that protects your routes from unauthenticated users. Laravel provides a middleware called Authenticate out of the box for this specific purpose.
Change your route to be like so:
Route::middleware("auth")->post("reports/update", "ReportsController#UpdateAll");

Json data not rendering to the DOM

so I'm trying to create a web app that when a user inputs a number from 0 to 50 it renders that quantity of images of dogs. If nothing is imputed it defaults to 3. Right now fetch is retrieving the data but I can't seem to render it. This is the html for it:
<div class="container">
<h1>Dog API: Display Multiple Random Dog Images</h1>
<form action="#" class="js-search-form">
<label for="query"></label>
<input required type="text" class="js-query" value="3"">
<button class="js-submit" type="submit">Search</button>
</form>
<section class="results hidden js-results">
<!--<img class="results-img" alt="placeholder">-->
</section>
</div>
and this is the Javascript for it:
function getDogImages(query) {
fetch(`https://dog.ceo/api/breeds/image/random/${query}`)
.then(response => response.json())
.then(responseJson => {
console.log(responseJson)
return responseJson
})
.then(responseJson => displayResults(responseJson))
.catch(error => alert('Something went wrong. Try again later.'));
}
function displayResults(responseJson) {
return `
<div>
<h2>Here are your dog pictures</h2>
<img src="${responseJson.answers}" class="results-img">
</div>
` ;
}
function displayDogSearchData(data) {
const results = data.items.map((item, index) => displayResults(item));
$('.js-results').html(results);
$('.results').removeClass('hidden');
}
function listenToInput() {
$('.js-search-form').submit(event => {
event.preventDefault();
const queryTarget = $(event.currentTarget).find('.js-query');
const query = queryTarget.val();
queryTarget.val("3")
getDogImages(query, displayDogSearchData);
});
}
$(function() {
console.log('App loaded! Waiting for submit!');
listenToInput();
});
This is the repl.it link if you want to see it https://repl.it/#GianinaSkarlett/DISPLAY-MULTIPLE-RANDOM-DOG-IMAGES-MVP
You're code is fairly close - only a few minor adjustments were needed to get it to work. Consider the code sample below (with documentation) as one option to resolve your issue:
/*
Add displayCallback parameter, which is called to perform
html/dom update on success
*/
function getDogImages(query, displayCallback) {
fetch(`https://dog.ceo/api/breeds/image/random/${query}`)
.then(response => response.json())
.then(responseJson => {
console.log(responseJson)
return responseJson
})
.then(responseJson => displayCallback(responseJson))
.catch(error => alert('Something went wrong. Try again later.'));
}
function displayResults(responseJson) {
/*
Update the code below to insert responseJson directly as image src
*/
return `
<div>
<h2>Here are your dog pictures</h2>
<img src="${responseJson}" class="results-img">
</div>
` ;
}
function displayDogSearchData(data) {
/*
Access message from data, as per API response format
*/
const results = data.message.map((item, index) => displayResults(item));
$('.js-results').html(results);
$('.results').removeClass('hidden');
}
function listenToInput() {
$('.js-search-form').submit(event => {
event.preventDefault();
const queryTarget = $(event.currentTarget).find('.js-query');
const query = queryTarget.val();
queryTarget.val("3")
/*
Add displayDogSearchData as second argument to getDogImages
as per callback above
*/
getDogImages(query, displayDogSearchData);
});
}
$(function() {
console.log('App loaded! Waiting for submit!');
listenToInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="container">
<h1>Dog API: Display Multiple Random Dog Images</h1>
<form action="#" class="js-search-form">
<label for="query"></label>
<input required type="text" class="js-query" value="3"">
<button class="js-submit" type="submit">Search</button>
</form>
<section class="results hidden js-results">
<!--<img class="results-img" alt="placeholder">-->
</section>
</div>

Categories