external function not called - javascript - javascript

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.

Related

how to fix javascript refresh error on google chrome

I have an error which is giving me a hard time to fix. I have written a program in JavaScript but when I refresh it doesn't affect the page. I even closed and opened the browser more than once but it didn't work, please does anyone have a solution to it?
This is some part of the code
var person = document.getElementById('formant');
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var num = document.getElementById('num').value;
var pass = document.getElementById('pass').value;
var conpass = document.getElementById('conpass').value;
var gen ='';
function setgen(f)
{
gen = document.getElementById(f).value;
}
person.addEventListener('submit', red);
function red(m)
{
m.preventDefault();
var xhr = new XMLHttpRequest();
// var response = document.getElementById().innerHTML;
xhr.open('POST','php/signupajax.php',true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function()
{
if(this.status == 200)
{
if(document.getElementById('pass').value.lenght < 0)
{
alert('less man');
}
console.log(this.responseText);
}
}
xhr.send('fname=' + document.getElementById('fname').value + '&lname=' + document.getElementById('lname').value + '&email=' + document.getElementById('email').value + '&num=' +document.getElementById('num').value+ '&pass=' + document.getElementById('pass').value + '&conpass=' +document.getElementById('conpass').value + '&gen=' + gen);
}
if(document.getElementById('pass').value <6)
{
alert('password not strong');
}
else{
alert('password good');
}

Using Ajax/XMLhttprequest to send data to a php file with mail function

I have been following this tutorial (https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) but I had no luck. I am trying to communicate with a php file with a javascript file using XMLhttpRequest. This is the code bellow. I still dont understand how to fully transfer the data across.
HTML
form id="uDF" method="post" onsubmit="submitValidation()">
JavaScript
function submitValidation(){
var data = [document.forms ["uDF"] ["uDFName"].value, document.forms ["uDF"] ["uDFNumber"].value,
document.forms ["uDF"] ["uDFEmail"].value, document.forms ["uDF"] ["uDFSubject"].value,
document.forms ["uDF"] ["uDFMessage"].value,]
console.log(data);
var char = ''; // variable used to check whether email has #
var x;
var isEmail = false;
var isNotEmpty = false;
//for loop checks email for # char
for(x = 0; x<data[2].length;x++)
{
char = data[2].charAt(x);
if(char === "#"){
isEmail = true;
break;
}
}
var i;
//for loop check if data is collected
for(i=0;i < 5;i++){
if(data[i] === ""){
isNotEmpty = false;
}else{
isNotEmpty = true;
}
}
if(isEmail === true && isNotEmpty === true)
{
var httpRequest;
httpRequest = new XMLHttpRequest();
if(!httpRequest){
return false;
}
httpRequest.onreadystatechange = function(){
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200)
{
var response = JSON.parse(httpRequest.responseText);
}
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]))
}
}else if (!isNotEmpty){
alert("empty fields");
}else if(!isEmail){
alert("Please enter valid email!");
}
}
PHP
$uDFName = (isset($_POST['uDFName'])) ? $_POST['uDFName'] : '';
$uDFNumber = (isset($_POST['uDFNumber'])) ? $_POST['uDFNumber'] : '';
$uDFEmail = "my#email";
$uDFSubject = (isset($_POST['uDFSubject'])) ? $_POST['uDFSubject'] : '';
$uDFMessage = $uDFName . "\r\n" . $uDFNumber . "\r\n" . "just testing";
$message = wordwrap($message, 70, "\r\n");
mail($uDFEmail, $uDFSubject, $uDFMessage);
You have to open and send the request outside of the event handler function. The onreadystatechange handler only executes when the ready state of your request changes.
If you don't open and send the request, the handler function is not executed, and you won't see any results.
This solution should work:
var httpRequest = new XMLHttpRequest();
// this function executes whenever the ready state of the request changes
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
}
}
// open the request ...
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// ... and send it
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]));

mediawiki api can not display the results from array

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

jQuery.post() dynamically generated data to server returns empty response

I'm generating a series of variables in a loop (using JS), and I'm assigning them an .id and a .name based on the current index. At each loop I'm sending a request to the server using jQuery.post()method, but the returning response is just an empty variable.
Here's the code:
JavaScript
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
$(document).ready(function(){
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
});
}
PHP
<?php
$index = $_POST['ind'];
$myVar = $_POST['myVarID'.$index];
echo $myVar;
?>
Response: Server response: ''
If I instead set a static index in JS code, getting rid of the loop, so for example:
var index = 0;
I get the expected result: Server response: myVarName0
Why is this happening? And how can I solve it?
Assuming the php file is in order. I use this:
function doThing(url) {
getRequest(
url,
doMe,
null
);
}
function doMe(responseText) {
var container = document.getElementById('hahaha');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
var thing = "script.php?" + url;
req.open("GET", thing, true);
req.send(null);
return req;
}
then use it like this:
doThing("myVarID="+myVar.id+"&i="+index);
also, you will have to change your PHP to something like this:
<?php
$index = $_GET['ind'];
$myVar = $_GET['myVarID'.$index];
echo $myVar;
?>
Obviously this code needs to be edited to suit your own needs
the function doMe is what to do when the webpage responds, in that example I changed the element with the id hahaha to the response text.
This won't win you any prizes but it'll get the job done.
Solution
It is working fine removing:
$(document).ready()
Working code
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
}

Overriding XMLHttpRequest's open/send method

I am trying to catch every XHR Request send from Gmail and add a classification lable in the body of the mail. I am not sending new XHR requests. My code is working like filter for all XHR requests by overriding XMLHttpRequest's open/send function. I am working on this issue from last week.Please help me.
function sendEmail() {
//alert("In sendEmail()");
var overrideMethods = function() {
//alert("In overrideMethods()");
window.XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
this.openParams = {
url: url
};
return window.XMLHttpRequest.prototype._open.apply(this, arguments);
};
window.XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function send() {
var defered = false;
var searchPattern = /(&selectedLable=|^selectedLable=)(.*?)&/;
alert("In send()");
if (typeof arguments[0] === "string" && arguments.length === 1) {
var str = arguments[0];
//alert("Inside of first if");
//alert("str : " + str);
if (this.openParams.url.match(/&act\=sm/) && str.match(/&bcc\=/) && str.match(searchPattern)) {
defered = true;
var sendData = (str.match(searchPattern) && str.match(searchPattern)[2]);
var tag = JSON.parse(decodeURIComponent(sendData)).tag;
alert("tag : " + tag);
/* Modify the POST url to reflect the tag */
str = str.replace(searchPattern, "");
str = str.replace(/&subject=/, "&subject=" + tag + ": ");
str = str.replace(/&body\=/, "&body=<br>" + tag.toLowerCase() + "<br>");
/* Capitalize the tag. */
arguments[0] = str + "&acn=!" + tag.charAt(0).toUpperCase() + tag.slice(1).toLowerCase();
window.XMLHttpRequest.prototype._send.apply(this, arguments);
}
}
if (!defered) { 
window.XMLHttpRequest.prototype._send.apply(this, arguments);
}
};
}
window.location.href = 'javascript: (' + overrideMethods.toString().replace(/(\n|\ {2,})/gm, '') + ')();';
}
sendEmail();
I found this link on stack overflow :
Overriding XMLHttpRequest's send method
Please note my method is working fine for native chrome extension, but its not working for crossrider extension.

Categories

Resources