Update HTML Table when API is getting updated - javascript

I am just making a simple UI for display orders from Woocommerce shop. I am successfully getting the JSON response and put it into a HTML table. But I need to update the table without refreshing the whole page or table. Actually i need like, whenever Woocommerce get an order, the HTML table should get updated while highlighting the row. I am using AJAX to update the table but its not updating.
Note - I tried to set particular time interval for refreshing the page but i thought it won't be a good solution.
So far i got this below.
**
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "https://localhost/site/wp-json/wc/v3/orders?consumer_key=key&consumer_secret=key1",
dataType: 'json',
type: 'get',
cache:false,
success: function(data){
console.log(data);
var event_data = '';
$.each(data, function(index, value){
/*console.log(value);*/
event_data += '<tr>';
event_data += '<td>'+value.id+'</td>';
event_data += '<td>'+value.billing.first_name + value.billing.last_name+'</td>';
event_data += '<td>'+value.date_created+'</td>';
event_data += '<td>'+value.billing.phone+'</td>';
event_data += '<td>'+value.billing.address_1 + ", " + value.billing.address_2 + ", " + value.billing.city + value.billing.postcode +'</td>';
event_data += '<td>'+value.total+'</td>';
event_data += '</tr>';
});
$("#data").append(event_data);
},
error: function(d){
/*console.log("error");*/
alert("404. Please wait until the File is Loaded.");
}
});
});
</script>
**
Any suggestions please.

Related

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

Unable to access AJAX Response Data through jQuery

I have searched and tried for hours but unsuccessful.
I have an existing page which displays simple data from DB using PHP in an HTML table. Now I want to implement AJAX functionality so that data is refreshed without page refresh.
I have implemented this solution, to my understanding, the AJAX call part is working and the values are getting refreshed as expected. but I am stuck in getting the values.
index.php (main page)
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
</head>
<body>
<h3>Output: </h3>
<table border="1" id="output"></table>
<script id="source" language="javascript" type="text/javascript">
$(function() {
update_content();
});
function update_content()
{
$.ajax({
url: 'query.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to query.php
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
if(data){
(data + '').length;
}
var temp = new Array();
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
}
});
setTimeout(function(){
update_content();
}, 1000);
}
</script>
</body>
</html>
query.php (used for AJAX call)
<?php
include('inc/connection.php');
# Main query
$sql = "
select LastUpdated, symbol, sum
from TheTable
";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
}
echo json_encode($table_data);
?>
If I run query.php directly in the browser, I see all the data in this format:[{"LastUpdated":"20170614","symbol":"AUD","sum":"20"},{"LastUpdated":"20170614","symbol":"AUD","sum":"10"}]
But on my main page, I see undefined inside the table.
I'd ideally like to have all the values (using a JS loop in the above code may be) to display all the records fetched from DB (variable no. of records).
HINT/MODIFICATION
When I change:
$('#output').html("<tr><td>"+data["symbol"]+"</td></tr>");
to
$('#output').html("<tr><td>"+data[0]+"</td></tr>");
in index.php
AND
$table_data[]=array("LastUpdated"=>$row[0],"symbol"=>$row[1],"sum"=>$row[2]);
to
$table_data[]=$row;
in query.php, then I get only first row as a string like
20170614,AUD,40.
END HINT/MODIFICATION
I am sorry if that's a silly question/problem. I am new to jQuery and trying AJAX for first time.
P.S. I know mysql_* functions are deprecated and I am aware of the vulnerability.
Your help would be highly appreciated.
When you update your data table you'll probably want to just rebuild the table. In your callback function, you need to loop through the array and add new rows to the table.
$.ajax({
url: 'query.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) {
if (!Array.isArray(data) || !data.length) {
return;
}
$("#output").empty(); //clear old table data
for(var i = 0, len = data.length; i < len; i++) {
$("#output").append(
"<tr><td>" + data[i].LastUpdated + "</td>" +
"<td>" + data[i].symbol + "</td></tr>" +
"<td>" + data[i].sum + "</td></tr>"
);
}
}
});
You have to change code as mentioned below.
From
data["symbol"]
to
data.symbol
Let me know if it not works.

how to create search function with jquery

