Fetch results from json - javascript

I have a bootstrap live search for pixabay api. But I have a problem with results from pixabay.
For example, I want to search images with query flowers but its returning results when i start typing. I type flo and i have a images with tag flo.
At the end I have links to images with tag flow flowe and flowers.
How to prevent this situation?
$('#search').keyup(function(){
var q = $(this).val().toLowerCase();
var API_KEY = 'xx';
var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent(q);
$.getJSON(URL, function(data){
if (parseInt(data.totalHits) > 0)
$.each(data.hits, function(i, hit){
htmlData = '<div class="col"><img src="'+hit.largeImageURL+'" class="img-fluid" alt=""/></div>';
$('.modal-body').append(htmlData);
});
else
console.log('No hits');
});
});
How to load expected images dynamically into modal?
Also how to remove images when i remove few chars from search bar?
If i put flowers It load flowers into modal, but when i type cars I want to show only cars, not flowers and cars.

There's two things you need to do to fix this behaviour. The first is to 'debounce' the event so that the AJAX request is only made when typing has finished for a short delay, eg. 150ms. The second is to wipe all previous results from the UI before you add the latest ones. Try this:
var searchTimeout;
$('#search').keyup(function() {
var q = $(this).val().toLowerCase();
var API_KEY = 'xx';
var URL = "https://pixabay.com/api/?key=" + API_KEY + "&q=" + encodeURIComponent(q);
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
$.getJSON(URL, function(data) {
if (parseInt(data.totalHits) > 0) {
var htmlData = data.hits.map(function(hit) {
return `<div class="col"><img src="${hit.largeImageURL}" class="img-fluid" alt=""/></div>`;
});
$('.modal-body').html(htmlData); // note 'html()' here. It will overwrite all existing content
} else {
console.log('No hits');
}
});
}, 150);
});

Related

How to use different blogger post ID in Javascript variable?

I am trying to make every article views having comma separated every 3 digit number. I have found the code for that.
But I have problem to find specific blogger post ID to use for the code to work fine.
Here's the whole code that I am trying to work on.
<--Viewable area /-->
<span class='entry-time'><b:if cond='data:allBylineItems.author and data:allBylineItems.timestamp.label'><span class='on'><data:allBylineItems.timestamp.label/></span></b:if><time class='published' expr:datetime='data:post.date.iso8601'><data:post.date/></time></span><span class='postviews1' style='margin-left:5px; display:display;'><a expr:name='data:post.id'/> <i class='far fa-eye'/> <span id='bacani'><span id='postviews'/></span> Views</span>
<--comma separated every 3 digit /-->
<script>var angka = document.getElementById('bacani').textContent;var reverse = angka.toString().split('').reverse().join(''),ribuan = reverse.match(/\d{1,3}/g);ribuan = ribuan.join(',').split('').reverse().join('');document.getElementById('bacani').innerHTML= ribuan;</script>
<--code for views count /-->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/> <script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); });</script>
I want to change:
<span id='bacani'><span id='postviews'/></span>
and
document.getElementById('bacani').textContent;
to have a specific value id which is post id from blogger. The only thing that i found from internet is
<data:post.id>
Is there any other way that i can make it work other than what I am thinking right now? I think I need specific new id to make it work for every article to have comma separated every 3 digit.
I try to use the code but it only work for one time only. I believe to make it work as a whole I need to use different code to read specific unique id base on data:.post.id from blogger post id itself. But i do not sure how to make it work. I am expecting when I know how to use different method which is making new code that find unique id for different article it would work fine.
You can just replace elem.text(data.value) to
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
The full code would be
<!-- code for views count -->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/>
<script>
/*<![CDATA[*/
$.each($("a[name]"), function (i, e) {
var elem = $(e).parent().find("#postviews");
var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name"));
blogStats.once("value", function (snapshot) {
var data = snapshot.val();
var isnew = false;
if (data == null) {
data = {};
data.value = 0;
data.url = window.location.href;
data.id = $(e).attr("name");
isnew = true;
}
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
data.value++;
if (window.location.pathname !== "/") {
if (isnew) blogStats.set(data); else blogStats.child("value").set(data.value);
}
});
});
/*]]>*/
</script>

