It's been a while since I've toyed with my JS, so I might be missing something completely obvious. I have the following:
MyApp.IaeCheckboxCallback = function ($trigger) {
var $checkbox = $trigger.find('input[type="checkbox"]');
$checkbox.on('click', function () {
doIAECallbackNT($trigger.attr('id'), $trigger.data('data-recordid'), $trigger.data('data-recordtype'),
$trigger.data('data-valuejs'), $trigger.data('data-statuselement'), $trigger.data('data-callback'))
});
};
Once inside $checkbox.on, $trigger becomes undefined. How do I prevent this?
Adding more relevant code
I'm tying into this other developer's JS that is in another script file.
function doIAECallbackNT
(
iaeId,
recordId,
recordType,
fieldName,
value,
statusElementId
)
{
doIAECallbackNT(iaeId, recordId, recordType, fieldName, value, statusElementId, function(success) { });
}
function doIAECallbackNT
(
iaeId,
recordId,
recordType,
fieldName,
value,
statusElementId,
callback
)
{
var req = newXMLHttpRequestNT ();
var statusElement = document.getElementById(statusElementId);
setStatusNT(statusElement, "Updating...");
var msg =
"<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:Body>" +
"<HandleRequest xmlns='https://somesite.com/WebService/'>" +
"<iaeId>" + iaeId + "</iaeId>" +
"<recordId>" + recordId + "</recordId>" +
"<recordType>" + recordType + "</recordType>" +
"<fieldName>" + fieldName + "</fieldName>" +
"<value>" + escape(value) + "</value>" +
"</HandleRequest>" +
"</soap:Body>" +
"</soap:Envelope>";
//alert(msg);
req.onreadystatechange = function() {
if (req.readyState == 4) {
var success = false;
try { success = (req.responseXML.documentElement.getElementsByTagName("Success")[0].text.toLowerCase() == "true"); }
catch (e) { success = false; }
var msg2 = "";
//var msg3 = "";
try { msg2 = req.responseXML.documentElement.getElementsByTagName("Message")[0].text; }
catch (e) { msg2 = req.responseText; }
//msg3 = msg2;
if (!success) {
//Error: The string was not recognized as a valid DateTime. There is a unknown word starting at index 2.
if ( msg2.indexOf("valid DateTime") != -1 )
msg2 = "Failed: You entered an invalid date. Please re-enter the date.";
if (msg2.indexOf("StartDate_Must_Be_Before_EndDate") != -1)
msg2 = "Failed: The Start date must be prior to the End date. Try changing the start date first.";
//alert(msg2);
AddFailedNote(msg2);
if (statusElement.tagName.toLowerCase() != 'a')
msg2 = "<span class='error bold'>" + msg2 + "</span>";
}
else if (statusElement.tagName.toLowerCase() != 'a') {
AddSuccessNote(msg2);
msg2 = "<span class='success bold'>" + msg2 + "</span>";
}
setStatusNT(statusElement, msg2);
if (callback != null) { callback(success); }
}
};
req.open("POST", "../Services/IAEService.asmx", true);
req.setRequestHeader("Content-type", "text/xml; charset=utf-8");
req.setRequestHeader("Content-length", msg.length.toString());
req.setRequestHeader("SOAPAction", "https://www.somesite.com/WebService/HandleRequest");
req.send(msg);
}
and here's the ugly .NET rendering of a checkbox:
<span class="IaeCheckboxCallback" title="Ent?" data-recordid="11012" data-recordtype="Person" data-fieldname="HasEnterprise" data-statuselement="MainContent_MainContent_hrmol3_sp_ctl00" data-callback="function() { }" data-valuejs="MainContent_MainContent_hrmol3_dp_ctl00_0.checked" style="font-size:1em;"><input id="MainContent_MainContent_hrmol3_dp_ctl00_0" type="checkbox" name="ctl00$ctl00$MainContent$MainContent$hrmol3$dp$0$tc_HasEnterprise$ctl00" /></span>
The other person's code fails at: f (statusElement.tagName.toLowerCase() != 'a')
All the parameters that I've passed in show as undefined in the browser developer tool.
Related
In function readyStateChangeHandler(xhttp), my website (which returns a table) outputs both results of the handler, success and failure, even though the table is being displayed with no problems at all.
Notice below the "get search result" button, an error is being displayed from readyStateChangeHandler
function makeAjaxQuery() {
// create an XMLHttpRequest
var xhttp = new XMLHttpRequest();
// create a handler for the readyState change
xhttp.onreadystatechange = function() {
readyStateChangeHandler(xhttp);
};
// making query by async call
xhttp.open("GET", "xxxxxxx-A3-Q6.json", true);
xhttp.send();
}
// handler for the readyState change
function readyStateChangeHandler(xhttp) {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// readyState = 4 means DONE
//status = 200 means OK
handleStatusSuccess(xhttp);
console.log('success')
} else {
// status is NOT OK
console.log('failure')
handleStatusFailure(xhttp);
}
}
// XMLHttpRequest failed
function handleStatusFailure(xhttp) {
//display error message
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
// XMLHttpRequest success
function handleStatusSuccess(xhttp) {
var jsonText = xhttp.responseText;
//parse the json into an object
var obj = JSON.parse(jsonText);
// display the object on the page
displayObj(obj);
}
function displayObj(obj) {
var table = "";
for (i = 0; i < 5; i++) {
table +=
"<tr><td>" + '<img src="' + obj.result.video[i].image + '" width=200"' + '' + "</td><td>" +
'<span style="color:#DA3FA4; font-weight:bold; font-size: 30px;">' + obj.result.video[i].title + "</span>" + "<br/>" +
'<span style="font-weight:bold;font-size: 25px;">' + obj.result.video[i].channel + "</span>" + "<br/>" +
'<span style="font-weight:bold;font-size: 25px;">' + obj.result.video[i].view + " views" + "</span>" + "<br/>" +
'<span style="font-weight:bold; background-color: black; color:white"font-size: 25px;>' + obj.result.video[i].length + "</span>" + "</td></tr><td>";
}
document.getElementById("test").innerHTML = '<h1>Search results</h1><br><span style="font-size: 30px;">Search keyword: Mathematics</span><br>';
document.getElementById("demo").innerHTML = table;
}
const start = document.getElementById("getSearch");
start.addEventListener("click", function() {
makeAjaxQuery()
});
I would guess you get something in between the if (xhttp.readyState == 4 && xhttp.status == 200) { for example 2 or 3 plus 200 readystate - so for example use
xhttp.onload= function() {
readyStateChangeHandler(xhttp);
};
or fetch
One day ago I started messin' with phantomjs and their ability to read javascript generated data from the websites.[web scraping]
I'm trying to get element's text content by ID, but sometimes the particular website I try to crawl through doesn't have it, so then I get this error:
ERROR: TypeError: null is not an object (evaluating 'document.getElementById('resInfo-0').textContent')
TRACE:
-> undefined: 2
-> : 5
Screenshot from the Command Prompt:
My code so far:
1 step: reading the data from the file.
var file = "path to text file";
var fs = require('fs');
var stream = fs.open(file, 'r');
var urls = new Array();
var index = 0;
console.log("READING A FILE...");
while(!stream.atEnd()) {
var line = stream.readLine();
urls[index] = line;
index++;
}
console.log("FINISHED READING THE FILE");
index = 0;
2 step: Reading the data from the websites.
function web_page()
{
webPage = require('webpage');
page = webPage.create();
page.onError = function(msg, trace)
{
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in
function "' + t.function +'")' : ''));
});
}
console.log(msgStack.join('\n') + " URL: " + urls[index]);
phantom.exit(0);
};
phantom.onError = function(msg, trace)
{
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line +
(t.function ? ' (in function ' + t.function +')' : ''));
});
}
console.log(msgStack.join('\n')+ " URL: " + urls[index]);
phantom.exit(0);
};
page.open('http://www.delfi.lt/paieska/?q='+urls[index], function(status)
{
if (status !== 'success')
{
console.log('Unable to access network');
}
else
{
var fs = require('fs');
var path = 'output.txt';
var content = page.content;
var ua = page.evaluate(function()
{
var x = document.getElementById('resInfo-0').textContent;
return x;
});
if ( ua != null && ua != "" )
{
var indexas = ua.indexOf("(");
ua = ua.substr(0,indexas);
ua = ua.replace(/\D/g,'');
fs.write(path,urls[index] + " - "+ ua + "\r\n", 'a+');
}
}
});
setTimeout(next,1000);
}
console.log("STARTING TO CRAW WEBSITES...");
web_page();
function next()
{
if ( index + 1 <= 288103 )
{
page.close();
index++;
web_page();
}
else if ( index + 1 > 288103 )
{
console.log("FINISHED CRAWLING PROCESS");
phantom.exit(0);
}
}
var ua = page.evaluate(function()
{
var x = document.getElementById('resInfo-0').textContent;
return x;
});
The error comes from here probably:
var ua = page.evaluate(function()
{
var x = document.getElementById('resInfo-0').textContent;
return x;
});
What I've tried:
if ( document.getElementById('resInfo-0').textContent != null )
if ( document.getElementById('resInfo-0').textContent != "" )
So why can't it become null without triggering this error?
PhantomJS version is 2.1.1 binary windows package.
Sometimes document.getElementById('resInfo-0') is null, but you're still trying to get .textContent of it, hence the error. Try
var elem = document.getElementById('resInfo-0');
if(elem !== null) {
return elem.textContent;
}
return false;
I have few problems with below code.Can anyone help?
The if (currentStatus!="undefined") block in getStatusUsingAjax methid is not working.
unable to get the control out of getStatusUsingAjax method
$(document).ready(
loadStatus()
);
function loadStatus(x) {
$('.a-IRR-table tr').each(function(i) {
var val = $(this).find("td").eq(0).text();
link = $(this).find("td").eq(0).find("a").attr("href");
linkTag = $(this).find("td").eq(0).find("a");
`if ((val !== "-") && (val !== "")) {
console.log("val is" + val);
if (verifyrequestArray(val)) {
console.log("inside second if");
} else {
console.log("inside else");
sleep(1.5 * 1000);
var updatedStatus2 = getStatusUsingAjax(val, link);
console.log("UpdatedStatus2 is " + updatedStatus2);
setTooltip(linkTag, updatedStatus2);
}
}
});
}
function verifyrequestArray(id) {
var newArray = requestArray.toString().split('-');
console.log("NewArray is :" + newArray);
for (i = 0; i < newArray.length; i++) {
// I'm looking for the index i, when the condition is true
if (newArray[i] === id) {
console.log("request id found" + newArray[i]);
break;
} else {
console.log("request id not found" + newArray[i]);
return false;
}
}
}
function getStatusUsingAjax(requestValue, currentlink) {
console.log("patch req: " + requestValue);
console.log("Link is " + currentlink);
var currentStatus;
GM_xmlhttpRequest({
method: "GET",
url: currentlink,
onload: function(response) {
if ($(response.responseText).find("#P16_STATUS2").size() === 1) {
currentStatus = $(response.responseText).find("#P16_STATUS2").text();
console.log("Current Status from #P16_STATUS2 is :" + currentStatus);
console.log("Final URL is " + response.finalUrl);
}
}
});
// console.log("Final URL is " +response.finalUrl);
if (currentStatus != "undefined") {
var pusharr = [requestValue + "-" + currentStatus];
requestArray.push(pusharr);
console.log("Updated Array is " + requestArray);
return currentStatus;
}
}
function setTooltip(currentTag, status2) {
console.log("in settooltip" + currentTag);
currentTag.attr("title", status2); //setting status a tooltip
}
Any clue where the error is?
fn getStatusUsingAjax is async, you can not get return value using:
var updatedStatus2 = getStatusUsingAjax(val, link);
You sholud create callback:
function getStatusUsingAjax(val, link, callback){
//...
// do not use return currentStatus, call calback fn instead
callback(currentStatus)
}
and call it using:
getStatusUsingAjax(val, link, function(updatedStatus2){
console.log("UpdatedStatus2 is " + updatedStatus2);
setTooltip(linkTag, updatedStatus2);
});
i tried everything but i don't know where the mistake should be its show me a unespekted token } in a line where i not even have this sign.
<script type="text/javascript">
function postToStatus(action,type,user,ta){
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ><br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+
'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_'+sid+
'"><a href="#" onclick="return false" >onmousedown="deleteStatus("'+sid+
'\',\'status_'+sid+
'\');" title="DELETE THIS STATUS AND ITS REPLIES">delete status</a> ></span><br />'+data+
'</div></div>"'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
}
You need to put a semi-colon after the last } just before the ajax.send() call.
This website is your best friend if you write JavaScript: http://closure-compiler.appspot.com/home
function postToStatus(action, type, user, ta) {
var data = _(ta).value;
if (data == "") {
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if (datArray[0] == "post_ok") {
var sid = datArray[1];
data = data.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, " ><br />").replace(/\r/g, "<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_' + sid + 'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_' + sid + '">delete status ></span><br />' + data + '</div></div>"' + currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
};
ajax.send("action=" + action + "&type=" + type + "&user=" + user + "&data=" + data);
}
;
I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.