I'm newbie on sap abap and sap crm and javascript. I'm trying to get facebook's page stream into my bsp app.
<%#page language="abap" %>
<%#extension name="htmlb" prefix="htmlb" %>
<htmlb:content id = "content"
design = "design2003"
controlRendering = "sap"
rtlAutoSwitch = "true" >
<htmlb:page title="jQuery" >
<htmlb:form id = "formBody"
method = "post" >
<script type="text/javascript" src="jquery-1.7.2.min.js" ></script>
<script>
function getPosts() {
FB.api('/8****5833028****/feed', 'get', { access_token : '7***5058***8**7|qJzB0*****VRC***YfE****wpk4' }, function(normalData) {
if (!normalData || normalData.error) {
alert('Error occured');
} else {
alert(normalData.data[0].from.name);
$('<div class="result"></div>')
.append('<h3>' + normalData.data[0].from.name + '</h3>')
.append('<h3>' + normalData.data[0].message + '</h3>')
.appendTo('body');
document.getElementById("gv_response").value = normalData;
}
});
}
</script>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '7***5058***8**7',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
Facebook
<htmlb:inputField id = "gv_response"
type = "string"
visible = "true"
size = "120" />
<htmlb:button id = "myButton11"
text = "onClick"
onClick = "getPosts" />
<body>
<div class="result"></div>
</body>
</htmlb:form>
</htmlb:page>
</htmlb:content>
With above code, i took all data and i write user name on page from facebook wall's feed. My access_token and connection is right.
Here's my question, how can i pass value into bsp app.'s variable.
- should i parse value in javascript and pass only asked value's?
- or is that possible take all value into bsp's variable and serialize in bsp app?
note: i know there's an abap function can serialize jsons.
For now i choose a way like this; I created all possible field i should use with html(or htmlb) code and those fields were hidden. With javascript code, i give my asked value into those fields.
Fields per feed sample:
<htmlb:inputField id = "fb_002_uname" />
<htmlb:inputField id = "fb_002_umssg" />
<htmlb:inputField id = "fb_002_ctime" />
<htmlb:inputField id = "fb_002_utime" />
Javascript code:
document.getElementById("fb_002_uname").value = normalData.data[1].from.name;
document.getElementById("fb_002_umssg").value = normalData.data[1].message;
document.getElementById("fb_002_ctime").value = normalData.data[1].created_time;
document.getElementById("fb_002_utime").value = normalData.data[1].updated_time;
And in abap:
request->get_form_fields( CHANGING fields = lt_data ).
like these i'll get all fields value.
Why i choose like this way?
Because i couldn't get json from facebook.
If you know how can i get json string from facebook, please help me and if you can with sample.
Thank you.
Utku
Related
I am trying to have a button on a SharePoint form query the govt SAM web service. Basically, I want to be able to manually enter a value in the form, click an HTML button, to query that value from the open form, and then fill out the rest of the fields automatically and save the record in a SP list. I am just working on the query portion now. I have jquery embedded in my master page.
When I wrote all the logic in the browser console, everything works fine. I cannot get it to mesh up with the button. I get this error in the console.
"Uncaught SyntaxError: Unexpected token <" which makes no sense. Here is my script:
<script>
$("button").click(function () {
var SAM_Title = document.getElementById('Title_fa564e0f-0c70-4ab9-b863-
0177e6ddd247_$TextField').value;
var URL = "https://api.data.gov/sam/v1/registrations/" + SAM_Title +
"0000?api_key=xxxxxxxxxxxxxxxxxxxxxxx";
var SAM_AJAX = $.get(URL);
var SAM_JSON = SAM_AJAX.responseText;
var parsedJSON = JSON.parse(SAM_JSON);
var BusinessName = parse.sam_data.registration.legalBusinessname;
var StreetAddress =
parsedJSON.sam_data.registration.govtBusinessPoc.address.Line1;
var City = parsedJSON.sam_data.registration.govtBusinessPoc.address.City;
var ZIP = parsedJSON.sam_data.registration.govtBusinessPoc.address.ZIP;
}
</script>
Here is what I am putting in my script editor web part:
<html>
<script src="/SiteAssets/SAM_Query.js">
</script>
<body>
<button>Get External Content</button>
</body>
</html>
where SAM_Query.js is the above mentioned script.
I got it to work. The key was line 13 and cleaning up the syntax.
jQuery.noConflict();
jQuery( document ).ready(function() {
console.log( "jquery ready!" );
})
function samWebService() {
SAM_Title = document.getElementById('Title_fa564e0f-0c70-4ab9-b863-0177e6ddd247_$TextField').value;
console.log("DUNS: " + SAM_Title);
URL = "https://api.data.gov/sam/v1/registrations/" + SAM_Title + "0000?api_key=xxxxxxxxx";
console.log("URL: " + URL);
jQuery.ajaxSetup({ async: false });
SAM_AJAX = jQuery.get(URL);
console.log("SAM JSON response: " + SAM_AJAX);
SAM_JSON = SAM_AJAX.responseText;
console.log(SAM_JSON);
parsedJSON = JSON.parse(SAM_JSON);
console.log(parsedJSON);
BusinessName = parsedJSON.sam_data.registration.legalBusinessName;
StreetAddress = parsedJSON.sam_data.registration.mailingAddress.Line1;
City = parsedJSON.sam_data.registration.mailingAddress.City;
ZIP = parsedJSON.sam_data.registration.mailingAddress.Zip;
document.getElementById('Address_bc611d08-c16c-4ad9-a5b8-14388e176aba_$TextField').value=StreetAddress
document.getElementById('City_dd99bc74-382f-406c-aec0-8dc196b2c8ef_$TextField').value = City
document.getElementById('Business_x0020_Name_5eb60d17-9d0b-4243-92f5-81f5534e8bc0_$TextField').value = BusinessName
document.getElementById('ZIP_e078f52b-a0bc-4c95-a622-a16d6491b017_$TextField').value = ZIP
};
And calling the function with a clickable link.
<script src="/siteassets/lib/jquery/jquery.min.js"></script>
<script src="/test/SiteAssets/SAM_Query.js"></script>
Click Me!
I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.
hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')
Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.
Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});
You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code¶meter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).
I need to send a parameter value into a query string of a PostBackUrl method
within asp button.
The value I need is already being captured within a java script function shown below.
How do I send the value in hiddId as part of URL ? The below method isn't working. Can someone please help ?
<script language="javascript" type = "text/javascript">
function btn_Selected() {
var hiddId = null;
$('#<%=GridView1.ClientID %>').find('input[type=radio]:checked').each(function () {
hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
});
}
<asp:Button ID="Btn_Update" runat="server" Text="Update" PostBackUrl="Screen_Edit.aspx?CustID='<%=hiddId%>'"
Instead of a post-back, just redirect using JavaScript.
function btn_Selected() {
var hiddId = null;
$('#<%=GridView1.ClientID %>').find('input[type=radio]:checked').each(function () {
hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
});
window.location.href = "Screen_Edit.aspx?CustID='" + hiddId + "'"
}
If you look at the HTML source of the page, the button will have an javascript onclick event that looks something like this javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$mainContentPane$Btn_Update", "", false, "", "Screen_Edit.aspx?CustID=", false, false))
All we have to do is find a way to insert your variable after ?CustID=.
You can replace the onclick value of the button with the .attr() function of jQuery and do a search and replace to insert your variable.
<script type="text/javascript">
$(document).ready(function () {
var hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
$("#<%=Btn_Update.ClientID %>").attr("onclick", $("#<%=Btn_Update.ClientID %>").attr("onclick").replace("?CustID=", "?CustID=" + hiddId));
});
</script>
DISCLAIMER: total beginner with regards to browser extensions and javascript.
BACKGROUND:
I'm trying to develop a proof-of-concept Chrome extension that picks up the text from the input fields in the HTML form of the web page loaded into one tab, and enters the same text on analogous fields of the page in another tab.
In my particular example, the source page is a minimal, local HTML file with two input fields ("user name" and "password"), and the destination is the login page for Apple's Developer Website (https://developer.apple.com/account/).
Reading the official guides and questions here, I've put together some code that seems to work.
THE PROBLEM:
Only text consisting of digits (e.g.: "111111") gets copied from one tab to the other. As soon as my input field contains letters (e.g.: "111111a"), nothing happens.
This is the source page (local file:///):
<html>
<head>
<title>Source Page</title>
<meta charset="utf-8" />
<script src="popup.js"></script>
</head>
<body>
<form>
<input id="accountname_src" name="appleId" placeholder="Apple ID" /><br />
<input id="accountpassword_src" name="password" placeholder="Password" />
</form>
</body>
</html>
The destination HTML (Apple's page) has similar input fields with element ids of accountname and accountpassword, respectively.
My extension's script is as follows:
document.addEventListener('DOMContentLoaded', function(){
// The button in the browser action popup:
var button = document.getElementById('autofill');
var sourceTabID = null;
var destTabID = null;
// Get the SOURCE tab id:
chrome.tabs.query({'title': 'Source Page'}, function(tabArray){
sourceTabID = tabArray[0].id;
});
// Get the DESTINATION tab id:
chrome.tabs.query({'title': 'Sign in with your Apple ID - Apple Developer'}, function(tabArray){
destTabID = tabArray[0].id;
});
if (button !== null){
button.addEventListener('click', function(){
// Get entered text from Source page:
chrome.tabs.executeScript(sourceTabID, {file: "read_input.js"}, function(results){
var credentials = results[0];
var userName = String(credentials[0]);
var password = String(credentials[1]);
// Pass values to Apple login page:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
var autofillCode = insertUserNameCode + insertPasswordCode;
chrome.tabs.executeScript(destTabID, {code:autofillCode});
});
//window.close();
});
}
});
of course, the contents of read_input.js are:
var userName = document.getElementById("accountname_src").value;
var password = document.getElementById("accountpassword_src").value;
var attributes = [userName, password];
attributes // (Final expression, passed to callback of executeScript() as 'results')
It feels like there could be a type inference problem somewhere, but can't tell where.
Bonus Question:
I can read the input fields in the source page using an external script (read_input.js above) and the method chrome.tabs.executeScript(..., file:...; but when I try to write the values to the destination tab using a similar approach, the script does not run (that is why I'm using chrome.tabs.executeScript(..., code:... in my code). Any idea what can be happening?
Silly me (again)... Some console.logging led me in the right direction...
I was not escaping the value in the script; these lines:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
...should be:
var insertUserNameCode = "document.getElementById('accountname').value = '" + userName + "';"
var insertPasswordCode = "document.getElementById('accountpassword').value = '" + password + "';"
(added single ticks around the values)
...so that the code ends up as:
document.getElementById('accountname').value = '111111a';
...instead of:
document.getElementById('accountname').value = 111111a;
Still not sure why a numbers-only value works, though.
A bookmarklet is a bookmark whose address is JavaScript code.
I would like to get the URL of the current page I am on and paste that into the text box of the Bing search page.
I can get the URL easily enough:
javascript:(function(){var%20url=window.location.href;alert(url);})();
But then how do I set the text box on the Bing page to my variable, url and then make it search?
This does not work:
javascript:(function(){var%20url=window.location.href;window.open%20("https://www.bing.com/search?q=&url");})();
Use the following bookmarklet code:
javascript:{window.location='http://bing.com/search?q='+encodeURIComponent(window.location.href)}
Of course you can do the way you have seen above. However, I have been in this situation where I wanted to control what to show from within my application.
Then I decided to connect my application from Bing API. The benefit is that it is free and you will not take user away from your website.
You will need to get the API Key from the Azure Market Place
Here is the code that you might want to give it a try , may be, in the future.
<html>
<head>
<title>BING API Integration</title>
<SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#searchButton').click(function(e){
$("#results").empty();
var query=$('#searchTerm').val();
if ( query) {
serviceOp = "Web";
search(query, serviceOp);
}
});
});
function search(query, serviceOp){
// your account key that youw ill get from https://datamarket.azure.com
var acctKey = '<Your Key>';
var rootUri = 'https://api.datamarket.azure.com/Bing/Search';
var requestUri = rootUri + "/" + serviceOp + "?$format=json&Query='" + query + "'";
$.ajax({
type: "GET",
url: requestUri,
headers: {
"Authorization": "Basic " + window.btoa(acctKey + ":" + acctKey)
},
}).done(function(o){
if ( o.d !== undefined){
var items = o.d.results;
for(var idx=0, len= items.length; idx < len; idx++ ){
var item = items[idx];
switch(item.__metadata.type){
case 'WebResult':
showWebResult(item);
}
}
}
});
}
// Shows one item of Web result.
function showWebResult(item) {
var p = document.createElement('p');
var a = document.createElement('a');
a.href = item.Url;
$(a).append(item.Title);
$(p).append(item.Description);
$('#results').append(a, p);
}
</script>
</head>
<body>
<label for="searchTerm">Search: </label>
<input id="searchTerm" type="text"/>
<button id="searchButton">Search</button>
<div id="results">
</div>
</body>
</html>