Google spreadsheet Search using javascript - javascript

I'm trying to build a search option where user will input their ID and they will see the result of that corresponding ID which is stored in google spreadsheet.
Like user will input:
1 and they will see result : Nitu
5 and they will see result : Dipon
<input id="id" type="text" placeholder="Your ID">
<input id="search" type="submit" value="Search">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function displayContent(json) {
var string = "<table>";
var len = json.feed.entry.length;
for (var i=0; i<len; i++) {
var id = json.feed.entry[i].gsx$id.$t;
var name = json.feed.entry[i].gsx$name.$t;
string += '<tr><td>' + id + '</td><td>' + name + '</td></tr>';
}
string += "</table>";
$(string).appendTo('body');
}
</script>
<script src="http://spreadsheets.google.com/feeds/list/1WMvFqepPmQUVwTFFUZW_3SfSt1ZBr_AEy_XdUXZ72ng/od6/public/values?alt=json-in-script&callback=displayContent" type="text/javascript"></script>
I can fetch data from my google sheet using the above code snippet. But I don't want to fetch all data at a time. I want only specific data based on search with ID.
So now how can I integrate this search feature in javascript?

You can use Structured Query for google spreadsheet API.
So if make a GET request with proper Structured Query and you will get the relevant data only. in your case add sq=id==5 as query parameter.
So rather then get the whole data onload and parse it afterwads, you should make a function which will make proper GET request and fetch you Only the data you need.
var fetchName = function(ID, workSheetID){
var url = 'https://spreadsheets.google.com/feeds/list/'+workSheetID+'/od6/public/values?sq=id='+ID+'&alt=json-in-script&callback=?';
$.get( url, function( data ) {
//Parse and Do Your Stuff Here
});
}
Plunker Sample
Hope this helps. Cheers !!

instead of doing a for loop just use filter to filter the corresponding ID. For exmaple:
function displayContent(json) {
var output = json.feed.entry.filter(function(name){
return name.gsx$id.$t === '2'
})
$('body').append(" <p>" + output[0].gsx$name.$t + "</p>");
Heres the edited version, just replace '2' with your id or with the input value getter and it should work. Notice you need to reference the output in array like syntax. fiddle

Cross reference your code with the answer provided carefully!
1) your filter: --> return element.gsx$id.$t === 2
The comparison may not return the expected result
--> return name.gsx$id.$t === '2'
2) The returned data if your comparison produces any result would be in the variable 'name'. var name is in an array. You are to use indexes to access the array elements. Therefore, taking that into account, you should change yout code to:
var test = name[0].gsx$id.$t;
Here you are correctly accessing the data returned.
3) Always make sure there is data to access. Your array must not be empty if you try to access it.

Related

adding js variable into url to add the products

