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) { **/
}
});
Related
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.
I have DataTables table with row details which are opening by clicking on row. The row details are displayed in 3 different languages which are selected by checkbox. When the row is clicked, the language is send to details.php script (langy:chLanguage) which returns json values for this selected language.
Initialy the language is set to chDe and everything is working fine until I click on another language. When the language is changed to EN or RU, or even back to DE, the returned json is empty.
index.php :
<h5>Language</h5>
<input type="checkbox" id="chDe" name="languages" checked>DE
<input type="checkbox" id="chEn" name="languages">EN
<input type="checkbox" id="chRu" name="languages">RU
<script>
var chLanguage = "chDe";
$('input[name=languages]').click(function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
chLanguage = [];
$('input[name=languages]:checked').each(function() {
chLanguage.push($(this).attr('id'));
});
if (chLanguage == '') {
chLanguage = 5;
}
$('#example').DataTable().ajax.reload();
});
function format ( rowData, row, $chLanguage ) {
// FOLLOWING CONSOLE.LOG RETURNS THE ACTUALLY SELECTED LANGUAGE CORRECTLY
console.log("chLanguage in format function: " + chLanguage);
var div = $('<div/>')
.addClass( 'loading slider' )
$.ajax( {
url: 'scripts/details.php',
data: {
name: rowData[0],
langy: chLanguage,
},
dataType: 'json',
type: 'post',
success: function ( json ) {
// FOLLOWING CONSOLE.LOG RETURNS [Object object] unless the language is changed, then it returns nothing
console.log("json: " + json);
var childTable = '<div id="rowdetails" class="slidera"><ul class="slider">';
childTable = childTable.concat(
'<div class="row rdstyle">' +
'<table class="detailstable detailserrors">' +
'<tr><td><b>Error class:</b></td><td>' + json[0].ERRTRIEDA + '</td></tr>' +
'<tr><td><b>Error group:</b></td><td>' + json[0].ERRSKUPINA + '</td></tr>' +
'<tr><td><b>Error:</b></td><td>' + json[0].ERRPOPIS + '</td></tr>' +
'</table>' +
'</div>
);
});
}
details.php :
$language = $_POST['langy'];
if ($language == 'chDe' ) {
$setLang = 'DE';
}else if($language == 'chEn') {
$setLang = 'EN';
} else{$setLang = 'RU';}
and $setLang is used in SQL query to filter data by language.
I hope I'm not far away from working solution, because it's working already, just the language switch don't work. Sorry not to attach working sample. I don't know how to implement all these parts including mysql db and several differenct php scripts :(
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>');
}
I've set up an Ajax request to the Ebay API using Jquery, which works while I have a search term/keyword hardcoded, but I cannot figure out how to write the code to make my (bootstrap) button trigger the Ajax request using the search form input. I've tried various things to no avail. I'm completely new to this and this is my first time making an Ajax request and using JQuery so hopefully this makes sense.
Jquery:
$(document).ready(function() {
url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=rare soul 45"; //This would get deleted?
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I'm a bit surprised you managed to get an ajax request running but you struggle with registering a click event handler. :) but here we go...
$('form[role="search"]').submit(function(ev) {
ev.preventDefault();
// get the input value with:
var searchstring = $('input[type="text"]', this).val();
// your ajax request, using the variable above
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=deleted for privacy";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=10";
url += "&keywords=" + searchstring;
url += "&sortOrder=StartTimeNewest";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
It looks like you are making that ajax call upon document ready which is not really what you want. You want to make that call upon a button press event. So I would do this.
Put that ajax call into a function that you can call
Give the button an id
On document ready, use jquery to attach an event handler to the element with the id in step 2 above that triggers a call to your function mentioned in step 1 above.
Then, don't forget to extract the value in the field from the event and place it into the called ajax function as a parameter.
Given your current HTML, you can call a click event on your submit button like this...
$('button[type="submit"]).on('click', function(event) {
/*
since the button is of type "submit",
prevent the default behavior. Which,
in this case, is to submit the form.
*/
event.preventDefault();
//Check your browser's console to see what this is
console.dir(event);
//insert AJAX code here
});
This code uses the jQuery .on() method to capture the given event, 'click', on a given element $('button[type="submit"]'). Once this event has been captured, you can access it as event, or name of your choice, within the function.
This event object contains information regarding the event itself. It can be quite daunting at first, but I encourage you to look through a console.dir(event); call. More specifically, e.currentTarget/e.target, and view to get a sense of what is going on. From there you can look into what the difference is between some things that seem the same and get as familiar with it as you'd like.
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