JSON select data at specific ID - javascript

In PHP, I've created a function to create a JSON file:
function writeJSONData(PDO $conn): void
{
$contentJSON = "SELECT * FROM tb_content";
$contentResultsJSON = $conn->query($contentJSON);
$contentJSONExt = array();
while ($JSON = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC)) {
$contentJSONExt = $JSON;
}
$infoJSON[] = json_encode(array('movies' => $contentJSONExt));
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/CineFlex/private/api/api.json";
file_put_contents($target_dir, $infoJSON);
}
In my HTML file I've created a button which sends the ID of the selected movie:
<!-- Edit Button -->
<button onclick="toggleDialog(editMovie, this.id)" id="<?php echo($info['content_id']) ?>Edit Movie</button>
My JavaScript file contains the function:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
console.log(data)
})
}
When I click on the edit button, it prints the entire JSON file in the console. Which is understandable.
Current output:
{
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
Now my issue is, I want the "dialogID" to be selected from the JSON file where it matches with "content_id". For example: When I click on a movie with 16 as "dialogID", I want the console to just print everything from that array.
Expected output:
{
"movies": [
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
}
]
}

To get it, you need to create dynamic API instead of static file content. In alternative case, you can get it only from JS loop (check all and check suitable ID). If you want to do it with API, you must change html and php script like this:
function getDataById(PDO $conn):string
{
$id = (int) $_GET['id'];
$contentJSON = "SELECT * FROM tb_content where id = :id";
$contentResultsJSON = $conn->prepare($contentJSON);
$contentResultsJSON->execute([':name' => 'David', ':id' => $_SESSION['id']]);
$rows = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC);
$contentJSONExt = array();
while ($JSON =$rows) {
$contentJSONExt = $JSON;
}
return json_encode(array('movies' => $contentJSONExt));
}
And, JS codes to change like this:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("https://my-site.com/getDataById/?id="+dialogID, function (data) {
console.log(data)
})
}

I don't know if you want to select in your php the right ID, and send back only the right one or if you want the whole json back and select in javascript.
First answer here gives the answer to dynamic php: only the right ID back from server.
I will try to answer the second possibility: all json movies back, selection in javascript.
html (3 buttons for example):
<button onclick="toggleDialog(this.id)" id="15">Edit Movie 15</button>
<button onclick="toggleDialog(this.id)" id="16">Edit Movie 16</button>
<button onclick="toggleDialog(this.id)" id="17">Edit Movie 17</button>
javascript, let say we have back the whole json movies, I put a variable here (it's supposed to be the whole json back from php):
let json = {
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
javascript function:
function toggleDialog(dialogID) {
dialogID = parseInt(dialogID);
json.movies.every(e => {
if (e.content_id === parseInt(dialogID)) {
console.log(e.content_id);
console.log(e.title);
console.log(e.description);
return false;
}
return true;
})
}
You iterate through the json.movies (it's an object) with "every" instead of forEach. With every, you can break the loop when condition is met dialogID === content_id with return false. You have to put return true at the end of the loop otherwise it breaks immediately.
Your content_id are numbers, so parseInt on the dialogID. If coming from php json, it'll normally be string so no need for that.

A friend of mine helped me out:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
for (let i = 0; i < data['movies'].length; i++) {
if (data['movies'][i]['content_id'] == dialogID) {
$('#editMovieTitle').val(data['movies'][i]['title'])
}
}
})
}

Related

Fetch works by categoryId