EDIT
I found the solution but this time I can not remove the comma from the end of the url. Below is my entire code. I just need to remove the from end of the url. i tried if statement but i failed.
var param = "";
//for loop for retrieving the selected values from array of object
for (let i = 0; i < that.productsSelected.length; i++) {
//console.log(that.productsSelected[i].id); + "<br>";
//console.log(that.productsSelected[i].quantity); + "<br>";
param += that.productsSelected[i].id +"&quantity="+ that.productsSelected[i].quantity;
if(!(i == that.productsSelected.length)){
param += ",";
}
}
console.log(param);
EDIT END
I am trying to add js variable in the url to add the products which user chose from a page.
that.productsSelected is array of javascript objects which I am getting from the page. Then to see the values I am using for loop, for now I am using console.log just for checking, see below.
//for loop for retrieving the selected values from array of object
for (let i = 0; i < that.productsSelected.length; i++) {
console.log(that.productsSelected[i].id); + "<br>";
console.log(that.productsSelected[i].quantity); + "<br>";
}
and I am getting values which is absolutely correct,
id 7464
quantity 1
Now my requirement is the value of id and quantity I want to add in the url for my online store.
window.location.href = "/cart/?add-to-cart=idvalue:"+quantity+",idvalue:"+quantity+",idvalue:"+quantity+",idvalue:"+quantity+",idvalue:"+quantity+"";
please note the product can be 2 or 8 or whatever it depends on user.
Can someone please help me? I am trying to get this solution for 1 week but miserably failed everytime
Use map() and join()
let cart_params = that.productsSelected.map(({id, quantity}) => `${id}:${quantity}').join(',');
window.location.href="/cart/?add-to-cart=" + cart_params;

How to capture the value of data attribute?

The javascript snippet that we have is :
Link
I would like to retrieve the value of data-test-socialmedia type. Based on that I would like to add the conditional statement to check if the data-test-socialmedia type is facebook. As we have many data attributes like this in the site.
I tried several ways and I get object as the value. But i need the actual value in this case it is facebook. Kindly help.
//first get element
var el = document.getElementsByClassName('n-contact')[0];
//get data and replace single quotes with double quotes to create valid JSON
var d = el.dataset.testSocialmedia.replace(/'/g, '"')
//parse JSON to javascript object
var parsed = JSON.parse(d, null)
//get country if type is facebook
if(parsed.options == 'facebook')
console.log(parsed.options.country)
Link
var str = document.querySelector('.n-contact').getAttribute('data-test-socialmedia').replace(/'/g,'"');
var obj = JSON.parse(str);
var result = obj.type;
console.log(result);
it would work.
With jQuery
var elementData = $(".n-contact").attr("data-test-socialmedia").replace(/'/g,'"'),
parsed = JSON.parse(elementData);
console.log(parsed);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Link

How to get the data inside the XML

I have this response data from the server that I authenticate.
<session session-guid="D39C1215-2F31-8641-E5T2-C7G35RT69127" user-id="34"> </session>
How can I get the value of session-guid and user-id and store them into 1 variable for each.
Thank you.
In plain Javascript in a modern browser you can use document.querySelectorAll().
For example, assuming you only have one session tag:
var session = document.querySelectorAll("session")[0];
var session_guid = session.getAttribute("session-guid");
var user_id = session.getAttribute("user-id");
console.log("session-guid: " + session_guid);
console.log("user-id: " + user_id);
If you have more that one session tag you can use forEach on the results of querySelectorAll() to locate the one you want. If you know that you're only going to have one session element you can use document.querySelector() instead of document.querySelectorAll()[0].
Here is one way to get the values client side. For this method you will need to add any custom class to your element like below:
Now write below lines of code inside tag:
var $mySession = jQuery(document.getElementsByClassName("mySession"));
for (i = 0; i < $mySession.length; i++) {
var sessionguid = jQuery($mySession[i]).attr('session-guid');
var userid = jQuery($mySession[i]).attr('user-id');
console.log(sessionguid);
console.log(userid);
}
You can check the values of "sessionguid" and "userid" variable in your browser console.
Here is what you can do to get the required data from the XML.
function getXMLData(xml) {
var txt, xmlDoc;
//get the responseXML
xmlDoc = xml.responseXML;
txt = "";
//get all the session nodes
var sessions = xmlDoc.getElementsByTagName("session");//this returns a array of nodes
for(var i =0;i<sessions.length;i++){
//iterate over nodes and get the attributes
txt += sessions[i].getAttribute("session-guid")+"<br />";
}
document.getElementById("demo").innerHTML = txt;
}
this function accepts the response as a parameter. And then extracts out the sessions nodes and the required attribute. You can modify it according to your requirements.
Here is a PLNKR demo for the same

Get array from jquery autocomplete

I am using JQuery to autocomplete names from a remote database... this all works fine.
However, I want to also get ALL the information associated with that name from the autocomplete and save it to a php array...
Can anyone help?
This is my code for the autocomplete
<script type="text/javascript">
$(function() {
$("#findname").autocomplete({
source: "templates/search2.php?field=sire",
minLength: 5
});
});
</script>
And here is how I call it...
<input type="text" name="name" id = "findname" size="45"><br>
So, when I find the name I am looking for, which works fine, how can I return ALL the data for that named record and store to an array, to then call a modal with the data ?
Thanks
if i understand your question, you want to get the data of a worker to show in a modal, well, first you need to get all the data you want in a single call, not just the names, but also the mail, age or other atributes, then you save it in an object .
For example:
After you called the information, you should get something like this :
var workersData=[{name:"a1",mail:"m1",age:20},
{name:"a2",mail:"m2",age:20},
{name:"a3",mail:"m3",age:20},
{name:"a4",mail:"m4",age:20}];
Then you create a method to get all the names and put this array in the autocomplete input:
function listStringsFromArray(list, atribute) {
var arrayString = [];
if (list) {
for (var index = 0; index < list.length; index++) {
arrayString.push(list[index][atribute]);
}
}
return arrayString;
}
$("#findname").autocomplete({
source: listStringsFromArray(workersData,"name"),
minLength: 5
});
Finally add a method for the input, so anytime it changes, to search for the rest of the data in the workers array and put the information where you want:
$("#findname").keypress(function(e){
fillDataModalWorker(); });
function fillDataModalWorker(){
var workerName=$("#findname").val();
var mail,age;
for (var index = 0; index < workersData.length; index++) {
if(workersData[index]["name"]==workerName){
mail=workersData[index]["mail"];
age=workersData[index]["age"];
$("#inputMailModal").val(mail);
$("#inputAgeModal").val(age);
break;
}else{
$("#inputMailModal").val("Worker´s information not found");
$("#inputMailModal").val("Worker´s information not found");
}
}
}
Hope it hepls.

Is it possible to use a string to reference a json object within an Ajax statement?

So i have a javascript function. It performs one ajax call, to retrieve a json object full of data. Within the success function of that ajax call i perfrom ANOTHER ajax call to retrieve the names of the columns of data for that particular set. (yes i'm sure there's a better way but thats not my issue). At this point in time i have two variables: items(json array) and interfaceCols(just an array of strings). Then i try to create an html string to create a table with said data.
Here is my code which will make everything more clear:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
interfaceCols = data.split(" ");
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
console.log(items[i].interfaceCols[4]);
for(j = 0; j < interfaceCols.length; j++){
myString = myString + '<td id = "visibleDef">' + items[i].interfaceCols[j] +'</td>';
}
myString = myString + '</tr>';
interfaces.push(myString);
}
});
}
});
My javascript file throws an error on the "myString = myString + '<td id ='... line.
I am almost positive that it is because i'm just placing a string at the end of "items[i]" with ".interfaceCols[j]"
Can anybody suggest a way to do this? The whole point is so that i dont have to manually type out every column name, because i have alot of tables and each table has many columns.
Given a JS object s:
s = {a: 1, b: 2}
You have (at least) two options to access an attribute:
s.a // returns 1
Which seems to be what you are trying to do right now. To access it with a dynamic name, you can use:
s['a'] // returns 1
In your case, it should be:
items[i][interfaceCols[4]]

Categories