I have a page with just the search bar; I wish to pull in content from an API, filter them on input[search], then display matches on the page. More like what this plugin does: https://lscf.pixolette.com/photography/ How can I achieve this, please?
Currently, I have this code. What am i doing wrong, please?
const search = document.getElementById('search_box');
const searchResults = document.getElementById('search-results');
const searchMessage = document.getElementById('search-message');
let users;
// Get users
const getUsers = async () => {
const res = await fetch('baseUrl/wp-json/wp/v2/posts');
users = await res.json();
};
// FIlter states
const searchUsers = searchText => {
// Get matches to current text input
let matches = users.filter(user => {
const regex = new RegExp(`^${searchText}`, 'gi');
// return user.displayName.match(regex) ||
user.abbr.match(regex);
});
console.log(matches);
// Clear when input or matches are empty
if (searchText.length === 0) {
matches = [];
searchResults.innerHTML = '';
}
outputHtml(matches);
};
// Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
const html = matches.map(match =>
`<div class="card card-body mb-1">
<h4>${match.title.rendered} (${match.id})
<span class="text-primary">${match.userPrincipalName}.
</span></h4>
<small>ID: ${match.id} / Language:
${match.preferredLanguage}</small>
</div>`
)
.join('');
searchResults.innerHTML = html;
}
};
window.addEventListener('DOMContentLoaded', getUsers);
search.addEventListener('input', () => searchUsers(search.value));
An example using the WordPress API
Search box
<div>
<h4>Search blog by title</h4>
<div class="form-group ">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by slug e.g my-title" onfocus="this.value=''" >
</div>
</div>
DISPLAY RESULTS
<table id='results'>
</table>
SEARCH BOX AJAX
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)
//on keyup, start the countdown
$('#search_box').keyup(function(){
clearTimeout(typingTimer);
if ($('#search_box').val()) {
var text = $('#search_box').val();
typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
}
});
//user is "finished typing," do something
function doneTyping (text) {
//do something
// var text = text;
var api_url_search = `/wordpress/wp-json/wp/v2/posts?slug=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var date = response[i].date_gmt;
var slug = response[i].slug;
var excerpt = response[i].excerpt.rendered;
var categories = response[i].categories;
var search_str =
'<td>'+
'<div class="card" style="width: 300px;">' +
'<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +
' <div class="card-section">' +
'<p>' + excerpt + '</p>' +
'<h4>' + date + '</h4>' +
'<h4>' + 'Category:' + categories + '</h4>' +
'<a href="somepage.php?">'+
'<input type="button" value="read more">' + '</input>' +
' </a>' +
' </div>' +
'</div>'+
'</td>'
;
$('#results').empty().append(search_str);
}
}
});
};
Related
I want to get value of dropdownlist and show textbox but my code dont working
This is my code:
Controller:
public function socaucuachuong($id)
{
$units = CauHoi::groupBy('chuong')->select('chuong', CauHoi::raw('count(id) as Total'))->where('idmonthi','=', $id)->get()->toArray();
return view('DeThi::dethi',compact('units'));
}
View: dethi.blade.php
$('select').select();
function get_units() {
var id = $('#id_select').val();
var list = $('#dschuong');
list.empty();
var url = "{{ route('dthi.socaucuachuong') }}"+'/'+id;
var success = function (result) {
if (result.length <= 0) {
var item = '<div class="input-field"><input type="text" disabled value="Môn này hiện chưa có câu hỏi nào"></div>';
list.append(item);
} else {
for (i = 0; i < result.length; i++) {
var item = '<div class="input-field"><label for="unit-' + result[i].chuong+ '">Nhập số câu hỏi chương ' + result[i].chuong+ ' (có ' + result[i].Total + ' câu) <span class="failed">(*)</span></label><input type="number" max="' + result[i].Total + '" class="unit_input" onchange="set_sum(' + result[i].Total + ')" name="unit-' + result[i].chuong+ '" id="unit-' + result[i].chuong+ '" required></div>';
list.append(item);
}
}
};
$.get(url, success);
}
Route:
Route::get('dethi/socau', 'App\Modules\DeThi\Controllers\DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
Route::resource('dethi', DeThiController::class);
And my error when I select dropdownlist:
How can I fix this?
You are missing a route parameter for the ID you're passing along.
https://laravel.com/docs/8.x/routing#required-parameters
Basically, your route needs to be updated to
Route::get('dethi/socau/{id}', 'App\Modules\DeThi\Controllers\DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
Route
Route::get('dethi/socau/{id}', 'App\Modules\DeThi\Controllers\DeThiController#socaucuachuong')->name('dethi.socaucuachuong');
Javascript (blade)
var url = '{{ "dthi.socaucuachuong", ":id") }}';
url = url.replace(':id', id);
This is the js file. What im trying to do is create an onclick delete function when clicked on a particular row in html page. So far i can get the child key(nesting) but somehow the delete function throws error i.e career-delete.html:1 Uncaught ReferenceError: MCu9V4ypS is not defined
at HTMLButtonElement.onclick (career-delete.html:1).
userImagesRef1.once("value", function(snapshot) {
var val1, val2, val3;
var ParentKey = snapshot.key;
console.log("PK"+ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
var childKey = snap.key;
console.log("CK" + childKey);
var Vacancy = snap.child("VacancyNumber").val();
console.log("VacancyNumber" + Vacancy);
// var NoticeNumber = snap.child("Service").val();
// var NameofWork = snap.child("Title").val();
snap.child('pictures').forEach(function(openPicturesSnap){
console.log("KEY LINKS: " + openPicturesSnap.key);
// var i = 0;
if(openPicturesSnap.key == 0){
val1 = openPicturesSnap.val();
// console.log("LINKS1111::::" + val1 );
}
if(openPicturesSnap.key == 1){
val2 = openPicturesSnap.val();
}
if(openPicturesSnap.key == 3){
val1 = openPicturesSnap.val();
}
})
var Service = String(snap.child("Service").val());
// console.log(Service)
var ts = snap.child("timestamp").val();
// console.log("TS:" + ts);
var Title = String(snap.child("Title").val());
// console.log(Title)
let Numberofposts = String(snap.child("NumberofPosts").val());
// console.log(Numberofposts);
var SNo = "";
var State = snap.child("Status").val();
var IssueDate = snap.child("IssueDate").val();
var ClosingDate = snap.child("ClosingDate").val();
var Remarks = String(snap.child("Remarks").val());
$("#tableBody").append("<tr><td>"+ SNo +"</td><td><a href = '" + val1+ "'>" +Vacancy+"</a></td>"+ "<td><a href = '" +val2 + "'>" +Service+"</a></td><td>" + Title + "</td><td>"+Numberofposts+"</td><td>" + IssueDate + "</td><td>"+ClosingDate + "</td> <td>" + State+"<td><a href = '" +val3 + "'>" +Remarks+"</a>"+ "</td><td>"+'<button type="button" onClick=Delete('+childKey+'); class="btn delete">X</button>'+"</td></tr>" );
})
})
function Delete(key){
var feedRef = firebase.database().ref("user-images").child(key);
feedRef.remove()
.then(function(){
console.log("Remove succeeded.")
alert("Added");
// console.log(key.val());
})
.catch(function(error){
console.log("Remove Failed!"+error.message)
});
}
});
You can delete nodes by using the following alternative:
feedRef.set(null);
https://firebase.google.com/docs/database/web/read-and-write#delete_data
You need to add some double quotes as follows:
<button type="button" onclick="Delete('" +childKey+ "');" class="btn delete">X</button>
I have been able to get a list of posts on a php web page (outside of WordPress). How can I use the search box to filter the existing results by blog title(search term).
Here is my search box
<div class="sbox">
<h4>Search blog by title</h4>
<div class="form-group ">
<input type="text" name="search_box" id="search_box" class="form-control" placeholder="Search by title, author or category" >
</div>
</div>
Here is my ajax attempt
$('#search_box').keyup(function(){
var text = $('#search_box').val();
var api_url_search = `http://example.com/wordpress/wp-json/wp/v2/posts?filter[s]=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var title = response[i].title.rendered;
var search_str =
'<li>'+
'<p>' + title + '</p>' +
'</li>'
;
$('#results').append(search_str);
}
}
});
});
It seems to be looping through every letter that is typed and returning all posts for each letter.
I found the answer. The WordPress api won't enable you to filter by title but you can filter by slug. So the user has to type the title with hyphens (e.g my-title)
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)
//on keyup, start the countdown
$('#search_box').keyup(function(){
clearTimeout(typingTimer);
if ($('#search_box').val()) {
var text = $('#search_box').val();
typingTimer = setTimeout(doneTyping(text), doneTypingInterval)
}
});
//user is "finished typing," do something
function doneTyping (text) {
// var text = text;
var api_url_search = `http://examle.com/wordpress/wp-json/wp/v2/posts?slug=${text}`;
$.ajax({
url:api_url_search,
dataType: 'json',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var date = response[i].date_gmt;
var slug = response[i].slug;
var excerpt = response[i].excerpt.rendered;
var categories = response[i].categories;
var search_str =
'<td>'+
'<div class="card" style="width: 300px;">' +
'<div class="card-divider">' + (i+1) + ' ' + slug + '</div>' +
' <div class="card-section">' +
'<p>' + excerpt + '</p>' +
'<h4>' + date + '</h4>' +
'<h4>' + 'Category:' + categories + '</h4>' +
'<a href="http://example.com/api-posts.php?">'+
'<input type="button" value="read more">' + '</input>' +
' </a>' +
' </div>' +
'</div>'+
'</td>'
;
$('#results').empty().append(search_str); // empty previous results and append new results
}
}
});
};
<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries');
this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "popultns" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var pop = el2.value;
if (country2)
{ // Add the new value
loadTableData.push(country2.trim() );
// Reset input value
el.value = '';
//el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
the image is the ui tht im working for the function
I'm supposed to auto-generate the table based on the data available from my main.js script which is in JSon format. There is no problem with the data loading since the data can be display in my html file. However, the problem comes whn my data is returned undefined on my auto generated table whn i click the 'add' button to update the data in the table. Whn i click in the edit button, the data is get correctly. only whn the display, it returns me undefined.
i know how alrdy.
here i attach the code & sample of the data i hv done.
hopefully this would help fresh grad like me who hv trouble in undrsntdng CRUD
<html>
<head>
<meta charset="UTF-8">
<title>Countries CRUD</title>
<style>
input[type='submit'], button, [aria-label]{
cursor: pointer;
}
#spoiler{
display: none;
}
</style>
</head>
<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries' && 'popultns');
//this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "populations" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var popltn = el2.value;
if (country2 && popltn )
{ // Add the new value
//loadTableData.push(country2.trim() );
loadTableData.push({country: country2, population:popltn});
// Reset input value
el.value = '';
el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
this.Edit = function (item)
{ var el3 = document.getElementById('edit-name');
var el4 = document.getElementById('edit-popu');
// Display value in the field
let index = item;
el3.value = loadTableData[index].country;
el4.value = loadTableData[index].population;
// Display fields
document.getElementById('spoiler').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function()
{
// Get value
var country2 = el3.value;
var popltn = el4.value;
//console.log({country2, pop});
if (country2 || pop)
//console.log(country2);
{ // Edit value (strt,del,replace)
console.log(country2,popltn);
console.log(index, 1,({country2,popltn}));
//update array
loadTableData[index].country = el3.value;
loadTableData[index].population = el4.value;
//self.loadTableData.splice(index, 1,({country2,popltn}));
//console.log(index, 1, pop.trim());
//self.loadTableData.splice(index, 1, pop.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item)
{
// Delete the current row
loadTableData.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput()
{ document.getElementById('spoiler').style.display = 'none';}
</script>
</body>
</html>
I need to set href to Javascript function. When I click it, nothing happens, but when I hover over link it displays:
unsafe:javascript:ShowManagementdDiv('65','a60f2a16-267e-418d-bb14-d88de3a33b5f','0');
The table data is built dynamically in my angular controller:
contractorService.getemrtabulation()
.success(function (data) {
$scope.emrcolumns = data.EMRTabulationColumns;
repeatRow = '<td align="center" valign="middle" style="background-color:Transparent;border-color:Black;border-width:1px;border-style:Solid;padding:5px;white-space:nowrap;"><a class="IncidentColumn" ng-href={{e.hyper}}>Click Here to Review EMR Document</a></td>';
firstRow = '<td>EMR Document</td>';
for (i = 0; i < $scope.emrcolumns.length; i++) {
repeatRow = repeatRow + '<td>{{e.' + $scope.emrcolumns[i].vchAssociatedDetailColumn + '}}</td>';
firstRow = firstRow + '<td>' + $scope.emrcolumns[i].vchColumnHeaderText + '</td>'
}
firstRow = '<tr>' + firstRow + '</tr>';
$scope.emrdetail = data.EMRTabulationDetail;
angular.forEach($scope.emrdetail, function (value, key) {
value.dteExpirationDate = convertDate(value.dteExpirationDate);
value.dteDateCompleted = convertDate(value.dteDateCompleted);
value.dteEffectiveDate = convertDate(value.dteEffectiveDate);
});
angular.forEach($scope.emrdetail, function (value, key) {
contractorService.getimage(value.EMRDetailID, value.dteEffectiveDate)
.success(function (data) {
$scope.emrdetail[key].hyper = data;
});
});
$scope.emrTable = '<table>' + firstRow + '<tr style="text-align:center" ng-repeat="e in emrdetail">' + repeatRow + '</tr></table>';
firstRow = '';
repeatRow = '';
});
I use this to call it in the html:
<div class="row row-relative">
<div class="col-md-12">
<div>{{emrQuestion.EMRTabulationID}}{{emrQuestion.vchTabulationSequenceLetter}}. {{emrQuestion.vchClassPropertyName}}</div><br />
<div dynamic="emrTable"></div><br /><br />
</div>
</div>
The function is in a <script> tag on the page:
function ShowManagementdDiv(imageTypeID, Guid, selectedYear) {
var TargetWidth = 950;
var TargetHeight = 670;
bModalPopupActivated = true; window.clearTimeout(t);
DisplayModalDivExitWithClickSave('box', TargetWidth, TargetHeight, 'http://localhost/PECIMS/DocumentManagement.aspx?eid=' + imageTypeID + '&Edx=' + Guid + '&y=' + selectedYear, 'Close', 'Click to close window. ');
}
Here is the C# code that creates the link:
public async Task<ActionResult> GetImage(int emrDetailID, string docDate)
{
var columns = await CommonClient.GetEMRTabulationColumnsForClusterID(876);
var getcolumn = columns.FirstOrDefault(c => c.EMRTabulationColumnID == 1);
int? imageTypeId = getcolumn.EdataFileImageTypeID;
UserInfo.intDocumentManagementMode = 13;
UserInfo.intPerspectiveCompanyID = UserInfo.intMajorID;
UserInfo.intPerspectiveCompanyTypeID = UserInfo.intMajorCompanyType;
UserInfo.SegmentID = emrDetailID;
UserInfo.dteDocumentDate = DateTime.Parse(docDate);
var token = await CompanyClient.SaveRecallData(UserInfo);
string strPathAndQuery = Request.Url.PathAndQuery;
string strUrl = Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
string LinkToImagesApp = "";
LinkToImagesApp = AppendProtocolAndHostHeadersPathToWebConfigPath("LinkToImagesApplication");
string javaLink = strUrl + LinkToImagesApp + "/DocumentManagement.aspx?eid=";
string docLink;
string address = "javascript:ShowManagementdDiv('" + imageTypeId + "','" + token + "','0');";
return Json(address, JsonRequestBehavior.AllowGet);
}
I am assuming that the issue is that Angular deems the Javascript as "unsafe". Any assistance is greatly appreciated.
In order to use the Javascript function in my href I had to add the following to my app.js file:
app.config([
'$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|javascript):/);
}
]);