SCRIPT5007: Unable to get property 'toLowerCase' of undefined or null reference

I have a .aspx file working on SharePoint.
We are using IE11, jQuery 2.2.3, jQuery UI 1.11.4, Bootstrap 3.3.6
We had this system for around three years by a third party, which we stopped business. And not able to contact anymore.
It was working fine until a few weeks ago suddenly the page is loading forever and showing this error
SCRIPT5007: Unable to get property 'toLowerCase' of undefined or null reference
Loading page - capture
I have Googled and it seems like the script is waiting for ConfigurationCube.js to load. But since it's not loading, I think it's waiting forever.
/* handles the displaying of all outstanding items requiring approval*/
var TableCreated=0;
var app="";
var teamsArr = [];
var GlobalDivisionsArr = [];
$(document).ready(function(){
//check to see if the Configuration cube Obj Exists and wait until it does
var checkExist = setInterval(function() {
if (sessionStorage["ConfigurationCube"] != null) {
app = JSON.parse(sessionStorage.ConfigurationCube).AppURL;
/**CreateLookupSectionForEmployees("My Winners","Kaizen List","#ViewWinnersTable");**/
//Displayed using the configuration cube.js file
DisplayUserInformation();
popDD("kznSearchCategory",JSON.parse(sessionStorage.ConfigurationCube).ListOfCategories);
IntialPopulationOfApprovedKaizens("","Kaizen List","#kznSearchResultsTable");
//Initialize date range picker
/**$("#kznEditToDate").datepicker();*/
var CubeMin = (JSON.parse(sessionStorage.ConfigurationCube).SubmissionPeriod).split(" ")[0];
clearInterval(checkExist);
}
}, 500);
});
I also tried in IE8, 9, 10, Edge. All not working.
Our company does not allow Chrome or any other browser so we need to get it work in IE..
My current meta tag is like this. Also tried various ways, but did not work.
<meta http-equiv="x-ua-compatible" content="IE=edge; charset=UTF-8">
Does anyone have any similar problems?
Any kind of idea is appreciated..
When clicking on the error, it directs to ConfigutationCube.js
//Tools for other pages
function compareStrings(a, b) {
// Assuming you want case-insensitive comparison
a = a.toLowerCase();
b = b.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
Script snip from SearchKaizen.js
function IntialPopulationOfApprovedKaizens(HeadingTitle,ListName,ElementToAppend){
//Get all current data from lists
var GetKaizenPromise = GetList( "Kaizen List",
"Id,Nominated_x0020_person, Status, Kaizen_x0020_Title,Division/Id, Team/Id,Division/Title, Team/Title, Name, Financial_x0020_Year, Kaizen_x0020_Category,Quarter",
"Division/Id, Team/Id,Division/Title, Team/Title",
"Status eq 'Approved'",
app);
$.when(GetKaizenPromise).done(function(KaizenSelectionData){
var EditButton = "";
var Results = KaizenSelectionData.d.results;
//Creates table structure and heading
var DataTableHtml = "";
var SetVotedBackground = "style='background-color:lightgreen;color:white;'";
var DivisionList = [];
var TeamList = [];
var YearList = [];
var DivisionCheck = [];
var TeamCheck = [];
if(Results.length > 0){
for(r=0;Results.length > r;r++){
TableCreated++;
var ResultsName = Results[r].Nominated_x0020_person;
var KaizenTitle = Results[r].Kaizen_x0020_Title;
var ResultsTeam = Results[r].Team.Title;
var ResultsDivision = Results[r].Division.Title;
var ResultsTeamId = Results[r].Team.Id;
var ResultsDivisionId = Results[r].Division.Id;
var ResultsCategory = Results[r].Kaizen_x0020_Category;
var ResultsStatus = Results[r].Status;
var ResultsQuarter = Results[r].Quarter;
var ResultsYear = Results[r].Financial_x0020_Year;
EditButton = "<p style='cursor:pointer;' class='edititem text-light-blue' data-itemid='"+Results[r].Id+"' data-listname='"+ListName+"'><i class='fa fa-edit'></i> View</p>";
DataTableHtml += "<tr>"+
"<td>"+ResultsName+"</td><td>"+ResultsDivision+"</td><td>"+ResultsTeam +"</td>"+
"<td>"+ResultsYear+"</td><td>"+ResultsQuarter+"</td><td>"+KaizenTitle +"</td>"+
"<td>"+ResultsCategory +"</td><td>"+EditButton+"</td>"
"</tr>";
//Create the drop down box info from all the results
if($.inArray(ResultsDivision , DivisionCheck ) == -1){
// Add to departments list
DivisionList.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
DivisionCheck.push(ResultsDivision);
//Keep duplicate of original divisions list
GlobalDivisionsArr.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
}
if($.inArray(ResultsTeam , TeamCheck) == -1){
// Add to Teams list
TeamList .push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
TeamCheck.push(ResultsTeam);
//Keep duplicates of original list
teamsArr.push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
}
if($.inArray(ResultsYear , YearList) == -1){
// Add to Year list
YearList.push(ResultsYear );
}
//next Item
}
}else{
//if there are no results
DataTableHtml = "<tr>"+
"<td colspan='8'>No results found</td>" +
"</tr>";
}
YearList.sort();
YearList.reverse();
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
popDD("kznSearchYear",YearList);
popDDSearchWithDataAttr("kznSearchTeam",TeamList,TeamList);
DivisionList.unshift({"FullName": "All","ID":"All"}); //Add All option to division list
popDDVal("kznSearchDivision",DivisionList);
//adds items to DOM
$(ElementToAppend + " tbody").html(DataTableHtml);
//Create column match with returned results
if (Results.length>0){
$.fn.dataTable.ext.errMode = 'console';
$(ElementToAppend).DataTable({
"dom": 'ftipr',
"responsive": true
});
}
$("body").css("overflow","");
//removes overlayer and loading symbol
$("#OverlayFade").addClass("hidden");
$("#Timer").addClass("hidden");
});
}
This snip of the script has popDDVal, and it looks like 'DivisionList' 'TeamList' 'YearList' is returning null. Since this is null it can not break from the loading overlayer.
I was able to narrow it down to this part.
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
Changed it to this, and it worked. But obviously the sorting is not sorted correctly, but least it works now...
TeamList.sort();
DivisionList.sort();
Instead of passing in an anonymous function pass the function name:
TeamList.sort(compareStrings);
or
DivisionList.sort(compareStrings);

Merge duplicate URLs into 1 URL, Javascript

I have function, which shows / outputs the urls from the textarea. At the moment however it won't merge duplicates into 1 URL. How can I output same urls as one (Merge http://google.com, www.google.com, http://www.google.com, or just google.com)?
At the moment:
Should be:
My Code:
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/[^\s]+)/g;
$("#textarea").val().replace(urlRegex, function(url) {
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea>
<div id="converted_url"></div>
JS FIDDLE
Credits
Scott Marcus, Stackoverflow
Simple fix: store matched urls in array and append link only if url is not present in that array.
UPDATE: changed regex to /((https?:\/\/|www\.|\/\/)[^\s]+)/g so it matches links starting with http://, https://, www., //. You may use any other regex covering other cases (like http://www.) just modify stored url so that you'll be able to compare it (you may want to treat http and https link as unique).
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /((https?:\/\/|www\.|\/\/)[^\s]+)/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
let trimmedUrl = url.replace(/^(https?:\/\/|www\.|\/\/)/, "");
if (found.includes(trimmedUrl)) {
return;
}
found.push(trimmedUrl);
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
var link = "";
var protOmmitedURL = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
if (found.includes(protOmmitedURL)) {
return;
}else
{
link = '<div>' + url + '</div>';
found.push(protOmmitedURL);
}
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>

loop posting ajax results until they are all posted

the below code works great for displaying in my first file
$.ajax({
url : "http://localhost/website/files/userstuff/files/",
asynch : false,
cache : false,
success: function (data) {
$(data).find("a").each(function(i, el) {
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("#filestable").html(displayfilestable)
$("filestable, table").append(adddata);
console.log(adddata)
}
});
}
});
this code will as you would think pull and display the files in the table row, however it is only performing this for the first file it finds I was wondering if anyone here could help get this to display all of the files in the files folder in the table. thanks in advance
enter image description here
Your code just works fine. The problems is, in that loop (each) you keep re-create table. That why it show only 1 data. Check my example based on your code.
HTML
<div>
sad1.pdf<br>
sad2.pdf<br>
sad3.pdf
<div id="filestable"></div>
</div>
JAVASCRIPT
var displayfilestable = ("<table><thead><tr><th>Files</th></tr></table>");
$("#filestable").html(displayfilestable);
$("DIV").find("a").each(function(i, el) { // this is your data
var val = $(el).attr('href');
if (val.match(/\.(pdf|doc|docx|txt|html|js|css|rar|7zip)$/)) {
var fileslocation = ("http://localhost/website/files/userstuff/files/" + val)
var adddata = ("<tr><td><a href='"+ fileslocation +"'target='_blank'>"+ val +"</td></tr>");
$("filestable, table").append(adddata);
console.log(adddata)
}
});
AND Jsfiddle here :https://jsfiddle.net/synz/yrag1zpr/

How can I delete the selected messages (with checkboxes) in jQuery?

I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
if ($('#checkbox_' + id).is(':checked')) {
$('#' + id).addClass("selected");
}
else {
$('#' + id).removeClass("selected");
}
}
But, I don't know where to go from there.
Here is some example markup for one of the lines [generated by PHP] of the list of messages:
<div class="line" id="33" >
<span class="inbox_check_holder">
<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />
<span class="star_clicker" id="star_33" onclick="addStar(33)" title="Not starred">
<img id="starimg_33" class="not_starred" src="images/blank.gif">
</span>
</span>
<div class="line_inner" style="display: inline-block;" onclick="readMessage(33, 'Test')">
<span class="inbox_from">Nathan</span>
<span class="inbox_subject" id="subject_33">Test</span>
<span class="inbox_time" id="time_33" title="">[Time sent]</span>
</div>
</div>
As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {
}
else {
alertBox('No messages selected.'); //this is a custom function
}
});
I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!
How about this
$('#delete').click(function() {
var checked = $('.inbox_check:checked');
var ids = checked.map(function() {
return this.value; // why not store the message id in the value?
}).get().join(",");
if (ids) {
$.post(deleteUrl, {idsToDelete:ids}, function() {
checked.closest(".line").remove();
});
}
else {
alertBox('No messages selected.'); // this is a custom function
}
});
Edit: Just as a side comment, you don't need to be generating those incremental ids. You can eliminate a lot of that string parsing and leverage jQuery instead. First, store the message id in the value of the checkbox. Then, in any click handler for a given line:
var line = $(this).closest(".line"); // the current line
var isSelected = line.has(":checked"); // true if the checkbox is checked
var msgId = line.find(":checkbox").val(); // the message id
var starImg = line.find(".star_clicker img"); // the star image
Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
var result = null;
var scriptUrl = './databaseDelete.php';
$.ajax({
url: scriptUrl,
type: 'post',
async: false,
data: {id: reference_id},
success: function(response)
{
result = response;
}
)};
return result;
}
$('.inbox_check').each(function(){
if ($(this).is(':checked')){
var row = $(this).parent().parent();
var id = row.attr('id');
if (id == null)
{
alert('My selector needs updating');
return false;
}
var debug = 'Deleting ' + id + ' now...';
if (console) console.log(debug);
else alert(debug);
row.remove();
var response = removeDatabaseEntry(id);
// Tell the user something happened
$('#response_div').html(response);
}
});

Categories

Resources