i have an auto-suggest url from that i need to write a JavaScript code through which i will be able to see the auto-suggest data.
i tried the below code but i am not able to get through it.
<!DOCTYPE html>
<head>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://***.poc.xxxxx.com/v1/staples/suggest?authKey=baef7f8e39c512342c8a14b7f6018b58&q=wat&rows=8";
var words = []
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var data = JSON.parse(response);
var req_data = data.suggestions[0].suggestion;
console.log(req_data);
//document.getElementById("id01").innerHTML = words;
}
</script>
</head>
<body>
<!-- <div id="id01"></div> -->
</body>
</html>
the thing i am getting in response is:-
{"suggestions":[{"suggestion":"\u200B\u200B\u200B<b>wat</b>er","categories":[{"name":"Water & Juice","filter":"category_id%3A4606"},{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er cooler","categories":[{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"},{"name":"Kitchen Storage & Organization","filter":"category_id%3A1303"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er bottle","categories":[{"name":"Lunch Totes & Water Bottles","filter":"category_id%3A8812"},{"name":"Water & Juice","filter":"category_id%3A4606"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er cups","categories":[{"name":"Disposable Plates & Cups","filter":"category_id%3A992"},{"name":"Disposable Cups","filter":"category_id%3A13302"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er bottle labels","categories":[{"name":"Labels","filter":"category_id%3A997"},{"name":"Mailing & Shipping Labels","filter":"category_id%3A6118"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>er dispenser","categories":[{"name":"Water Dispensers & Filters","filter":"category_id%3A16896"},{"name":"All Kitchen","filter":"category_id%3A60479"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>ch","categories":[{"name":"Pedometers & Fitness Trackers","filter":"category_id%3A2554"},{"name":"Smart Watches","filter":"category_id%3A62030"}]},{"suggestion":"\u200B\u200B\u200B<b>wat</b>ercolor","categories":[{"name":"Abstract Art","filter":"category_id%3A12645"},{"name":"Wall Art/Decor","filter":"category_id%3A26678"}]}]}
from that response i need to find all the product name which coming after suggestion not suggstions like suggestion for wat water cooler etc.
It is hard to discern what exactly you're asking for. If what you want is just a list of all the "name" properties that are returned as suggestions, you could collect those like this:
function myFunction(response) {
var data = JSON.parse(response);
var items = data.suggestions;
var names = [], cat;
// iterate array of suggestions
for (var i = 0; i < items.length; i++) {
cat = items[i].categories;
// iterate array of categories in each suggestion
for (var j = 0; j < cat.length; j++) {
names.push(cat[j].name);
}
}
console.log(names.join(","));
}
Working demo: http://jsfiddle.net/jfriend00/trdppth0/
Now that you've clarified what output you want, you can get the list of suggestion words like this:
function myFunction(response) {
var data = JSON.parse(response);
var items = data.suggestions;
var suggestions = items.map(function(item) {
return item.suggestion;
});
console.log(suggestions.join(","));
}
Working demo: http://jsfiddle.net/jfriend00/bv3yfkwr/
Related
I'm new to code development and I'm trying to build a project to help me retain the skills I have learned. In doing so, I've hit a snag.
I am trying to pull a couple of attributes from nodes in an XML file but having trouble getting to what I need. I need to be able to pull the "number" from the node parent and the team "code" for each team listed in the node. The number of teams fluctuate between 2 and 6. Here's a sample of the XML.
My code is below. When it runs, it will get the bye week data but it won't load the teams. Several posts that I've read have had a similar issue but with some other technology or data structure in place that didn't apply to what I'm working with here (as far as I could tell). Any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Bye Week</title>
<script>
var xmlhttp;
window.onload = function()
{
var url = "https://www.fantasyfootballnerd.com/service/byes/xml/test/";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = byeWeeks;
xmlhttp.send();
}
function byeWeeks()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var theXML = xmlhttp.responseXML.documentElement.getElementsByTagName('Week');
for(var i = 0; i < theXML.length; i++)
{
var week = theXML[i].getAttribute('number');
var team = theXML[i].getElementsByTagName('Team');
var out = "<b>" + team + "</b><br/>";
out += "Bye Week: " + week + "<br/>";
console.group('Output for ' + team);
console.log('Bye Week: ' + week);
console.log();
console.groupEnd();
document.getElementById('result').innerHTML += out
}
}
}
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>
As per the attached xml structure it seems the team node can be multiple inside a week node, so you would have to iterate over the team nodes in order to extract the code.
var week = theXML[i].getAttribute('number');
var teams = theXML[i].getElementsByTagName('Team');
teams.forEach(function(team) {
console.log(team.getAttribute('code'));
});
I'm not familiar with fantasy football but I'm assuming each week there is two teams that you want to retrieve. To access the child element attributes for week try:
var team1Name = theXML[i].childNodes[0].getAttribute("name");
var team2Name = theXML[i].childNodes[1].getAttribute("name");
team1Name should be holding "washington redskins"
team2Name should be holding "florida panthers"
if you want the team code just replace "name" with "code"
if you're not sure how many teams there are the following code should work
var teams = [];
for each (team in theXML[i].childNodes){
teams.push(team.getAttribute("name"));
}
//at this point teams will hold an array of team names playing that week
#Ashish Khandelwal
Here's the updated code with the array that I referenced earlier (I tried to post it as a comment on our conversation string but it was too long). The XML can be found here.
<!DOCTYPE html>
<html>
<head>
<title>Bye Week</title>
<script>
var xmlhttp;
window.onload = function()
{
var url = "https://www.fantasyfootballnerd.com/service/byes/xml/test/";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = byeWeeks;
xmlhttp.send();
}
function byeWeeks()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var theXML = xmlhttp.responseXML.documentElement.getElementsByTagName('Week');
for(var i = 0; i < theXML.length; i++)
{
var week = theXML[i].getAttribute('number');
var teams = theXML[i].getElementsByTagName('Team');
Array.from(teams).forEach(function(team) {
console.log(team.getAttribute('code'));
});
console.group('Output for ' + team);
console.log('Bye Week: ' + week);
console.log(theXML[i]);
console.log(teams.push(team.getAttribute("code")));
console.groupEnd();
document.getElementById('result').innerHTML += out
}
}
}
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>
Currently, when a div is clicked, jQuery detects it sends request to fetch data from mysql via Ajax.
What I'm actually fetching is, sub categories for the item clicked and display them in html page.
Now all is done in procedural way, so when another sub level needed to be displayed, I have to copy paste the ajax function. But how do make it into objects so that I don't have to repeat myself?
I just need to know how to bring in OOP into this context..Any help will be greatly appreciated. Thank you.
HTML
<!--append the default top level items starts-->
<div id="default"></div>
<!--append the default top level items ends-->
<hr>
<!--append the default top level items starts-->
<div id="sub"></div>
<!--append the default top level items ends-->
Jquery/AJax
<!--select top level items and append to default id starts-->
$("#clickme").on("click",function()
{
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var data = JSON.parse(this.responseText);
//console.log(this.responseText);
//console.log(JSON.parse(this.responseText));
for (i = 0; i < data.length; i++)
{
var id=data[i].id;
var name=data[i].item_name;
/*check if sub item exist*/
checkSubExist(id);
/*append to div*/
$("#default").append("name= "+name+", ");
}
}
}
}
xmlhttp.open("GET", "selectTopLevel.php");
xmlhttp.send();
});
<!--select top level items and append to default id ends-->
function checkSubExist(param)
{
//alert(param);
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var data = JSON.parse(this.responseText);
//console.log(this.responseText);
//console.log(JSON.parse(this.responseText));
for (i = 0; i < data.length; i++)
{
var id=data[i].id;
var name=data[i].item_name;
//alert(name);
$("#sub").append(name+", ");
}
}
}
}
xmlhttp.open("GET", "checkSubExist.php?sub="+param);
xmlhttp.send();
}
I would use $.ajax to wrap the xmlHttpRequest.
If you want a more "OOP" like approach, I would suggest you define some kind of Request Wrapper Objects which you then create upon event binding, naive example:
var RequestWrapperProto = {
getSubnodes: function(){
//handle request
}
//etc
}
var requestWrapper = Object.create(RequestWrapperProto)
$('.sub').on('click', requestWrapper.getSubNodes);
I am developing a Rails 4 web application. In my Rails application View i have 2 forms . First form contains List of Employees where i can select employees and add to Second Form by clicking on ADD button . Second form also contains a button where i can remove employees from Second Form, all the removed employees will be moved back to first form.
Currently i achieving it like , when i click the add button in First form i will pass the selected employee data to controller through an Ajax call and return the same selected data to second form to display selected employees.
Is it possible to manage this from client side without making any call to Server.
Is there any gems available in Rails to achieve this.
I am using Rails 4 and Ruby 2.
Example : Sample List Manipulation in Javascript
Any help is appreciated.
Yes it's possible to do this on the client-side
Javascript
All I would do is replace your ajax calls with the on-page JS
Have used JQuery in this example (hope that's okay):
http://jsfiddle.net/U443j/3/
$(".move").on("click", "input", function() {
var button = $(this).attr("id");
var from = document.getElementById("FromLB");
var to = document.getElementById("ToLB");
if (button == "left") {
move(to, from);
}else{
move(from, to);
}
});
function move(tbFrom, tbTo)
{
var arrFrom = new Array(); var arrTo = new Array();
var arrLU = new Array();
var i;
for (i = 0; i < tbTo.options.length; i++)
{
arrLU[tbTo.options[i].text] = tbTo.options[i].value;
arrTo[i] = tbTo.options[i].text;
}
var fLength = 0;
var tLength = arrTo.length;
for(i = 0; i < tbFrom.options.length; i++)
{
arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
if (tbFrom.options[i].selected && tbFrom.options[i].value != "")
{
arrTo[tLength] = tbFrom.options[i].text;
tLength++;
}
else
{
arrFrom[fLength] = tbFrom.options[i].text;
fLength++;
}
}
tbFrom.length = 0;
tbTo.length = 0;
var ii;
for(ii = 0; ii < arrFrom.length; ii++)
{
var no = new Option();
no.value = arrLU[arrFrom[ii]];
no.text = arrFrom[ii];
tbFrom[ii] = no;
}
for(ii = 0; ii < arrTo.length; ii++)
{
var no = new Option();
no.value = arrLU[arrTo[ii]];
no.text = arrTo[ii];
tbTo[ii] = no;
}
}
This will allow you to move the items between form elements. The reason this is important is because it allows you to send the data to the controller as one data-set:
Controller
On my JSFiddle, I have a save button
This can be tied to your Rails controller, allowing you to send your form data to your system
This will send your params hash like this:
params { "FromLB": ["value1", "value2"], "ToLB": ["value1", "value2"] }
The hash will be structured differently, but you'll get two sets of data, which you can then put into your db:
#app/controllers/your_controller.rb
def action
#from = params[:FromLB]
#to = params[:ToLB]
#Save the data-sets here
end
I recently created my own personal portal page to replace iGoogle since it's going to be shuttered later this year. Everything is working fine except that one of the RSS feeds that I'm pulling in outputs urls that look like this: http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305
Which when clicked go to a bad url page. How would I remove the first half of that url so that it only has the part starting from the second http://
Strange, but here the link works fine...
Just realized the issue is that somehow the ampersands are being turned into entities which is breaking the links...
Try this. A generic approach.
function queryString(parameter, url) {
var a = document.createElement("a");
a.href = url;
var loc = decodeURIComponent(a.search.substring(1, a.search.length));
var param_value = false;
var params = loc.split("&");
for (var i = 0; i < params.length; i++) {
param_name = params[i].substring(0, params[i].indexOf('='));
if (param_name == parameter) {
param_value = params[i].substring(params[i].indexOf('=') + 1)
}
}
if (param_value) {
return encodeURIComponent(param_value);
}
else {
return "";
//param not found
}
}
var secondHTTP = queryString("url", 'http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305');
var str = "http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNFEguC5pqagsWkkW_y_EjYj9n1bMg&url=http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305";
var url = decodeURIComponent(str.split(/https?:/ig).pop());
will result in
"//www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
or
var url = decodeURIComponent(str.match(/^http.+(http.+)/i)[1]);
will result in
"http://www.haaretz.com/news/diplomacy-defense/israel-to-un-replace-austrian-peacekeepers-withdrawn-from-golan-1.528305"
Edit: Code updated, jsFiddle added
HTML:
<input id="schnitzel" type="text" value="http://www.google.com/http://www.real-foo.bar/" />
<input type="button" onclick="$('#schnitzel').val(window.firstHTTP($('#schnitzel').val()));" value="ยป" />
JavaScript:
window.firstHTTP = function (furl = "") {
var chunked = furl.split("http://");
return (chunked && chunked[2]) ? ("http://" + chunked[2]) : furl;
};
JS-Fiddle:
http://jsfiddle.net/Rm5bU/
I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)