Slick Slider not initializing with API json - json

Trying to incorporate slick slider with an API but for some reason it won't work.
Not sure if I'm doing something wrong.
html
<div class="row">
<div id="test">
<div class="card top">Hello! My name is<div class="name">Izzy</div><div class="location">Alamo, CA</div><div class="sex-age">Female, adult</div></div>
<div class="card top">Hello! My name is<div class="name">Izzy</div><div class="location">Alamo, CA</div><div class="sex-age">Female, adult</div></div>
<div class="card top">Hello! My name is<div class="name">Izzy</div><div class="location">Alamo, CA</div><div class="sex-age">Female, adult</div></div>
</div>
</div>
<div class="row">
<div id="cats">
</div>
</div>
You can see the first slider "#test" does work with the same html markup as the one in the bottom named "#cats"
For some reason the slider #cats won't initialize though. Does it have to do with me using append() to the div with id "cats"?
js
$(document).ready( function() {
$.getJSON("https://api.myjson.com/bins/187677", function(data){
$.each(data.pets, function() {
var name = this["pet_name"];
var sex = this["sex"];
var age = this["age"];
var state = this["addr_state_code"];
var image = this ["large_results_photo_url"];
var city = this ["addr_city"];
if ( sex = "m") {
sex = "Male";
}
if ( sex = "f") {
sex = "Female";
}
$("#cats").append(
"<div class='card top'>" +
"Hello! My name is"+
"<div class='name'>" + name + "</div>" +
"<div class='location'>" + city + ", " +state + "</div>" +
"<div class='sex-age'>" + sex + ", " + age + "</div>" +
"</div>"
);
});
});
$('#cats').slick();
$('#test').slick();
});
THank you in advanced!

You need to initialize the slick plugin for the #cats after you have inserted the relevant slides in the DOM
$(document).ready(function() {
$.getJSON("https://api.myjson.com/bins/187677", function(data) {
$.each(data.pets, function() {
var name = this["pet_name"];
var sex = this["sex"];
var age = this["age"];
var state = this["addr_state_code"];
var image = this["large_results_photo_url"];
var city = this["addr_city"];
if (sex = "m") {
sex = "Male";
}
if (sex = "f") {
sex = "Female";
}
$("#cats").append(
"<div class='card top'>" +
"Hello! My name is" +
"<div class='name'>" + name + "</div>" +
"<div class='location'>" + city + ", " + state + "</div>" +
"<div class='sex-age'>" + sex + ", " + age + "</div>" +
"</div>"
);
});
$('#cats').slick();
});
$('#test').slick();
});
Alternatively you can initialize the plugin earlier, and use the .slice('slickAdd', 'html node here') method
$(document).ready(function() {
$('#test').slick();
$('#cats').slick();
$.getJSON("https://api.myjson.com/bins/187677", function(data) {
$.each(data.pets, function() {
var name = this["pet_name"];
var sex = this["sex"];
var age = this["age"];
var state = this["addr_state_code"];
var image = this["large_results_photo_url"];
var city = this["addr_city"];
if (sex = "m") {
sex = "Male";
}
if (sex = "f") {
sex = "Female";
}
$("#cats").slick('slickAdd',
"<div class='card top'>" +
"Hello! My name is" +
"<div class='name'>" + name + "</div>" +
"<div class='location'>" + city + ", " + state + "</div>" +
"<div class='sex-age'>" + sex + ", " + age + "</div>" +
"</div>"
);
});
});
});

Related

how to make each json data to an separate element

