loading saving and showing json results in javascript - javascript

I have a php file called rows2.php that shows results like so after entering new fields in a database. It is simply showing the new id of the field :-
{'new_id':'92'}
I want to load this with javascript and add the new_id to existing list with : either side of the number and display it but I seem to be struggling? Many thanks.
The javascript to load the page and get the result is :
$.getJSON("rows2.php", function(result) {
var new_id=console.log(result[0].new_id);
document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + 'new_id' + ':';
})

You should use
document.getElementById('vehicle_list').innerHTML = ''+document.getElementById('vehicle_list').innerHTML+'new_id'+':';
instead of
document.getElementById('vehicle_list').value = ''+document.getElementById('vehicle_list').value+'new_id'+':';
.value is used only in case of input elements otherwise you must use .innerHTML

Don't put the variable name (new_id) in quotes.
document.getElementById('vehicle_list').value = '' + document.getElementById('vehicle_list').value + new_id + ':';

Related

Passing a List<Map> through location.href

My problem is, I want to pass a parameter which is a List to my location.href
function addNewDriver()
{
var pEntityType = <%=c.WIDOC_ENTITY_DRIVER%>;
var pListEntities = <%=lListDrivers%>;
location.href= "<%= c.url %>do/user/groupItemForm.step1.jsp?idClient=" + <%=pIdClient%> + "&listEntities:" + pListEntities +
"&idGroup=" + <%=pIdGroup%> + "&entityType=" + pEntityType + "&<%= lBackButtonUrl %>";
}
This is an example in Chrome console.
var pListEntities = [{dniPerson=4444444S, surname2Person=XXX, passportPerson=null, namePerson=XXX, idGroupItem=1, idPk=1111, surname1Person=XXXX};
This is how I think "they" wanted it.
var pListEntities = [{dniPerson:4444444S, surname2Person:XXX, passportPerson:null, namePerson:XXX, idGroupItem:1, idPk:1111, surname1Person:XXXX};
"lListDrivers" is already filled with values of each driver, like dni, name, surname etc.
The problem comes because, to pass this list, values inside can't have an equal, they need a ":", but I don't know any way to change it.
Convert your List<Map> to JSON. you can use Jackson ObjectMapper to convert it and it will change your pListEntities to a JSON object.
Here is one example.

Display thumbnailPhoto from Active Directory using Javascript only - Base64 encoding issue

Here's what I'm trying to do:
From an html page using only Javascript I'm trying to query the Active Directory and retrieve some user's attributes.
Which I succeded to do (thanks to some helpful code found around that I just cleaned up a bit).
I can for example display on my html page the "displayName" of the user I provided the "samAccountName" in my code, which is great.
But I also wanted to display the "thumbnailPhoto" and here I'm getting some issues...
I know that the AD provide the "thumbnailPhoto" as a byte array and that I should be able to display it in a tag as follow:
<img src="data:image/jpeg;base64," />
including base64 encoded byte array at the end of the src attribute.
But I cannot manage to encode it at all.
I tried to use the following library for base64 encoding:
https://github.com/beatgammit/base64-js
But was unsuccesful, it's acting like nothing is returned for that AD attribute, but the photo is really there I can see it over Outlook or Lync.
Also when I directly put that returned value in the console I can see some weird charaters so I guess there's something but not sure how it should be handled.
Tried a typeof to find out what the variable type is but it's returning "undefined".
I'm adding here the code I use:
var ADConnection = new ActiveXObject( "ADODB.connection" );
var ADCommand = new ActiveXObject( "ADODB.Command" );
ADConnection.Open( "Data Source=Active Directory Provider;Provider=ADsDSOObject" );
ADCommand.ActiveConnection = ADConnection;
var ou = "DC=XX,DC=XXXX,DC=XXX";
var where = "objectCategory = 'user' AND objectClass='user' AND samaccountname='XXXXXXXX'";
var orderby = "samaccountname ASC";
var fields = "displayName,thumbnailPhoto";
var queryType = fields.match( /,(memberof|member),/ig ) ? "LDAP" : "GC";
var path = queryType + "://" + ou;
ADCommand.CommandText = "select '" + fields + "' from '" + path + "' WHERE " + where + " ORDER BY " + orderby;
var recordSet = ADCommand.Execute;
fields = fields.split( "," );
var data = [];
while(!recordSet.EOF)
{
var rowResult = { "length" : fields.length };
var i = fields.length;
while(i--)
{
var fieldName = fields[i];
if(fieldName == "directReports" && recordSet.Fields(fieldName).value != null)
{
rowResult[fieldName] = true;
}
else
{
rowResult[fieldName] = recordSet.Fields(fieldName).value;
}
}
data.push(rowResult);
recordSet.MoveNext;
}
recordSet.Close();
console.log(rowResult["displayName"]);
console.log(rowResult["thumbnailPhoto"]);
(I replaced db information by Xs)
(There's only one entry returned that's why I'm using the rowResult in the console instead of data)
And here's what the console returns:
LOG: Lastname, Firstname
LOG: 񏳿က䙊䙉Āā怀怀
(same here Lastname & Firstname returned are the correct value expected)
This is all running on IE9 and unfortunetly have to make this compatible with IE9 :/
Summary:
I need to find a solution in Javascript only
I know it should be returning a byte array and I need to base64 encode it, but all my attempts failed and I'm a bit clueless on the reason why
I'm not sure if the picture is getting returned at all here, the thing in the console seems pretty small... or if I'm nothing doing the encoding correctly
If someone could help me out with this it would be awesome, I'm struggling with this for so long now :/
Thanks!

Cannot read property 'match' of undefined

I'm running the following:
var token = document.location.href.split('?s=')[1].match(/[a-z0-9]+/);
var longString = "?s=" + token + "?_sft_category=";
var tokenB = document.location.href.split(longString)[1].match(/[a-z0-9]+/);
var attribuB = "." + tokenB;
jQuery('a[data-filter-value="' + attribuB + '"]').parent().parent().parent().find(".dropdown-toggle").html(tokenB).append(' <span class="caret"></span>');
How come I get?
Uncaught TypeError: Cannot read property 'match' of undefined
If I remove .match(/[a-z0-9]+/) i don't get any error, but I do need match ..
The URL looks like:
http://www.example.com/xchanges/results/?s=sky&_sft_category=ogilvy
Probably using a library would be better here. I developed a tiny JavaScript library that work with the urls: url.js.
<script src="path/to/url.js"></script>
<script src="your-js.js"></script>
Then you can do:
var token = Url.queryString("s");
var tokenB = Url.queryString("_sft_category");
And that's it.
Note that instead of calling parent() multiple times, you can use the closest() method:
$('a[data-filter-value="' + attribuB + '"]')
.closest("<your_container>")
.find(".dropdown-toggle")
.html(tokenB)
.append(' <span class="caret"></span>')
;
Your location.href probably doesn't contain your longString. If you split the href using a string that's not present in href, you're left with an array with only 1 string, so you cannot get the [1] element.
It all depends on what your token variable is....
You've used a '?' character twice, which is incorrect.
I'd use
var tokenB = document.location.href.split('_sft_category=')[1].match(/[a-z0-9]+/);
to get the desired value, as _sft_category= will probably only occur once in location.href and you should then be able to split the href into an array of 2.
Saves you 2 lines of code ;) ...
You are using ? twice in longString, which in turn will make split() return an array with only one value. You need to change it to:
var longString = "?s=" + token + "&_sft_category=";
The ? character should only be used once, at the start of the querystring.

Google Apps Script - Dynamically Add Remove UiApp Form Elements

I am looking to create a Ui form section in my application that will Dynamically Add Remove UiApp Form Elements. I was trying to use the example from App Script Tutorials here
This example works great as far as performing the add remove elements, but when I use the submit button to capture the values, it submits as a JSON.stringify format. When I just want to capture the values only in a text or string format that will be added to a html email.
If there is way to convert JSON.stringify to text, string or get the values only in format, I will continue to use this example.
If not I was wonder if the following Javascript HTML code can be convert into GAS code and able to capture the values for each entry in a HTML email template to using in MailApp.
http://jsfiddle.net/g59K7/
Any suggestions, examples or adjustments to the codes would be greatly appreciated.
Thank you in advance
If you don't want the result to be in a JSON object, then you can adjust the _processSubmittedData(e) function. Right now he has it writing everything to an Object, which is fine. All you have to do is have a way to parse it:
function _processSubmittedData(e){
var result = {};
result.groupName = e.parameter.groupName;
var numMembers = parseInt(e.parameter.table_tag);
result.members = [];
//Member info array
for(var i=1; i<=numMembers; i++){
var member = {};
member.firstName = e.parameter['fName'+i];
member.lastName = e.parameter['lName'+i];
member.dateOfBirth = e.parameter['dob'+i];
member.note = e.parameter['note'+i];
result.members.push(member);
}
var htmlBody = 'Group Name: ' + result.groupName;
for(var a in result.members) {
var member = result.members[a];
var date = member.dateOfBirth;
var last = member.lastName;
var first = member.firstName;
var note = member.note;
htmlBody += first + ' ' + last + ' was born on ' + date + ' and has this note: ' + note;
}
MailApp.sendEmail('fakeEmail#fake.com',"Test Subject Line", "", {htmlBody: htmlBody});
}

jQuery - parsing JSON data - Having trouble with variable name

My first delve into working with JSON data. I have a bit of experience using jQuery though.
I'm posting to this URL (tumblr api): jyoseph.com/api/read/json
What I'm trying to do is output the json that gets returned. What I have so far:
$(document).ready(function(){
$.getJSON("http://jyoseph.com/api/read/json?callback=?",
function(data) {
//console.log(data);
console.log(data.posts);
$.each(data.posts, function(i,posts){
var id = this.id;
var type = this.type;
var date = this.date;
var url = this.url;
var photo500 = this.photo-url-500;
$('ul').append('<li> ' +id+ ' - ' +type+ ' - ' +date+ ' - ' +url+ ' - ' +photo500+ ' - ' + ' </li>');
});
});
});
See my jsbin post for the entire script: http://jsbin.com/utaju/edit
Some of the keys from tumblr have "-" hyphens in them, and that seem to be causing a problem. As you can see "photo-url-500" or another "photo-caption" is causing the script to break, it's outputting NaN.
Is there a problem with having hyphens in the key names? Or am I going about this all wrong?
If there are dashes in the names you'll need to access them differently. Change var photo500 = this.photo-url-500; to read var photo500 = this["photo-url-500"];.
Please note it is best not to append inside each iteration. Better to append to a string or push to an array then append once after the iterator has finished. Appending to the dom is expensive.
Use the bracket notation to access the members:
var photo500 = this['photo-url-500'];

Categories

Resources