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
}
}
});
};
Possible duplicate Nested elements
I'm getting from server-side ajax response (Json) and I'm trying to dynamically create table rows and append them to an existing table with id=records_table.
I tried to implement the solution in possible duplicate but it failed.
My response looks like that:
'[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]'
the require result is something like that:
<tr>
<td>9</td>
<td>Alon</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>Tala</td>
<td>5</td>
</tr>
I want to do something without parsing the Json so I tried to do the following, which of course was a disaster:
function responseHandler(response)
{
$(function() {
$.each(response, function(i, item) {
$('<tr>').html(
$('td').text(item.rank),
$('td').text(item.content),
$('td').text(item.UID)
).appendTo('#records_table');
});
});
}
From my solution I get only one row with the number 6 in all cells. What am I doing wrong?
Use .append instead of .html
var response = "[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]";
// convert string to JSON
response = $.parseJSON(response);
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.rank),
$('<td>').text(item.content),
$('<td>').text(item.UID)
); //.appendTo('#records_table');
console.log($tr.wrap('<p>').html());
});
});
Try this (DEMO link updated):
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
Fiddle DEMO WITH AJAX
Here is a complete answer from hmkcode.com
If we have such JSON data
// JSON Data
var articles = [
{
"title":"Title 1",
"url":"URL 1",
"categories":["jQuery"],
"tags":["jquery","json","$.each"]
},
{
"title":"Title 2",
"url":"URL 2",
"categories":["Java"],
"tags":["java","json","jquery"]
}
];
And we want to view in this Table structure
<table id="added-articles" class="table">
<tr>
<th>Title</th>
<th>Categories</th>
<th>Tags</th>
</tr>
</table>
The following JS code will fill create a row for each JSON element
// 1. remove all existing rows
$("tr:has(td)").remove();
// 2. get each article
$.each(articles, function (index, article) {
// 2.2 Create table column for categories
var td_categories = $("<td/>");
// 2.3 get each category of this article
$.each(article.categories, function (i, category) {
var span = $("<span/>");
span.text(category);
td_categories.append(span);
});
// 2.4 Create table column for tags
var td_tags = $("<td/>");
// 2.5 get each tag of this article
$.each(article.tags, function (i, tag) {
var span = $("<span/>");
span.text(tag);
td_tags.append(span);
});
// 2.6 Create a new row and append 3 columns (title+url, categories, tags)
$("#added-articles").append($('<tr/>')
.append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
.append(td_categories)
.append(td_tags)
);
});
Try it like this:
$.each(response, function(i, item) {
$('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table');
});
Demo: http://jsfiddle.net/R5bQG/
$.ajax({
type: 'GET',
url: urlString ,
dataType: 'json',
success: function (response) {
var trHTML = '';
for(var f=0;f<response.length;f++) {
trHTML += '<tr><td><strong>' + response[f]['app_action_name']+'</strong></td><td><span class="label label-success">'+response[f]['action_type'] +'</span></td><td>'+response[f]['points']+'</td></tr>';
}
$('#result').html(trHTML);
$( ".spin-grid" ).removeClass( "fa-spin" );
}
});
You shouldn't create jquery objects for each cell and row. Try this:
function responseHandler(response)
{
var c = [];
$.each(response, function(i, item) {
c.push("<tr><td>" + item.rank + "</td>");
c.push("<td>" + item.content + "</td>");
c.push("<td>" + item.UID + "</td></tr>");
});
$('#records_table').html(c.join(""));
}
Data as JSON:
data = [
{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}
]
You can use jQuery to iterate over JSON and create tables dynamically:
num_rows = data.length;
num_cols = size_of_array(data[0]);
table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");
header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);
$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})
Here is the size_of_array function:
function size_of_array(obj) {
size = Object.keys(obj).length;
return(size)
};
You can also add styling if needed:
$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');
Result:
This is working sample that I copied from my project.
function fetchAllReceipts(documentShareId) {
console.log('http call: ' + uri + "/" + documentShareId)
$.ajax({
url: uri + "/" + documentShareId,
type: "GET",
contentType: "application/json;",
cache: false,
success: function (receipts) {
//console.log(receipts);
$(receipts).each(function (index, item) {
console.log(item);
//console.log(receipts[index]);
$('#receipts tbody').append(
'<tr><td>' + item.Firstname + ' ' + item.Lastname +
'</td><td>' + item.TransactionId +
'</td><td>' + item.Amount +
'</td><td>' + item.Status +
'</td></tr>'
)
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
}
// Sample json data coming from server
var data = [
0: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test1", Lastname: "Test1", }
1: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test 2", Lastname: "Test2", }
];
<button type="button" class="btn btn-primary" onclick='fetchAllReceipts("#share.Id")'>
RECEIPTS
</button>
<div id="receipts" style="display:contents">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Transaction</th>
<th>Amount</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I have created this JQuery function
/**
* Draw a table from json array
* #param {array} json_data_array Data array as JSON multi dimension array
* #param {array} head_array Table Headings as an array (Array items must me correspond to JSON array)
* #param {array} item_array JSON array's sub element list as an array
* #param {string} destinaion_element '#id' or '.class': html output will be rendered to this element
* #returns {string} HTML output will be rendered to 'destinaion_element'
*/
function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) {
var table = '<table>';
//TH Loop
table += '<tr>';
$.each(head_array, function (head_array_key, head_array_value) {
table += '<th>' + head_array_value + '</th>';
});
table += '</tr>';
//TR loop
$.each(json_data_array, function (key, value) {
table += '<tr>';
//TD loop
$.each(item_array, function (item_key, item_value) {
table += '<td>' + value[item_value] + '</td>';
});
table += '</tr>';
});
table += '</table>';
$(destinaion_element).append(table);
}
;
You could do it something like this:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function(){
$.ajax({
url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
data: '<any parameters you want to send as the Request body or query string>',
dataType: json,
async: true,
method: "GET"
success: function(data){
//If the REST API returned a successful response it'll be stored in data,
//just parse that field using jQuery and you're all set
var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td>' + value + '</td>';
});
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('#tblSomething').html(tblSomething);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
});
</script>
<table id = "tblSomething" class = "table table-hover"></table>
jQuery.html takes string or callback as input, not sure how your example is working... Try something like $('<tr>').append($('<td>' + item.rank + '</td>').append ...
And you have some definite problems with tags fromation. It should be $('<tr/>') and $('<td/>')
I do following to get JSON response from Ajax and parse without using parseJson:
$.ajax({
dataType: 'json', <----
type: 'GET',
url: 'get/allworldbankaccounts.json',
data: $("body form:first").serialize(),
If you are using dataType as Text then you need $.parseJSON(response)
Initially my table has no data and I get "No data available in table" which is the expected functionality.
I'd like to have no text or row created as I will be populating the table via Ajax depending on user action.
Is there a setting to stop the display of this row in the table? I can't seem to find one. This code works but the first row reads "No data available in table". This is the jQuery code:
$.ajax({
type: 'GET',
url: '/Home/postInformationofConferenceTitle',
dataType: "JSON",
success: function (data) {
$.post("/Home/selectRooms", { xtitle: data.xglobalTitle }, function (data) {
var ndx = 0;
$.each(data.xroom_name, function (key, value) {
var Xroom_name = data.xroom_name[ndx];
var Xroom_plan = data.xroom_plan[ndx];
var column =
('<tr>' +
'<td>' +
'<div class="img-container">' +
'<img src="../../assets/img/room-plan/' + Xroom_plan + '" alt="..." id="imgsrc">' +
'</div>' +
'</td>' +
'<td id="imgname">' + Xroom_name + '</td>' +
'<td class="text-right">' +
'<i class="fa fa-edit"></i>' +
'</i>' +
'</td>' +
'</tr>');
document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;
ndx++;
});
});
}
})
I guess you might be looking at the language settings of datatables.
language : {
"zeroRecords": " "
},
(Note the space between " ". (Its a hack but found it to be useful for now.)
$(document).ready(function () {
var serverData = [
]
var table = $('#example').DataTable({
language : {
"zeroRecords": " "
},
data: serverData,
columns: [
{ data: "name" },
{ data: "age" },
{ data: "isActive" },
{ data: "friends" },
],
'columnDefs': [{
'targets': 2,
'render': function (data, type, full, meta) {
let checked = ''
if (data) {
return '<input type="checkbox" checked / >';
}
else {
return '<input type="checkbox" / >';
}
return data;
}
},
{
'targets': 3,
"render": function (data, type, full, meta) {
var selectInitial = "<select>";
var selectClosing = "</select>";
var options = '';
$.each(data, function (key, value) {
options = options+"<option value="+value.id+">"+value.name+"</option>";
});
return selectInitial+options+selectClosing;
}
}
],
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js'></script><link rel='stylesheet prefetch' href='https://cdn.datatables.net/1.10.9/css/jquery.dataTables.css'>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>isActive</th>
<th>friends</th>
</tr>
</thead>
</table>
It works for me.
var someTableDT = $("#some-table").on("draw.dt", function () {
$(this).find(".dataTables_empty").parents('tbody').empty();
}).DataTable(/*init object*/);
Below worked for me:
$(document).ready(function () {
$("#TABLE_ID").DataTable();
$(".dataTables_empty").empty();
});
Next CSS worked for me to totally hide that block (not only delete text):
.dataTables_empty
{
display:none;
}