I've created a bootstrap menu from a json response. The menu gets the list of items and creates a link to https://example.com/api/products/GetProductDetail/product_id which takes you to the json response.
What I need it to do is not follow the link to the json response, but rather get that response, parse the data and plug it into a div on the existing page, but I'm not sure how to do that.
Here is what I have right now:
<script>
$.getJSON('https://example.com/api/products/GetProductList/', function(data) {
var output = '<div class="panel panel-default">';
for (var i in data.Categories) {
output += '<div class="panel-heading '+data.Categories[i].category_id +'"><a data-toggle="collapse" data-parent="#accordion" href="#' + data.Categories[i].category_id + '-products">';
output += data.Categories[i].Category + '</a></div>';
output += '<div id="' + data.Categories[i].category_id + '-product" class="panel-collapse collapse"><div class="panel-body">';
for (var j in data.Categories[i].Products) {
output += '<li>'+data.Categories[i].Products[j].short_description + " -- " + data.Categories[i].Products[j].cost+' coins</li>';
}
output += "</div></div>";
}
output += "</div>";
document.getElementById("accordion").innerHTML = output;
});
</script>
Instead of creating a link to the product detail url, create a link to some function accepting the productid.
This function could make a call just like the one you currently have for the product list, processing the json and appending the result to a div.
So add a function like:
function getProduct(id) {
$.getJSON('https://example.com/api/products/GetProductDetail/' + id, function(data) {
//Process JSON to some HTML.
var productDetails = '<div>' + data.Product.Name + '</div>';
//Add it to the div where you want your product details to appear
document.getElementById("detailsDiv").innerHTML = productDetails;
};
}
and replace the li, created for every product in the overview with something like the following:
output += '<li><a onclick="getProduct(' + data.Categories[i].Products[j].product_id + ');">'+data.Categories[i].Products[j].short_description + " -- " + data.Categories[i].Products[j].cost+' coins</a></li>';
Related
I have an HTML page that contains only an empty <div id="data"></div> and in javascript, I got the information from the database through the ajax and return it back to javascript then print it out in the <div id="data"></div>
I've set the data to be in the columns, now if I want to add another column and this column would contain a button if I click on it then the row will be deleted. (I know how to do the delete through ajax and return it back, etc..) but the question is how could I do the button?
If I add it inside the div = data it will be printed once, and if I add it inside the javascript file then I won't able to add a click listener .. how could I do that?
let printItems = document.getElementById("data");
function succes(user) {
let info = "<div class='infoTable'>";
for (let i = 0; i < user.length; i++) {
info += "<div class='info'>";
info += "<div class='fcol'>" + (i+1) + "</div>";
info += "<div class='scol'>" + user[i].name + "</div>";
info += "<div class='tcol'>" + user[i].quantity + "</div>";
info += "I NEED TO ADD THE BUTTON HERE TO HAVE user[i].ID";
info += "</div>";
}
info += "</div>";
printinfo.innerHTML = info;
}
<div id="data"></div>
Okay, you did the hard part. What you are looking is very easy and you can do that in more than one way. I can suggest you an easier way to me. Write a function which delete the row (from UI and ajax). Now your problem is how to call that function for each row. So you can attach a onclick function for every row you created.
For example:
info += '<button onclick="deleteRowFunction"> Delete This<button />';
Now every time you click the button your delete function called. But how to determine which function is called?
That can be solved by following ways:
info += '<button onclick="deleteRowFunction(\'' + user[i].ID + '\')"> Delete This<button />';
The other easy way is to use data- attribute:
For example:
info += '<button data-userId=' + user[i].ID + ' onclick="deleteRowFunction"> Delete This<button />';
In this way you can get the ID in the deleteRowFunction. You can read all the details here
const user = [{
name: "ABC",
quantity: 2,
}, {
name: "XYZ",
quantity: 1,
}, {
name: "abcdef",
quantity: 12,
}];
let printItems = document.getElementById("data");
function deleteButton(e){
const targetButton = e.target;
targetButton.parentElement.parentElement.remove();
}
function succes(user) {
let info = "<div class='infoTable'>";
for (let i = 0; i < user.length; i++) {
info += `<div class='info'>
<div class='fcol'>${(i + 1)}</div>
<div class='scol'>${user[i].name}</div>
<div class='tcol'>${user[i].quantity}</div>
<div class='tcol'><button onclick="deleteButton(event)">Delete</div>
</div>`;
}
info += "</div>";
printItems.innerHTML = info;
}
succes(user);
<div id="data"></div>
I am having trouble. So I need to get data from an api. I have a search bar and the user needs to input the search bar to look up a super hero api.
How would I get data from a search bar and put in my url all in a .click function.
var userInput;
var url;
var test;
//https://superheroapi.com/api/10215865526738981
$(document).ready(function () {
// when the user types in the data and clicks the button
$(btn1).click(function () {
// this is where the search bar is
userInput = document.getElementById('mySearch').innerHTML;
});
url = 'https://www.superheroapi.com/api.php/10215865526738981/search/batman' + userInput;
// here is where the api link in say type in batman
// and is should pop up with info about batman and
$.getJSON(url, function (data) {
var html = '';
$.each(data.results, function (i, demo) {
html += '<h2>' + demo.name + '</h2>';
//html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2> Power Stats ' + demo.powerstats.combat + '</h2>';
html += '<p> Connections ' + demo.connections.relatives + '</p>';
html += '<p> appearance ' + demo.appearance.gender + '</p>';
html += '<h2> Work ' + demo.work.base + '</h2>';
html += ' Profile <img src ' + demo.image.url + '>';
});
$('#demo').html(html);
});
}
<p>
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<p id="demo"></p>
</p>
Here is something that works that you can use to compare with your code and make something out of it. I've used plain javascript and left comments what is going on so that you can learn from it.
There were few wrong assumptions in original question.
code was executing on page load and didn't wait for user input
url was hardcoded to start with batman + what ever user wrote
Code below is not perfect, but it is close enough to original code and it should be easy to understand. I also opted not to use jQuery, but you should be able to use it if wanted. Just replace getElementById with jQuery selectors and replace XMLHttpRequest with getJson.
I hope this helps you move ahead with your problem and that you will be able to learn something new which could help you better understand javascript. Happy coding!
var button = document.getElementById('btn1');
// when user clicks on button, we want to call function start search
button.addEventListener('click', startSearch);
function startSearch(event) {
// when we are starting the search, we want to pick up the value
// input field from user
var userInputValue = document.getElementById('mySearch').value;
// this is base API url on which we can add what user wanted
var urlBase = 'https://www.superheroapi.com/api.php/10215865526738981/search/'
// if user did not provide name in input, we want to stop executing
if (userInputValue === null || userInputValue === '') return;
// if we are still in this function, append what user typed onto urlBase
var searchUrl = urlBase + userInputValue;
// call function which actually executes the remote call
performSearch(searchUrl);
}
function performSearch(searchUrl) {
// this could be jQuery getJSON if you so prefer
// here it is vanila JS solution of how to get data via AJAX call
var requestData = new XMLHttpRequest();
// because AJAX is always async, we need to wait until file is loaded
// once it is loaded we want to call function handleResults
requestData.addEventListener('load', handleResults);
requestData.open('GET', searchUrl);
requestData.send();
}
function handleResults() {
// once we get response, because we used vanilla JS, we got response
// available in this context as "this.response", however it is type string
// we need to take that string and parse it into JSON
var responseJSON = JSON.parse(this.response);
// if there is error, we didn't find any character
if (responseJSON.error) console.log('Character not found');
else {
var html = '';
responseJSON.results.forEach(function (result) {
html += '<h2>' + result.name + '</h2>';
// html += "<h2>" + demo.biography.alter-egos + "</h2>";
html += '<h2>Power Stats ' + result.powerstats.combat + '</h2>';
html += '<p>Connections ' + result.connections.relatives + '</p>';
html += '<p>Appearance ' + result.appearance.gender + '</p>';
html += '<p>Work ' + result.work.base + '</p>';
// html += ' Profile <img src ' + result.image.url + '>';
})
// this is bad thing to do, injecting html like that into DOM
// but let's leave this lesson for later stage
// so, let's take this html and drop it onto the page
document.getElementById('demo').innerHTML = html;
}
}
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<div id="demo"></div>
const value = document.getElementById('mySearch').value;
And then use this value in your api url.
I am trying to load JSON data from a drop down menu to a div area which would be refreshed with the new results, i have manged to get the data and show it in the div area without using the drop down menu, but cannot find a way to call the required data using the drop down menu.
the below code is to bring up part of the json data from the json file that is present which is working when i load the web page, but what i need is that when the user clicks on the drop-down menu and clicks any of the links, the relevant json data will be displayed
$(function loadpc()
{
$(document).ready(function () { // load json file using jquery ajax
$.getJSON('PCproducts.json', function (data) {
var output = '<div id="row">';
var count = 1;
$.each(data.pc, function (key, val) {
output += '<div id="holding-area">';
output += '<div id="img-area">' +
'<img id="img" src="'+val.imgpath+'" alt="'+ val.title +'" /></div>';
output += '<div id="info">';
output += '<h2>' + val.title + '</h2>';
output += '<p>' + val.category + '</p>';
output += '<p>' + val.develop + '</p>';
output += '<p>' + val.released + '</p>';
output += '<p>' + val.price + '</p>';
output += '<p>' + val.quantity + '</p>';
output += '<p><input type="submit" value="Add to cart" class="btn" /></p>'
output += '</div>';
output += '</div>';
if(count%2 == 0){
output += '</div><div id="row">'
}
count++;
});
output += '</div>';
$('#content-2-1').html(output); // replace all existing content
});
});
});
Can anyone please guide me in the right direction as i have been trying for a long time with no success
Using jquery template is the simple manner :)
You may find some info there jquery template documentation
jquery template is a simple type formatted like this i took it from one of my project:
<script type="text/x-jquery-tmpl" id="tplmsg">
<div class="row">
<div class="col-xs-3 col-md-1">
<img src="${src}" class="img-thumbnail" alt="${title}" />
</div>
<div class="col-xs-9 col-md-11">
<div class="col-xs-12 col-md-12">
<p class="title">${getSubstring(title,0,100)}</p>
</div>
<div class="col-xs-12 col-md-12 btf" >
<p class="adsdts"><strong>Data: </strong>${parseJsonDate(DateAdd)}
<strong>Prezzo:</strong>${price}
<strong>Provincia:</strong>${pvname}
<%--<strong>Provincia:</strong>${pvname}--%>
</p>
</div>
</div>
</div>
<hr />
</script>
In abovesnippet you may see some stuff which is vbnet related how ever logic is the same.
Then you may fill it with simple js function like this:
function getAds(task,token) {
var qry='task='+task+'&token=' +token;
$.ajax(
{
type: "POST", url: url, data: qry
,
success: function (msg) {
if (msg.hasOwnProperty('error')) {
$("#").html(msg.error);
return;
}
else if (msg.hasOwnProperty('empty')) {
$("#result").html(msg.empty);
return;
}
else {
//reular version
$("#"+msg.tmpl).tmpl(msg.data, null).appendTo("#"+msg.result);
}
},
error: function (msg) {
$("#result").html("errore durante l'elaborazione");
}
});
}
That's all simple and fast.
I have this javascript code where it goes for each movies in jsonp dataType. For each movies I have to display its thumbnail image and its title together with the star rating. To display the star symbols below for each movies I have this code:
var include = '<div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>';
$(".prediction").html(include); //DISPLAYS THE PREDICTION RATING
It simply sets the html content of the class prediction to this -> <div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>
I tried to use this on directly on my html code and it is fully working I can see the stars. Here it is:
But I tried this on javascript and it is not displaying. I just want to have ratings below for each and every movies.
This is my javascript code:
var html = '';
var count = 0;
$.each(data.movies, function(index, movie) {
html += '<div class="item col-xs-6 col-md-3">';
html += '<div class="thumbnail" style="min-height:320px;max-height:320px;">';
//add link here
html += '<a href="viewMovieDetails.php?id=' + movie.id + '">'
html += '<img src="' + movie.posters.detailed + '" style="width:175px; height: 230px;" class="img-responsive" alt="" ></a>';
html += '<div class="caption">';
html += '<h5>' + movie.title + '</h5>';
html += '<div class="prediction"></div>';
html += '</div></div></div>';
//set a delay (1second) for a call on rotten tomatoes api and
//store data on db
if(count > 5){
setTimeout(function() { storeDataOnDB(movie.id);; }, 1000);
count = 0;
}
else{
count++;
}
});
// Append movies
$('#movie_recommend').html(html);
var include = '<div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>';
$(".prediction").html(include); //DISPLAYS THE PREDICTION RATING
What do you think is wrong? Am I missing something? or is there other way to do it. Thanks for the help.
You should notify RateIt plugin, that new data is available, just add this:
$(".rateit").rateit();
after $(".prediction").html(include);
I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;