I have this ajax request that's working on pulling the data I need but I would like to make this a search function that lets the user pull in data as requested. Is there away to take my working code and repurpose it to work with the search box? Not sure how to go about this...
function foodQuery(){
var foodURL = "http://api.example.com/items?key=123456789";
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) {
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >#' + product.itemCode + '</h4>';
// get description
htmlString += '<p class="product_desc">' + product.description + '</p>';
// open price
htmlString += '<div class="price">';
// get price & close div
htmlString += '<span class="dollar"><span class="usd">$</span>' + product.price + '</span> <span class="product_desc">per weight</span></div>'
// close divs
htmlString += '</div>';
//console.log(htmlString);
$('.listing').append( $(htmlString) );
}); //end each
}, // end success
error: function(e) {
console.log(e.message);
$('.listing').append( '<h1 class="errmsg" >Sorry, there was an unkown error.</h1>' );
} // end error
}); // end ajax request
}
It depends on the API that you are using, but assuming the API has a way to search using text, you could have something that looks like the following:
function foodQuery(searchTerm) {
var foodUrl = '/path/to/api?query=' + searchTerm;
$.ajax({
// fill in AJAX call here and callback handling like you are doing
})
}
$('#searchBox').on('keypress', function() {
foodQuery($(this).val());
});
So every time the user types, the function foodQuery() will be run with the current search term. You may want to add some delay so that the API is not hit every time the user types a new character.
First create a text input,
<input type="text" id="search">
Then listen for the keyup event of that input. Get the value of the input as the user is typing (if this is the behavior you want) and call the foodQuery function sending the value of the input as a parameter. Then use this value as the key parameter of the foodURL. Then perform the ajax request the same way you did.
$(function() {
/**
Whenever user types a letter and release the key, its value is passed to the
foodQuery function
**/
$("#search").keyup(function() {
var value = $(this).val();
foodQuery(value);
});
function foodQuery(key) { // key is passed as a parameter
var foodURL = "http://api.example.com/items?key=" + key;
/** Send you ajax request here and manipulate the DOM the same way yo do. Since we are
fetching new products continuously, it is better to clear the .listing element
every-time before you update it. **/
$(".listing").html("");
/**
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) { **/
}
});

jQuery populate select issues with onclick

I've manage to create a sample in jsfiddle http://jsfiddle.net/9vkk5/ to illustrate my problem
As you might see it's only an example because I fill the select with information by database, this way:
$.ajax({
type: "POST",
url: "load.php?type=clients",
dataType: 'json',
success: function(data){
$("#clients").empty();
var options = '';
for(var i = 0; i <= data.length - 1; i++){
options += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#clients").append(options);
$("#clients").trigger('chosen:updated');
}
});
But the problem I have is totally the same as the jsfiddle example. I would like to, whenever I click the select to fill with data from database but keep the actual option selected.
Edit: Solved.
$("#clients").append(options);
$("#clients").val(selected_option); // trick is here
$("#clients").trigger('chosen:updated');
$("#clients").trigger('chosen:refresh');

All Dynamic Posts defaults to first Object

I am currently working on an app to retrieve feeds from a wordpress site and list individual posts in a jquery mobile list format. Below is the JS code:
$(document).ready(function () {
var url = 'http://howtodeployit.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json_xml&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 6; i++) {
var entry = postlist[i];
console.log(entry);
html += '<li>';
html += '<a href="#articlepost" onclick="showPost(' + entry.id + ')">';
html += '<div class="etitle">' + entry.title + '</div>';
html += '<div class="esnippet">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#devotionlist").append(html);
$("#devotionlist ul[data-role=listview]").listview();
}
});
});
function showPost(id) {
$('#articlecontent').html("Loading post...");
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function (data) {
var html = '';
html += '<h3>' + data.post.title + '</h3>';
html += data.post.content;
$('#articlecontent').html(html);
});
}
When I click on any of the 6 posts displayed, only the contents of the first Post gets displayed instead of the contents of the individual posts.
How did I workaround this?
Step1: From my WordPress Permalink Settings, I selected Custom Structure and added /%postname%/%post_id% This means my RSS XML output results for my 'Link' element will be in this format:
<myurl>/<postname>/<postID> (http://howtodeployit.com/xxx/111/)
Step2: To make it easier for me instead of writing a regex query I used a Split command like this:
var postlink = entry.link;
var id = postlink.split(/\//)[4];
(///)[4] would simply split the URL by the number of slashes and take only that 4th bit which is where my postID is.
I hope this comes in handy for others in my position

Categories