I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});
Related
I have implemented autocomplete feature using JQuery, but now I wanted to store last 20 searched per inputfield in browser. So, if user when focuses the suggestion will be fetched from the browser. If user types then from Rest API using ajax I am fetching the data.
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'page':1,'size':"10"};
params[id]=request.term;
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url:"http://localhost:5645/search",
data: jsonParams,
headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//const result = new Set()
var result=[];
console.log(id);
console.log(msg.details)
console.log(msg.details.length)
for(var i = 0; i < msg.details.length; i++) {
var obj = msg.details[i];
if(obj!=null && columnMapping[id]!=undefined && obj[columnMapping[id]]!=undefined){
console.log(obj[columnMapping[id]]);
//result.add(obj[columnMapping[id]]);
result.push(obj[columnMapping[id]]);
}
console.log(result);
}
//response(Array.from(result));
response(result);
}
/* error: function() {
response([]);
} */
})
},
select: function(event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
console.log('test');
var item = $("<div>" + item.label + "</div>")
return $("<li>").append(item).appendTo(ul);
};
Above is the jquery code which I am using for autocomplete. So, if no input is there I need to fetch from browser recent search. So, when user types unique search keys should be inserted. How I can store and retrive using javascript.
I am doing the Wikipedia Viewer challenge of freecodecamp and when I am itterating through the pages that are found the first item of the list does not contain a link to the Wikiepdia page. Why is that?
JS Code:
function getData(){
var search = $("#searchBar").val();
var url = baseUrl + '/w/api.php?action=query&format=json&origin=*&list=prefixsearch&psoffset=max&pssearch='+search;
$.ajax( {
url: url,
dataType: 'json',
type: 'GET',
success: function(data) {
var html="";
var entries = data.query.prefixsearch;
console.log(url);
html+="<ul class='items'>";
for(var i=0;i<entries.length;i++){
html+="<li><h3>"+entries[i].title+"</h3><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'</a></li>";
}
html+="</ul>";
$(".entries").html(html);
}
});
}
Html Code:
<div class="entries">
</div>
As James pointed out in comments, your code outputs <a> without a closing > and with no text.
Change:
html+="<li><h3>"+entries[i].title+"</h3><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'</a></li>";
into this:
html+="<li><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'><h3>"+entries[i].title+"</h3></a></li>";
Full Code
function getData() {
var search = $("#searchBar").val();
var url = baseUrl + '/w/api.php?action=query&format=json&origin=*&list=prefixsearch&psoffset=max&pssearch=' + search;
$.ajax({
url: url,
dataType: 'json',
type: 'GET',
success: function(data) {
var html = "";
var entries = data.query.prefixsearch;
console.log(url);
html += "<ul class='items'>";
for (var i = 0; i < entries.length; i++) {
html+="<li><a href='http://en.wikipedia.org/?curid="+entries[i].pageid+"'><h3>"+entries[i].title+"</h3></a></li>";
}
html += "</ul>";
$(".entries").html(html);
}
});
}
I am currently developing a Mobile App using the Movie DB API.
I have currently got the data pulling through but it's being hardcoded to bring up Spiderman from the Database.
Could anyone point me in the right direction? I have attached my code below :)
$(document).on('pageinit', '#home', function(){
// $(document).ready(function(){
console.info('hi');
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
movieName = '&query='+encodeURI('Spiderman'),
key = '&api_key=7b0b1d8b1253e2bbfcd5602f76c52fdb';
$.ajax({
url: url + mode + key + movieName ,
dataType: "jsonp",
async: true,
success: function (result) {
console.dir(result);
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
});
$(document).on('pagebeforeshow', '#headline', function(){
$('#movie-data').empty();
$.each(movieInfo.result, function(i, row) {
if(row.id == movieInfo.id) {
$('#movie-data').append('<li><img src="http://image.tmdb.org/t/p/w92'+row.poster_path+'"></li>');
$('#movie-data').append('<li>Title: '+row.original_title+'</li>');
$('#movie-data').append('<li>Release date'+row.release_date+'</li>');
$('#movie-data').append('<li>Popularity : '+row.vote_average+'</li>');
$('#movie-data').listview('refresh');
}
});
});
$(document).on('vclick', '#movie-list li a', function(){
movieInfo.id = $(this).attr('data-id');
$.mobile.changePage( "#headline", { transition: "slide", changeHash: false });
});
var movieInfo = {
id : null,
result : null
}
var ajax = {
parseJSONP:function(result){
movieInfo.result = result.results;
$.each(result.results, function(i, row) {
console.log(JSON.stringify(row));
$('#movie-list').append('<li><a href="" data-id="' + row.id + '"><img src="http://image.tmdb.org/t/p/w92'+row.poster_path+'"/><h3>' + row.title + '</h3><p>')
})
}
}
Regards
Tom
Spiderman is being hardcoded into the Url here, so you need to obtain the search string, save it in a variable and replace the hardcoded spiderman:
var searchString = 'your_search_string'
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
movieName = '&query='+encodeURI(searchString),
key = '&api_key=7b0b1d8b1253e2bbfcd5602f76c52fdb';
Also if you just want a list of movies not necessarily related to a search string you can try the discover endpoint of Movie DB API http://api.themoviedb.org/3/discover/movie.
Documentation link
I am doing on a instagram api, and I get information from server including user profiles and two more kinds. I want to put the information in a table on html. Each row is related to a username(since I searched for username), and there are profiles and two more things on each row. I am a little confused about how to do that.
here is my code:
var searchUsers = function(query,count){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
data: {
q: query,
count: count,
access_token: access_token,
},
url: "https://api.instagram.com/v1/users/search",
success: function(data) {
// placing the images on the page
console.log(data);
if (data.data.length>0){
var resultShow = $("#users_result");
for (var i in data.data){
resultShow.append("<img src='" + data.data[i].profile_picture + "'></img>");
// var username = "https://www.instagram.com/"+ data.data[i].username;
// console.log(username);
resultShow.append("<a target='_blank' href = 'https://www.instagram.com/"+data.data[i].username+"'>user profile</a>");
// var id = data.data[i].id;
// console.log(id);
$.ajax({
url: 'https://api.instagram.com/v1/users/' + data.data[i].id + '/media/recent/',
type: "GET",
dataType: "jsonp",
data: {access_token: access_token},
success: function(data2){
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
},
error: function(data2){
console.log(data2);
}
});
}
} else {
resultShow.html("Noting found!");
}
},
error: function(data){
console.log(data);
}
});
};
You can change almost any value in a page using the innerHTML property.
Ex:document.getElementById("demo").innerHTML = "Paragraph changed!";
http://jsfiddle.net/blazeeboy/fNPvf/
To change the values inside a table, just assign an ID to it and change with your Javascript function.
In your case, I would suggest inserting any Javascript parameter between line 31 and 32.
success: function(data2){
var title = document.getElementById('title');
var username = "https://www.instagram.com/"+ data.data[i].username;
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
It will write the username into the table with id "title", if you need more than one table value, you'll need to make a array and use the for loop to insert an specific value into a specific table, tr, etc... id
success: function(data2){
//tableids are the ids of each table row or column in the order you wanna write them
var tableids = ['0', '1', '2'];//starting at 0
var username = "https://www.instagram.com/"+ data.data[i].username;
var title = document.getElementById(tableids[i]);
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
Hope it was clear enough
Currently I have stored variables in a Javascript array. The goal here is to turn them into PHP variables so that I can use these variables and insert them into my database.
The problem with this code is that the AJAX part doesn't work. Please get me in the right direction as I am extremely new to AJAX. I did try to read about them but still do not understand much. Doing it without refreshing the page is not necessary. Methods other than AJAX are welcomed.
Here is my current code:
<button onclick="Bookings()">Book</button>
<script>
function Bookings() {
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: "studioSelected=" + studioSelect,
success: function(data) {
alert("success!");
}
});
}
}
</script>
<?php
//bookingconfirmed.php
if (isset($_POST['studioSelect'])) {
$uid = $_POST['studioSelect'];
//steps to insert into database.
First, you should move ajax call outside of foreach
var usefulData = [];
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
// add data to array
usefulData.push(studioSelected);
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
}
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: {'usefuldata': usefulData},
success: function(data) {
alert("success!");
}
});
Then in your php file:
if (isset($_POST['usefuldata'])) {
var_dump($_POST['usefuldata']);
}