Hello you wonderful people, I am trying to build JavaScript file to extract information from Wikipedia based on search value in the input field and then display the results with the title like link so the user can click the link and read about it. So far I am getting the requested information in(JSON)format from Mediawiki(Wikipedia) but I can't get it to display on the page. I think I have an error code after the JavaScript array.
I'm new at JavaScript any help, or hint will be appreciated.
Sorry my script is messy but I am experimenting a lot with it.
Thanks.
var httpRequest = false ;
var wikiReport;
function getRequestObject() {
try {
httpRequest = new XMLHttpRequest();
} catch (requestError) {
return false;
}
return httpRequest;
}
function getWiki(evt) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
var search = document.getElementsByTagName("input")[0].value;//("search").value;
if (!httpRequest) {
httpRequest = getRequestObject();
}
httpRequest.abort();
httpRequest.open("GET", "https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=" + search , true);//("get", "StockCheck.php?t=" + entry, true);
//httpRequest.send();
httpRequest.send();
httpRequest.onreadystatechange = displayData;
}
function displayData() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
wikiReport = JSON.parse(httpRequest.responseText);//for sunchronus request
//wikiReport = httpRequest.responseText;//for asynchronus request and response
//var wikiReport = httpRequest.responseXML;//processing XML data
var info = wikiReport.query;
var articleWiki = document.getElementsByTagName("article")[0];//creating the div array for displaying the results
var articleW = document.getElementById("results")[0];
for(var i = 0; i < info.length; i++)
{
var testDiv = document.createElement("results");
testDiv.append("<p><a href='https://en.wikipedia.org/?curid=" + query.pages[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
var newDiv = document.createElement("div");
var head = document.createDocumentFragment();
var newP1 = document.createElement("p");
var newP2 = document.createElement("p");
var newA = document.createElement("a");
head.appendChild(newP1);
newA.innerHTML = info[i].pages;
newA.setAttribute("href", info[i].pages);
newP1.appendChild(newA);
newP1.className = "head";
newP2.innerHTML = info[i].title;
newP2.className = "url";
newDiv.appendChild(head);
newDiv.appendChild(newP2);
articleWiki.appendChild(newDiv);
}
}
}
//
function createEventListener(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener) {
form.addEventListener("submit", getWiki, false);
} else if (form.attachEvent) {
form.attachEvent("onsubmit", getWiki);
}
}
//createEventListener when the page load
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
Mediawiki api link
https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=
You are wrong some points.
1)
var articleW = document.getElementById("results")[0];
This is wrong. This will return a element is a reference to an Element object, or null if an element with the specified ID is not in the document. Doc is here (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
The correct answer should be :
var articleW = document.getElementById("results");
2)
var info = wikiReport.query;
for(var i = 0; i < info.length; i++) {}
The info is object . it is not array , you can't for-loop to get child value.
wikiReport.query is not correct wiki data. The correct data should be wikiReport.query.pages. And use for-in-loop to get child element
The correct answer:
var pages = wikiReport.query.pages
for(var key in pages) {
var el = pages[key];
}
3) This is incorrect too
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. You are using the method to adds a string . This will cause error. Change it to node element or use append method instead
I have created a sample test.You can check it at this link below https://codepen.io/anon/pen/XRjOQQ?editors=1011
Related
I have a few different JavaScript web resources that use the getGrid(), all of which started failing this week after I enabled the 2020 Wave 1 Updates in D365. The error message shows:
"Error occurred :TypeError: Unable to get property 'getGrid' of undefined or null reference"
Here is my code:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
console.log("this resource name=" + thisResourceName)
}
});
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
console.log("duplicates found= " + duplicatesFound);
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Page.getAttribute("new_showduplicateerror").setValue(true);
Xrm.Page.getControl("new_showduplicateerror").setVisible(true);
Xrm.Page.getControl("new_showduplicateerror").setNotification("A duplicate resource was found. Please remove this before saving.");
} else {
Xrm.Page.getAttribute("new_showduplicateerror").setValue(false);
Xrm.Page.getControl("new_showduplicateerror").setVisible(false);
Xrm.Page.getControl("new_showduplicateerror").clearNotification();
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Here is a separate web resource that triggers the function:
function TriggerSalesQDResourceCount(executionContext){
var formContext = executionContext.getFormContext();
formContext.getControl("s_qd").addOnLoad(GetTotalResourceCount);
}
Any ideas how I can fix this? Is this a known issue with the new D365 wave 1 update?
Thanks!
This is the problem with unsupported (undocumented) code usage, which will break in future updates.
Unsupported:
var gridCtx = formContext._gridControl;
You have to switch to these supported methods.
function doSomething(executionContext) {
var formContext = executionContext.getFormContext(); // get the form Context
var gridContext = formContext.getControl("Contacts"); // get the grid context
// Perform operations on the subgrid
var grid = gridContext.getGrid();
}
References:
Client API grid context
Grid (Client API reference)
I have placeholder with any web page url. It should extract the elements when i click on button. I have to show elements and xpath values in my page. How can i do that? Please help me.
I'm not sure if that is what you want, but if you need to display every element's XPath, here is my solution:
function buildDom(text) {
var div = document.createElement('div');
div.innerHTML = text;
return div.firstChild;
}
function fetchAttrs(node) { // getting attributes object for element
return node && Array.prototype.reduce.call(node.attributes, function(list, attribute) {
list[attribute.name] = attribute.value;
return list;
}, {}) || {};
};
function traverseElement(element, argPrefix = "") {
if (element.nodeType === Node.TEXT_NODE)
return; // skipping text elements
var attrs = fetchAttrs(element)
var prefix = argPrefix + "/" + element.tagName; // build element path
if (Object.keys(attrs).length !== 0){
prefix += "[" + Object.keys(attrs).map((value, index) => {
return "#" + value + ' = "' + attrs[value] + '"'
}).join(" and ") + "]" // append arguments
}
console.log(prefix);
var children = element.childNodes // iterating over children
for (var i = 0; i < children.length; i++)
{
traverseElement(children[i], prefix)
}
}
var url = "https://icanhazip.com/" // URL to load
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // when loaded
var dom = buildDom(this.responseText); // build a DOM tree from a response string
traverseElement(dom) // and traverse it
}
};
xhttp.open("GET", url, true);
xhttp.send(); // loading needed website
I am creating an AJAX dynamic search bar which returns results from a database. I find that when i open the debugger, the code isn't entering the function handleSuggest() which sets the inner html of the div where the results are shown. Here is my code.
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
var search = getXmlHttpRequestObject();
function ajaxSearch(){
if (search.readyState == 4 || search.readyState == 0){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", 'searchSuggest.php?search=' + str, true);
search.onreadystatechange.handleSearchSuggest();
search.send(null);
}
}
function handleSearchSuggest(){
if(search.readyState == 4){
var ss = document.getElementById('ajaxSearch');
ss.innerHTML = '';
var str = search.responseText.split("\n");
for(i=0; i<str.length-1; i++){
var suggestion = '<div onmouseover="javascript:suggestOver(this);"';
suggestion += 'onmouseout="javascript.suggestOut(this);"';
suggestion += 'onclick="javascript:setSearch(this.innerHTML);"';
suggestion += 'class="suggestLink">' + str[i] + '<div>';
ss.innerHTML += suggestion;
}
}
}
function suggestOver(divValue){
divValue.className = "suggestLink";
}
function suggestOut(divValue){
divValue.className = "suggestLink";
}
function setSearch(x){
document.getElementById('searchBox').value = x;
document.getElementById('ajaxSearch').innerHTML = '';
}
The problem is in this line:
search.onreadystatechange.handleSearchSuggest();
search.onreadystatechange needs a callback function assigned to it.
Change it to the following:
search.onreadystatechange = handleSearchSuggest;
Note that this does not invoke the handleSearchSuggest function here as onreadystatechange needs a callback function not the result of the function.
can anyone tell me why this is not working?
ui = (function() {
collabElement = document.getElementById( 'approveCollab' );
if(collabElement)
collabElement.onclick = function(){editor.collaborate(); removeOverlay();}
deleteElement = document.getElementById( 'approveDelete' );
if(deleteElement)
deleteElement.onclick = function(){editor.deletePost(); removeOverlay();}
})();
"collaborate" is an exported function in "editor.js" file.
removeOverlay()" is a function in the same file.
when "collabElement" is clicked only "removeOverlay" is being called.
there are no errors, just that the function is not called at all.
these are the function being called from editor.js:
function collaborate( event ) {
console.log("started");
var url = '';
var postID = document.querySelector('.save').getAttribute('id');
var recipient = document.querySelector('.collab-input').value;
//validate email syntax
var atpos=recipient.indexOf("#");
var dotpos=recipient.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
console.log("wrong email");
document.querySelector('.email-error').style.display = "block";
}
else{
console.log("sending email to " + recipient);
document.querySelector('.email-error').style.display = "none";
if(postID != "new"){
url = url + "?id=" + postID + "&recipient=" + recipient;
var request = new XMLHttpRequest();
request.open("GET", "collaborate"+url, true);
request.send();
}
}
}
function deletePost( event ) {
var url = '';
var postID = document.querySelector('.save').getAttribute('id');
if(postID != "new"){
url = url + "?id=" + postID;
var request = new XMLHttpRequest();
request.open("GET", "delete"+url, true);
request.send();
}
}
If you want to call a function add () to it.
editor.collaborate()
(instead of editor.collaborate, which will just only address the function)
I suspect the problem is that your IIFE is not returning anything; ui will always be undefined. I think you want this:
ui = (function() {
collabElement = document.getElementById( 'approveCollab' );
if(collabElement)
collabElement.onclick = function(){editor.collaborate; removeOverlay();}
//return collabElement so it's assigned to ui
return collabElement;
})();
EDIT
While it's true your IIFE does not return anything, it looks like Peter's answer is more relevent to you at the moment; collaborate is not being called. His appears to be the right answer to this question.
As seen below I'm trying to get #currentpage to pass client params
Can someone help out thanks.
$(document).ready(function() {
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
}
var url = $("currentpage");
// yes I relize this is the part not working.
var client = jQuery.param("currentpage");
var page = jQuery.param("currentpage");
var devurl = "http://#/?clientsNumber=" + client + "&pageName=" + page ;
});
This is a method to extract the params from a url
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Here's how to use it in your code
var url = "?c=231171&p=home";
var params = getUrlParams(url);
var devurl = "http://site.com/?c=" + encodeURIComponent(params.c) + "&p=" + encodeURIComponent(params.p) + "&genphase2=true";
// devurl == "http://site.com/?c=231171&p=home&genphase2=true"
See it in action http://jsfiddle.net/mendesjuan/TCpsD/
Here's the code you posted with minimal changes to get it working, it also uses $.param as it's intended, that is to create a query string from a JS object, this works well since my suggested function returns an object from the url
$(document).ready(function() {
// This does not handle arrays because it's not part of the official specs
// PHP and some other server side languages support it but there's no official
// consensus
function getUrlParams(url) {
var paramMap = {};
var questionMark = url.indexOf('?');
if (questionMark == -1) {
return paramMap;
}
var parts = url.substring(questionMark + 1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
// no need for the extra load listener here, jquery.ready already puts
// your code in the onload
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentpage').innerHTML = tab.url;
});
var url = $("currentpage");
var paramMap = getUrlParams(url);
// Add the genphase parameter to the param map
paramMap.genphase2 = true;
// Use jQuery.param to create the url to click on
var devurl = "http://site.com/?"+ jQuery.param(paramMap);
$('#mydev').click( function(){
window.open(devurl);
});
});