** i want to display the theaters like a child node element of the demo node and after i want to trigger the onclick event for other function...**
using only javascript
let VizagData = '{"theater":[' +
'{"TheaterName":"Sangam","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"Sarat","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"Melody","Quality":"4K","sound":"DolbyAtmos"}]}';
let VZMData = '{"theater":[' +
'{"TheaterName":"Srikanya","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"kameswari","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"IMAX","Quality":"4K","sound":"DolbyAtmos"}]}';
function search() {
document.getElementById('th').innerHTML = myfunction();
function myfunction() {
var value = document.getElementById('ct').value;
var th1 = document.createElement('div');
document.getElementById('th').appendChild(th1);
th1.innerHTML = "theaters in " + value;
return th1.innerHTML;
}
}
function data() {
var index = document.getElementById('ct');
var demo = document.getElementById("demo");
if(index.value === "vizag"){
const obj = JSON.parse(VizagData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
else {
const obj = JSON.parse(VZMData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
}
var go = document.getElementById('go');
addEventListener('click', search);
addEventListener('click', data);
<select id="ct">
<option value="vizianagaram">vizianagaram</option>
<option value="vizag">vizag</option>
</select>
<button id="go">GO</button>
<div class="th" id="th"></div>
<div id="demo"></div>

How to insert line break (enter) in Whatsapp message sent via jQuery

This is how I am sending whatsapp message via jQuery
var ques = "I";
var a = "am";
var b = "having";
var c = "a good";
var d = "time";
$(document).on("click", '.whatsapp', function() {
var whatsappMessage = ques + "\r\n\r\n" + a + "\r\n" + b + "\r\n" + c + "\r\n" + d;
var whatsapp_url = "whatsapp://send?text=" + whatsappMessage;
window.location.href = whatsapp_url;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showques" style="margin-left: 10px;font-size: 32px;">
</div>
<div style="width:300px;padding: 20px;background-color:#5755d9;">
<a class="whatsapp" style="font-size: 40px;color:white; text-decoration: none;">Whatsapp</a>
</div>
output = I \r\n\r\n am \r\n\r\n having \r\n\r\n a good \r\n\r\n time
I want an output like this:
I
am
having
a good
time
Add the following line in the code and it will work
whatsappMessage = window.encodeURIComponent(whatsappMessage);
$(document).on("click", '.whatsapp', function() {
var whatsappMessage = ques + "\r\n\r\n" + a + "\r\n" + b + "\r\n" + c + "\r\n" + d;
if( isMobile.any() ) {
whatsappMessage = window.encodeURIComponent(whatsappMessage);
var whatsapp_url = "whatsapp://send?text=" + whatsappMessage;
window.location.href = whatsapp_url;
} else {
alert("Please share this in mobile device");
}
});

How can I display a profile stored in a database after a SQL query in a Google Spreadsheet Sidebar?

Basically here is what I'm doing:
Storing a person profile in a MYSQL Database
Creating a google spreadsheet add-on with a sidebar
giving to the user the possibility to search profiles through the DB in the add-on
giving to the user the possibility to display the datas of the profile in the Sidebar in the add-on
So Imagine you want to search John but the input you've entered in the searchbar is the letter J. The result of this query will be Jack , Johnatan, Jules, Joe and John as they all have a J. All this names will appear as link for you to click on in order to have more datas displayed (age, picture, fullname, description...). Only problem is that the only way I've managed to achieve is by making a SQL query after each keyup in my HTML input then create X numbers (in this case 5) of hidden classes with the infos, that I can show by clicking on a created link.
So this can easily work for 5 results, but imagine there's 100 of them and you only want to see one of them. Sounds crazy to create 100 hidden divs with all the infos to finally show only one.
here is an example code
code.gs
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('UI_HTML');
SpreadsheetApp.getUi().showSidebar(ui);
}
//My function to search for profiles (returns an array with each lines found)
function searchProfile(entry){
var address = 'sql3.freemysqlhosting.net';
var user = 'user';
var userPwd = 'password';
var db = 'sql12345678910';
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.createStatement();
var ret = [];
var res = stmt.executeQuery('SELECT * FROM item WHERE name = "' + entry + '"'
+ ' OR fullname LIKE CONCAT("%", "' + entry + '", "%")'
+ ' OR description LIKE CONCAT("%", "' + entry + '", "%")');
var numCol = res.getMetaData().getColumnCount();
var i = 0;
var j = 0;
while (res.next())
{
j = 0;
if (!ret[i])
ret[i] = [];
while (j < numCol)
{
ret[i][j]= res.getString(j + 1);
j++;
}
i++;
}
return (ret);
}
UI_HTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.show {
display: block;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div>
<p>Search Profile</p>
<input type="text" id="searchProfile" onkeyup="searchProfileHTML()" placeholder="Search for ...">
<div id="results" ></div>
</div>
<script>
function searchProfileHTML()
{
var x = document.getElementById("searchProfile").value;
google.script.run
.withSuccessHandler(createLinks)
.searchProfile(x);
function createLinks(result)
{
$('.links').remove();
if (!x)
return (0);
$('#results').append('<ul></ul>');
$('#results ul').addClass('links');
result.forEach(function(el){
//My Link to show/hide my Div
$('.links').append('<li><a id="' + el[0] + '-link" href="#">' + el[0] + '</a><div id="' + el[0] + '" class ="hide" ></div></li>');
//My div with all the infos (hidden by default)
$('#' + el[0]).append(""
+ '<img src="' + el[14] + '" height="100" width="100">'
+ "<div>"
+ "<ul>"
+ "<li>Name: "+ el[0] + "</li>"
+ "<li>Full name: "+ el[1] + "</li>"
+ "<li>Description : "+ el[2] + "</li>"
+ "<li>email: "+ el[3] + "</li>"
+ "</ul>"
+ "</div>");
$('#' + el[0] + '-link').on("click", function(){
$('#' + el[0]).toggleClass("hide show");
})
});
}
}
</script>
Anyone has an idea how I can make this more lite?

i want to use ajax variable in other function

I want to use modal, so i get the data value from ajax.
the data is like that [{'source_name': '인터넷', 'description': '여행자료', 'source_slug': '_1', 'subject_name': '여행', 'subject_slug': '_6'}]
I want to put the value of source_name "인터넷" to source_name variable.
I want to use soure_name variable at this line.
html += '<li><span> 출처 : ' + source_name + ''
but source_name is undefined.
please help me
this is code.
function showModal(){
var pk = $(this).find('img').attr('id');
$.ajax({
url : '/photo/' + pk + '/',
async: false,
success: function(data){
data= JSON.stringify(data)
var source_slug = data[0]["source_slug"];
var source_name = data[0]["source_name"];
var description = data[0]["description"];
var subject_slug = data[0]["subject_slug"];
var subject_name = data[0]["subject_name"];
}
});
var src = $(this).find('img').attr('src');
var largeImg = $(this).find('img').attr('data-bsp-large-src');
if(typeof largeImg === 'string'){
src = largeImg;
}
var index = $(this).attr('data-bsp-li-index');
var ulIndex = $(this).parent('ul').attr('data-bsp-ul-index');
var ulId = $(this).parent('ul').attr('data-bsp-ul-id');
var theImg = $(this).find('img');
var pText = $(this).find('.text').html();
var modalText = typeof pText !== 'undefined' ? pText : 'undefined';
var alt = typeof theImg.attr('alt') == 'string' ? theImg.attr('alt') : null;
clicked.img = src;
clicked.prevImg = parseInt(index) - parseInt(1);
clicked.nextImg = parseInt(index) + parseInt(1);
clicked.ulIndex = ulIndex;
clicked.ulId = ulId;
$('#bsPhotoGalleryModal').modal();
var html = '';
var img = '<img src="' + clicked.img + '" class="img-responsive"/>';
html += img;
html += '<span class="' + settings.iconClose + ' bsp-close"></span>';
html += '<div class="bsp-text-container">';
html += '<li><span> 출처 : ' + source_name + ''
html += '</span></li>'
html += '<li><span> 과목 및 단원 :' + subject_name + ''
html += '<li><span>' + description + '</span></li>'
html += '</div>';
html += '<a class="bsp-controls next" data-bsp-id="'+clicked.ulId+'" href="'+ (clicked.nextImg) + '"><span class="' + settings.iconRight + '"></span></a>';
html += '<a class="bsp-controls previous" data-bsp-id="'+clicked.ulId+'" href="' + (clicked.prevImg) + '"><span class="' + settings.iconLeft + '"></span></a>';
$('#bsPhotoGalleryModal .modal-body').html(html);
$('.bsp-close').on('click', closeModal);
showHideControls();
}
You need to make the change inside success not after:
function showModal(){
var pk = $(this).find('img').attr('id');
$.ajax({
url : '/photo/' + pk + '/',
async: false,
success: function(data){
data= JSON.stringify(data)
var source_slug = data[0]["source_slug"];
var source_name = data[0]["source_name"];
var description = data[0]["description"];
var subject_slug = data[0]["subject_slug"];
var subject_name = data[0]["subject_name"];
var src = $(this).find('img').attr('src');
var largeImg = $(this).find('img').attr('data-bsp-large-src');
if(typeof largeImg === 'string'){
src = largeImg;
}
var index = $(this).attr('data-bsp-li-index');
var ulIndex = $(this).parent('ul').attr('data-bsp-ul-index');
var ulId = $(this).parent('ul').attr('data-bsp-ul-id');
var theImg = $(this).find('img');
var pText = $(this).find('.text').html();
var modalText = typeof pText !== 'undefined' ? pText : 'undefined';
var alt = typeof theImg.attr('alt') == 'string' ? theImg.attr('alt') : null;
clicked.img = src;
clicked.prevImg = parseInt(index) - parseInt(1);
clicked.nextImg = parseInt(index) + parseInt(1);
clicked.ulIndex = ulIndex;
clicked.ulId = ulId;
$('#bsPhotoGalleryModal').modal();
var html = '';
var img = '<img src="' + clicked.img + '" class="img-responsive"/>';
html += img;
html += '<span class="' + settings.iconClose + ' bsp-close"></span>';
html += '<div class="bsp-text-container">';
html += '<li><span> 출처 : ' + source_name + ''
html += '</span></li>'
html += '<li><span> 과목 및 단원 :' + subject_name + ''
html += '<li><span>' + description + '</span></li>'
html += '</div>';
html += '<a class="bsp-controls next" data-bsp-id="'+clicked.ulId+'" href="'+ (clicked.nextImg) + '"><span class="' + settings.iconRight + '"></span></a>';
html += '<a class="bsp-controls previous" data-bsp-id="'+clicked.ulId+'" href="' + (clicked.prevImg) + '"><span class="' + settings.iconLeft + '"></span></a>';
$('#bsPhotoGalleryModal .modal-body').html(html);
$('.bsp-close').on('click', closeModal);
showHideControls();
}
});}

Converting html to Json object

I'm currently working on a project where I need to convert some older code into a json object. We're taking the result set from a sql query and returning the categories it gives back as json. I'm not that well versed in javascript let alone json so I'm not sure what's the simplest way to go about this. Here is the function I need to change into JSON:
function createOutputCategories(){
try
{
output =
"<html>" +
"<head>" +
"<title>" +
"You can find it!" +
"</title>" +
"</head>" +
"<body bgcolor='#CED3F3'>" +
"<a href='" + url + "file.xsjs?parent=1'>" +
"</a>" +
"<br><br>";
if(parent === "1"){
output = output + "<h3><font color='#AAAAAA'>Home</font>";
}else{
output = output +"<a href='javascript:history.back()'>" +
"<h3>Back";
}
output = output +
"</h3>" +
"</a>" +
"<h1>" +
"Categories:" +
"</h1>";
while(rs.next()){
if(rs.getString(3) === 0 || rs.getString(3) === null || rs.getString(3) === undefined || rs.getString(3) === "0" ){
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(2) + "</a>";
}else{
output = output + "<br><a href='" + url + "yeti.xsjs?parent=" + rs.getString(1) + "'>" + rs.getString(3) + "</a>";
}
}
}catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
Here is what I have so far but I am not returning a valid JSON object:
function createOutputCategories(){
try{
output =
"category: {name = \"" + parent + "\"; description = \"\"}";
output = output +
"subcategories: [ ";
while(rs.next()){
output = output +
"{ catid = \"" + rs.getString(1) + "\"; catname = \"" + rs.getString(2) + "\"; altname = \"" + rs.getString(3) + "\"; description = \"" + rs.getString(4) + "\"}";
}
output = output +
"];";
}
catch(Exception){
$.response.contentType = "text/plain";
$.response.setBody( "Failed to retreive data" );
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
If I need to provide anything else please let me know! Thanks!
Do you want to output a javascript object to a string?
Construct the object:
var category=new Object();
category.name="Name";
category.description="My lovely description";
category.subcategories=[];
var subCat=new Object();
subCat.catid=1;
subCat.catname="My subcat";
category.subcategories.push(subCat);
Alternatively, you could construct the object using literals:
var category={
name:"Name",
description:"My lovely description",
subcategories:[
{catid:1,catname:"My subcat"}
]
};
Then return the object as string.
return JSON.stringify(category);
A reference to Javascript objects if you need more help:
http://www.w3schools.com/js/js_objects.asp