Hello i am learning JS actually i try to fetch some data from an API, i have fetch all the work from api/works and display them in a div but now i need to create 3 button who represent the 3 category who regroup all works, i created dynamically the buttons but now i need to put a function on these button to display the api/works from the category id give (example button 1 represent category id 1 and when i click, all api/works from category id 1 are displayed, same for 2nd et 3rd button) there is the json format for data
[
{
"id": 1,
"title": "Abajour Tahina",
"imageUrl": "http://localhost:5678/images/abajour-tahina1651286843956.png",
"categoryId": 1,
"userId": 1,
"category": {
"id": 1,
"name": "Objets"
}
}
i don't know how said fetch all works but with categoryId 1, hide all and display these categoryId of works
if someone know how to do this or documentation to doing this
document.getElementById("button").addEventListener("click", function(){
// Clear the container element
document.getElementById("works").innerHTML = "";
// Make GET request to API endpoint for all works with categoryId 1
fetch("http://localhost:5678/api/works?categoryId=1")
.then(response => response.json())
.then(data => {
// Loop through the list of works
data.forEach(function(work) {
// Create a new HTML element for each work
var workElement = document.createElement("div");
workElement.innerHTML = "Work ID: " + work.id + "<br>" + "Title: " + work.title + "<br>" + "Content: " + work.content;
// Append the new HTML element to the page
document.getElementById("works").appendChild(workElement);
});
})
.catch(error => console.log(error));
i tried this but he give me all /works the url http://localhost:5678/api/works?categoryId=1 not working for me i think
put console.log on the function that handle the click on button to see if the function is actualy triggerd.
i think because your buttons are dynamically added javascript can't recognize them.

Is it possible to format my json file for a Yes or No chat flow for my chatbot

I'm currently trying to create a chatbot as an IT support for FAQs on IT Department.
Since every computer problems have more than 1 solution, is there anyway I could format my json file in such a way that the conversation could flow like this:
Chatbot : Hello, what can I do for you?
User: My Wi-Fi keeps disconnecting
Chatbot: Solution 1: Click on the Network & Internet icon in the
system....(Please type Y if this solved your problem, and Type N if
No)
User: No
Chatbot; Soution 2: DISABLE WIFI SENSE. Click on the Windows icon in
your taskbar...(Please type Y if this solved your problem, and Type N
if No)
User: Yes
Chatbot: Glad I could help.
here's my sample code below
#Python
import random,json,pickle,numpy as np,nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import load_model
# import tech_supp._sample_chatbot.nlp.training
__my_file_path = 'tech_supp/python/chatbot/nlp/'
lemmatizer = WordNetLemmatizer()
intents = json.loads(open(f'{__my_file_path}intents.json').read())
words = pickle.load(open(f'{__my_file_path}words.pkl', 'rb'))
classes = pickle.load(open(f'{__my_file_path}classes.pkl', 'rb'))
model = load_model(f'{__my_file_path}chatbotmodel.h5')
def clean_up_sentence(sentence):
sentence_words = nltk.word_tokenize(sentence)
sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]
return sentence_words
def bag_of_words(sentence):
sentent_words = clean_up_sentence(sentence)
bag = [0] * len(words)
for w in sentent_words:
for i,word in enumerate(words):
if word == w:
bag[i]=1
return np.array(bag)
def predict_class(sentence):
bow = bag_of_words(sentence)
res = model.predict(np.array([bow]))[0]
ERROR_THRESHOLD = 0.80
results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
results.sort(key=lambda x:x[1],reverse= True)
return_list = []
for r in results:
probability = round(r[1] * 100,ndigits=2)
probability = str(probability)+'%'
return_list.append({'intent':classes[r[0]],'probability':probability})
return return_list
def get_response(message):
intents_list = predict_class(message)
# for each_intent_list in intents_list:
# print(each_intent_list)
if len(intents_list)>0:
tag = intents_list[0]['intent']
accuracy = intents_list[0]['probability']
else:
#fallback message
return "I'm sorry I don't understand you."
list_of_intents = intents['intents']
for i in list_of_intents:
if i['tag'] == tag:
# return f'Accuracy: "{accuracy}" {random.choice(i["responses"])}'
return random.choice(i["responses"])
print('Go! Bot is running!')
#Javascript
function open_chatbot(){
document.getElementById("chatbot").innerHTML =
`<div>
<button class="btn btn-outline-info" onclick="minimize_chatbot()">Minimize</button>
<label>Was this chatbot helpful?</label>
<button class="right-msg btn btn-outline-info" onclick="save_chat_session('yes')">Yes</button>
<button class="right-msg btn btn-outline-info " onclick="save_chat_session('no')">No</button>
<div class="msger-chat"></div>
<form class="msger-inputarea">
<input type="text" class="msger-input" id="textInput" placeholder="Enter your query...">
<button type="submit" class="msger-send-btn">Send</button>
</form>
</div>`;
const msgerForm = get(".msger-inputarea");
const msgerInput = get(".msger-input");
const msgerChat = get(".msger-chat");
//Icons made by Freepik from www.flaticon.com
const BOT_NAME = "Jayvee";
const PERSON_NAME = "You";
msgerForm.addEventListener("submit", event =>
{
event.preventDefault();
const msgText = msgerInput.value;
if (!msgText) return;
appendMessage(PERSON_NAME, "right", msgText);
msgerInput.value = "";
botResponse(msgText);
});
function appendMessage(name, side, text)
{
//Simple solution for small apps
const msgHTML =
`
<div class="msg ${side}-msg">
<div class="msg-img"></div>
<div class="msg-bubble">
<div class="msg-info">
<div name="message-name" class="msg-info-name">${name}</div>
<div name="message-datetime" class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div name="message-text" class="msg-text">${text}</div>
</div>
</div>
`;
msgerChat.insertAdjacentHTML("beforeend", msgHTML);
msgerChat.scrollTop += 500;
}
function botResponse(rawText) {
// Bot Response
$.get("/chat", { msg: rawText }).done(function (data)
{
const msgText = data;
appendMessage(BOT_NAME, "left", msgText);
});
}
// Utils
function get(selector, root = document)
{
return root.querySelector(selector);
}
//chabot introduction
appendMessage(BOT_NAME, "left", "Hello! I\'m Jayvee your computer technical-support Chatbot.");
}
function minimize_chatbot(){
document.getElementById("chatbot").innerHTML =
'<button class="btn btn-outline-info" onclick="open_chatbot()">Chatbot</button>';
}
function formatDate(date){
var hour = date.getHours();
var minute = date.getMinutes();
if(hour==0)
hour=12;
var ampm = "AM";
if( hour > 12 ) {
hour -= 12;
ampm = "PM";
}
hour = "0" + hour;
minute = "0" + minute;
return `${hour.slice(-2)}:${minute.slice(-2)} ${ampm}`;
}
function save_chat_session(result){
/*
* result
* name
* datetime
* message
*/
let name= document.getElementsByName("message-name");
let datetime= document.getElementsByName("message-datetime");
let message= document.getElementsByName("message-text");
let conversation=[];
for (let i = 0; i < name.length; i++) {
let obj = {
"name":name[i].innerHTML,
"datetime":datetime[i].innerHTML,
"message":message[i].innerHTML
}
conversation.push(obj);
}
fetch('/admin/chatbot/save_session',{
headers: {'Content-Type': 'application/json' },
method: 'POST',
body: JSON.stringify(
{
"result": result,
"conversation":conversation
}
)
})
.then(function (response) {return response.text();})
.then(function (text) {console.log('POST response: '+text);});
minimize_chatbot();
}
minimize_chatbot();
#Excerpt from my JSON FILE
{
"intents": [
{
"tag": "greetings",
"patterns": [
"hello",
"hey",
"hi",
"good day",
"Greetings",
"what's up?",
"how is it going?"
],
"responses": [
"Hello, Welcome to Our IT Chatbot",
"Good to see you, Welcome to our IT Chatbot",
"Hi there, how can I help?"
]
},
{
"tag": "Cannot access email",
"patterns": [
"can't access email",
"email inaccessible",
"cannot acess email"
],
"responses": [
"1.Restart the e-mail application. Log in with your credentials <br> 2.Try accessing your e-mail through the web. If you can access it, the problem lies in the application\u00e2\u20ac\u2122s software.<br> 3.Check the service status for any general e-mail issues.<br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for greater assistance!"
]
},
{
"tag": "Slow downloading and uploading speeds",
"patterns": [
"slow download speed, download slow",
"slow download",
"internet download slow",
"slow internet"
],
"responses": [
"Try running a speed test online. Ideally, you should get half of the speed that your service provider is claiming to offer.<br>If the tests are positive, double-check the background for any hidden files that are downloading or uploading <br> Also, check whether the network card needs updating or not. <br> 2.If slow speed still occurs, try resetting the modem to solve the network problems.<br> If the issue is not resolved, call your service provider to check if they are having problems from their end. <br> If you're connecting wirelessly, then the location may be the problem. The signal is not necessarily strong in all corners of the building. Similarly, you could just be too far away. If this is not the issue, then spyware or viruses are a likely cause. <br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for in-depth assistance!"
]
},
{
"tag": "Windows takes a long time to start",
"patterns": [
"windows starts slow",
"pc starts slow",
"turning on pc loads slow",
"slow startup"
],
"responses": [
"1.Disable Fast Startup-open Settings and browse to System then click Power & sleep. <br> On the right side of this screen, click Additional power settings to open the Power Options menu in the Control Panel and untick Turn on fast startup click Save.<br> <br> 2.Adjust Paging File Settings- Click Start Menu, choose the Adjust the appearance and performance of Windows. Under the Advanced tab, click Change. Uncheck Automatically manage paging file size for all drives then choose Custom Size and set the Initial Size and Maximum Size then Restart your computer.<br> <br> 3.Update Graphics Drivers- Open the Device Manager by right-clicking on the Start button (or hitting Win + X) and choose Device Manager. Go to Display adapters to see which graphics card you're using (others are Nvidia or AMD).Install any new version <br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for greater assistance! "
]
},
{
"tag": "How to fix lag on a PC",
"patterns": [
"How to fix lag on a PC",
"lag pc",
"solutions for lag pc"
],
"responses": [
"Solution 1: Run Disk Defragmenter.<br> Step 1: Press the Windows button. Click *All Programs* and open *Accessories*.<br> Step 2: Right-click *Command Prompt*. Choose *Run as Administrator*.<br> Step 3: Type *defrag X: -v* in the prompt, X representing the letter of your hard disk. For instance, if you want to defrag drive E type *defrag E: -v* in the prompt. Press *Enter*.<br> Step 4: Wait for the defragmentation to complete. Reboot your system once it is complete.<br><br> Solution 2: Run Disk Cleanup<br> Step 1: Press the Windows button. Type *Disk Cleanup* in the *Start Search* field. Press *Enter*.<br>Step 2: Click *My Files Only* when the Disk Cleanup Options prompt appears.<br> Step 3: Choose the drive and click *OK*. Allow the tool to scan for possible space to free up.<br>Step 4: Place a check by the files you want to delete. Click *OK*.<br> Step 5: Click *Delete Files* when the *Are You Sure You Want To Permanently Delete These Files?* prompt launches.<br> <br> Solution 3: Scan for Harmful Software<br>Step 1: Press the Windows button. Click *All Programs* and open *Windows Defender*.<br>Step 2: Click the *Scan* option toward the top of the window.<br> Step 3: Choose the repair option once the scan is complete. Reboot your system once the repair is complete.<br> If the solution given above didn't solve your problem, please contact your IT department or an IT expert for in-depth assistance!"
]
}
]
}
Thanks in advance!

Getting json data for dropdown list using jquery not working

Looking for information on how to read a json from an api call we have to populate a dropdown list.
[
{
"name": "jira",
"description": "The default JIRA workflow."
},
{
"name": "Business Review and Build",
"description": "The default JIRA workflow starting point."
}
]
The json does not seem to have opening and closing { .. }. It looks basically like what I pasted in above. I guess it is like an anonymous array of two values, name, and description. It is retrieved via a url that has a go script running that outputs this json.
I tried to use jquery, but something like this does not display any options.
function populateWF() {
let dropdown = $('#projWF');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose a workflow');
dropdown.prop('selectedIndex', 0);
const url = 'http://esjira01d.internal.company.com:8088/workflows';
$(document).ready(function() {
$.getJSON(url, function(obj) {
$(obj).each(function() {
dropdown.append($('<option>/option>')
.val(this.Name).html(this.Description));
}); #each
}); #getJSON
}); #ready
}
The option box does dispaly and it does say the mesage about Choose a workflow. It just seems to bomb at the actual getJSON.
It does not display anything in the drop down. If I go to the url, it shows what appears to be json. If I go to jlint and type in what I think it is returning, it says it is valid.
The data you get back is a normal Array of Objects encoded as JSON. To get the values, you can use a simple for-loop or the .forEach() function:
let obj = '[{"name":"jira","description":"The default JIRA workflow."},{"name":"Business Review and Build","description":"The default JIRA workflow starting point."}]';
obj = JSON.parse(obj);
let dropdown = $("#dropdown");
obj.forEach(function(e) {
let option = $('<option></option>');
option.val(e.name);
option.html(e.description);
dropdown.append(option);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>
function populateWF() {
let dropdown = $('#projWF');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose a workflow');
dropdown.prop('selectedIndex', 0);
const url = 'http://esjira01d.internal.company.com:8088/workflows';
$(document).ready(function() {
$.getJSON(url, function(obj) {
obj.forEach(function(e) {
let option = $('<option></option>');
option.val(e.name);
option.html(e.description);
dropdown.append(option);
});
});
});
}
The result you received is an array instead of object. You can use .map() function to create the options.
var result = [
{
"name": "jira",
"description": "The default JIRA workflow."
},
{
"name": "Business Review and Build",
"description": "The default JIRA workflow starting point."
}
]
$(document).ready(function() {
result.map(function(item) {
$("select").append($('<option></option>').val(item.name).html(item.description));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>

jQuery search in an object using a string

UPDATE
23 November 2016:
I was very close to the solution. Rory McCrossan has solved it for me, so I accepted his answer. BUT I changed the code for faster developing. I want to share this so you can use it to.
JSON langfile-v1.0.json
{
"nl": {
"text1":"Hallo Wereld!",
"text2":"voorbeeld.com",
"text3":"Ik hou van Stack Overflow"
},
"en":{
"text1":"Hello World!",
"text2":"example.com",
"text3":"I love Stack Overflow"
}
}
Javascript / jQuery script.js
//Creating an GLOBAL object
var languageObject;
//Get the language json file
$.get("langfile-v1.0.json", function(response){
languageObject = response; //Assign the response to the GLOBAL object
setLanguage(); //Calling the setLanguage() function
});
//Call this function to set the language
function setLanguage() {
$("lang").html(function() {
var userLang = navigator.language || navigator.userLanguage;
var langSupported = false; //Check if the user language is supported
$.each(languageObject, function(key) {
if (userLang == key) {
langSupported = true;
}
});
if (langSupported) {
//Users language is supported, use that language
return languageObject[userLang][$(this).html()];
} else {
//User language is NOT supported, use default language
return languageObject.en[$(this).html()];
}
});
}
HTML page.html
<lang>text1</lang> <br>
<lang>text2</lang> <br>
<lang>text3</lang>
Demo
You can check how this works on JSFiddle (with a slightly different code because I dont know how to inculde the langfile-v1.0.json file)
Click here for demo
OLD QUESTION POST:
I want to search in a object using a string.
Example:
JSON
{
"nl": {
"lang":"Nederlands",
"header-WelcomeText":"Welkom op de website",
"header-Sub1":"Hoofdpaneel"
},
"en": {
"lang":"English",
"header-WelcomeText":"Welcome on the website",
"header-Sub1":"Dashboard"
}
}
Javascript/jQuery
var output;
$.get("file.json", function(response){
output = response; //This is now a object in javascript
});
This all works, here what i want:
//The jQuery code
$('span .lang').text(output.nl.$(this).attr("data-lang"));
//The HTML code
<span class="lang" data-lang="header-Sub1"></span>
I know this will not work, but I know there will be a way to achief this.
To make this work there's a few changes you need to make.
when accessing the key of an object through a variable you need to use bracket notation.
to reference the element through the this keyword you need to run your code within it's scope. To do that you can pass a function to the text() method which returns the value you need from the object.
the .lang class is directly on the span, so you shouldn't have the space in your selector.
With all that in mind, this should work for you:
var output = {
"nl": {
"lang": "Nederlands",
"header-WelcomeText": "Welkom op de website",
"header-Sub1": "Hoofdpaneel"
},
"en": {
"lang": "English",
"header-WelcomeText": "Welcome on the website",
"header-Sub1": "Dashboard"
}
}
$('span.lang').text(function() {
return output.nl[$(this).data("lang")];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="lang" data-lang="header-Sub1"></span>

search to json pull from API to html all nice and pretty?

I'm working on a project for a client where the site visitors can search Campusbooks.com and get the results displayed.
Contacted Campusbooks and was told that I can use their API and have fun... and that's it.
I've found how to create a search form that pulls the results as posts the raw JSON. There's no formatting in the JSON so what I am getting is
"response":{
"#attributes":{
"status":"ok",
"version":"10"
},
"label":{
"#attributes":{
"plid":"3948",
"name":"Textbooks 4 You"
}
},
"page":{
"#attributes":{
"name":"search"
},
"count":"1000",
"pages":"100",
"current_page":"1",
"results":{
"book":[{
"isbn10":"1463590776",
"isbn13":"9781463590772",
"title":"Life on the Mississippi",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"13.99",
"pages":"316",
"publisher":"CreateSpace",
"published_date":"2011-06-19",
"edition":"Paperback",
"rank":"99999999",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/51sXKpUcB0L.SL75.jpg"
},
{
"isbn10":"1406571253",
"isbn13":"9781406571257",
"title":"How to Tell a Story and Other Essays (Dodo Press)",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"12.99",
"pages":"48",
"publisher":"Dodo Press",
"published_date":"2008-02-29",
"edition":"Paperback",
"rank":"214431",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/41S5poITLpL.SL75.jpg"
},
{
"isbn10":"0520267192",
"isbn13":"9780520267190",
"title":"Autobiography of Mark Twain, Vol. 1",
"author":"Mark Twain",
"binding":"Hardcover",
"msrp":"34.95",
"pages":"743",
"publisher":"University of California Press",
"published_date":"2010-11-15",
"edition":"1",
"rank":"344",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/41LndGG6ArL.SL75.jpg"
},
{
"isbn10":"1936594595",
"isbn13":"9781936594597",
"title":"The Adventures of Huckleberry Finn",
"author":"Mark Twain",
"binding":"Paperback",
"msrp":"8.88",
"pages":"270",
"publisher":"Tribeca Books",
"published_date":"2011-04-07",
"edition":"Paperback",
"rank":"1285",
"rating":"0.0",
"image":"http://ecx.images-amazon.com/images/I/51J4kzmKcpL.SL75.jpg"
}
]
}
}
}
}
I need to take that output and make it all nice and pretty in HTML.
The script I am using to do this with at this point is:
// Vanilla JS Example: CampusBooksJS
(function () {
var CampusBooks = require('campusbooks'),
// This key is a special dummy key from CampusBooks for public testing purposes
// Note that it only works with Half.com, not the other 20 textbook sites, so it's not very useful,
// but good enough for this demo
cb = CampusBooks.create("T4y4JKewp48J2C72mbJQ"),
cbform = document.getElementById("vanilla-campusbooksjs-form");
// Note: This is for demonstration purposes only (with modern browsers)
// Use MooTools or jQuery for a real-world solution that works cross-browser
// (and please don't write you own, it's not worth it)
function cbSearch(e) {
var cbform = this,
search = cbform.querySelector("select").value,
data = cbform.querySelector("input").value;
e.preventDefault();
if (!data) {
alert("Try Typing in a Keyword or Two First");
return;
}
alert("Your Search: " + search + ": " + JSON.stringify(data, null, ' '));
var params = {};
params[search] = data;
cb.search(params).when(function (err, nativeHttpClient, data) {
if (err || !data) {
alert("Error: " + JSON.stringify(err) || "No Data Returned");
return;
}
document.querySelectorAll("#vanilla-campusbooksjs-display")[0].innerHTML = JSON.stringify(data, null, ' ');
});
}
// This will work on modern browsers only
cbform.addEventListener("submit", cbSearch, false);
}());
The search form is:
<form id="vanilla-campusbooksjs-form">
<select name="cb_search">
<option>keywords</option>
<option>author</option>
<option>isbn</option>
</select>
: <input name="cb_value" type="text"/>
<input type="submit" value="Search"/>
</form>
<div>
<pre>
<code id="vanilla-campusbooksjs-display">
</code>
</pre>
</div>
I hope this isn't too long of a post. If additional information is needed, please let me know.
I would suggest using Mustache Templates. Its easy to apply mustache templates to JSON and get some markup. It can be done on the server or client side.

Categories