AJAX Query to Web Service in SharePoint on Button Click - javascript

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!

Related

how to get alert message content when page load and auto click

i have sevrale pages that have multiple jquery datatable and i just want to auto click alert when alert have this message : 'DataTables warning: table id='. i have set this javascript for auto click if this message comes.
code :
<script type="text/javascript">
debugger;
var htmlString = new XMLSerializer().serializeToString(document)
var indexOfAlertBeginning = "";
var indexOfAlertEnd = "";
var stringFromAlert = "";
var alertMessages = "";
if (htmlString.includes('alert(')) {
indexOfAlertBeginning = htmlstring.indexof('alert(');
stringFromAlert = htmlstring.substr(indexOfAlertBeginning);
indexOfAlertEnd = stringFromAlert.indexof(')');
alertMessages = stringFromAlert(0, indexOfAlertEnd);
}
if (stringFromAlert.includes('DataTables warning: table id=', 0)) {
window.alert = function () {
return true;
}
}
</script>
but this have no effect and alert message comes up every time. whats' wrong here please help me...
If you are loading data to the table using ajax most of the time cause the problem unmatched column name between json data and columnname in your script.
I found this post pretty useful for datatable and .Net Jquery Datatable with .Net

Can Not Set Value of DOM Element Unless New Value Is Strictly Numeric

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.

Having trouble appending javascript into my html

OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>

Javascript bookmarklet to send url of current page to bing

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>

jQuery replaceWith issue

I have an iframe to a third party system and which, when called, updates a database record and then displays a confirmation message. I'd like to change the text of the confirmation using jQuery, but cannot seem to get it working. This is the code I have so far. The call to the third party system works but the replacement text doesn't appear. Any pointers, please? Thank you.
<script type="text/javascript">
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return ''; }
return results[1] || '';
}
var lidval = $.urlParam('lid');
var cidval = $.urlParam('cid');
var cyidval = $.urlParam('cyid');
//construct url
var crmurl ='http://somerandomhost.com/Portal/index.php?task=unsusbscribe&lid='+lidval+'&cid='+cidval+'&cyid='+cyidval;
jQuery(function($){
$('#crm').attr('src', crmurl);
});
</script>
<iframe frameborder="0" id="crm" scrolling="no" width="100%" src=""></iframe>
<script type="text/javascript">
function($){
$('crm').replaceWith('Replacement text goes here');
};
</script>
if you want to show the string into the irframe try this:
PURE JS:
var doc = document.getElementById('crm').contentDocument;
doc.body.innerHTML = 'Replacement text goes here';
jQuery:
var doc = $('#crm')[0].contentDocument;
$(doc.body).html('Replacement text goes here')
To change content of an iframe you can Try below code
var ifr = $('#crm')[0].contentWindow.document,
ifbody = $('body',ifr);
ifbody.html('Replacement text goes here');

Categories