jQuery search in an object using a string - javascript

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>

Related

JSON select data at specific ID

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'])
}
}
})
}

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>

How to add content via ajax using the popover boostrap

I tried to view different sources and also looked into the forums posting similar question, but it didnt quite help me with the issue that im facing.
I have a text input filed to which I'm adding a popover to show similar a list of names in the database. The inout field checks for validation, to see if the name entered is unique, if not it displays similar names available in the database that could be re-used.
here is the popover snippet:
$("#account_name_create").popover({
title: 'Twitter Bootstrap Popover',
content: function (process) {
this.accountCollection = new ipiadmin.collections.AccountCollection();
var newName = $("#new-account-form #account_name_create").val();
var userFilter = "accountName~'" + newName + "'";
this.accountCollection.fetch({
data: { "f": userFilter,
"sortby": null,
"type":"ipi",
"pageno":0,
"pagesize":2,
"reversesort" : true
},
cache: false,
success: function(model, response, options) {
var states = [];
map = {};
$.each(model.aDataSet, function (i, state) {
map[state.accountName] = state;
states.push(state.accountName);
});
process(states); //gives an error saying 'undefined is not a function (says process is undefined)'
},
error: function(model, response, options) {
console.log('error');
}
});
},
});
here is the html:
<input type="text" id="account_name_create" name="account_name" class="" size="40" />
I'm not sure how why it says 'process' as undefined. Also not sure if this would be the correct way of displaying the data in the popover.
Any ideas??
Thanks!
process doesn't have scope in the success function, only in the content function. If you want to call the process function from within the success function, you could define it somewhere outside of the jQuery call.

$watch function gives undefined - AngularJS

I am a very basic beginner in AngulerJS.
What i'm trying to do is that when a user clicks on a product, the types of that product come up, then they pick a type and the colors of that type come up. I've tried using the same system that gets the types to show but my colors keep coming up undefined.
<section class="colorDisplay">
<div class="mcolor" ng-repeat="color in shoColor">
<img ng-src="{{color.image}}"/></div>
</section>
script.js
$scope.prod = {"name":"Pens"};
$scope.typ = {"id":1};
$scope.$watch('prod.name',function(){
$http.get("products/"+$scope.prod.name+".json").success(function(data){
$scope.type = data;
});
$scope.$watch('typ.id',function(type){
$scope.shoColor = type[$scope.typ.id].colors;
});
})
JSON File
{
"types":[
{
"name":"laser",
"id":0,
"image":"d-u-b/pens/laser.png",
"colors":[
{
"color":"Black and Silver",
"image":"colors/blacksilver.png",
"prodimage":"d-u-b/pens/laser/blacksilver.png"
},
{
"color":"Red",
"image":"colors/red.png",
"prodimage":"d-u-b/pens/laser/red.png"
}
]
},
{
"name":"plain",
"id":1,
"image":"d-u-b/pens/plain.png",
"colors":[
{
"color":"Yellow",
"image":"colors/yellow.png",
"prodimage":"d-u-b/pens/plain/yellow.png"
},
{
"color":"Blue",
"image":"colors/blue.png",
"prodimage":"d-u-b/pens/plain/yellow.png"
},
{
"color":"Cyan",
"image":"colors/cyan.png",
"prodimage":"d-u-b/pens/plain/cyan.png"
},
{
"color":"Silver",
"image":"colors/silver.png",
"prodimage":"d-u-b/pens/plain/silver.png"
}
]
}
]
}
I'm trying to call the id number of a certain types colors, putting it into something like this: types[0].colors, where the 0 is the inserted id number.
No matter where I put the watch function or what I name it, it's either the "0" is undefined or "colors" is undefined.
What am I doing wrong this time?
change this
$scope.shoColor = type[$scope.typ.id].colors;
to
$scope.shoColor = $scope.type[type].colors;
and
$http.get("products/"+$scope.prod.name+".json").success(function(data){
$scope.type = data;
to
$http.get("products/"+$scope.prod.name+".json").success(function(response){
$scope.type = response.data;
Here is a working fiddle of what i think you are trying to achieve.
note: - i have hard coded the $scope.type data in order for it to work on jsfiddle.
i have used nested ng-repeats as it follows the same code structure as the json response.
Hope it helps,
D

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