Trying to read responseText to XMLRequest is just duplicating the body - ajax

So what's the deal? I'm simply trying to read text from this file. However, this code has the odd effect that, when I click the button, it seems to take the content of the page as the responseText, and will duplicate the button and paragraphs. Yet as far as I can tell I am mimmicking the W3Schools example, yet it doesn't work.
<head></head>
<body>
<button onclick = "loadDoc()">Something to load?</button>
<p>Here's a paragraph</p>
<script>
function loadDoc(){
let xhttp = new XMLHttpRequest();
xhttp.onload = function()
{
document.write(this.responseText);
}
xhttp.open("GET", "testText.txt");
xhttp.send();
}
</script>
</body>

Related

Ajax - understanding of the code

I try to understand Ajax. I'd like to understand how the data and commands flow in the code. I have the following code. Please, read my comments in this code. The comments describe, how I understand the code. The problem is marked as PROBLEM!!! Important notice: The code is working, I only try to understand the code.
<!DOCTYPE html>
<HTML>
<HEAD>
<META charset="UTF-8" />
<TITLE>Test02</TITLE>
</HEAD>
<BODY>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<SCRIPT>
function loadDoc() {
// select right object
function createXhttp(){
var variable;
if (window.XMLHttpRequest) {
// code for modern browsers
variable = new XMLHttpRequest();
} else {
// code for IE6, IE5
variable = new ActiveXObject("Microsoft.XMLHTTP");
}
return variable;
}
var xhttp = createXhttp();
// check the state
xhttp.onreadystatechange = function (){
// if the response is ready and file or url exists
if (xhttp.readyState == 4 && xhttp.status == 200) {
/* display the text in console - but which text if xttp.open
with source file is opened on the next line? (PROBLEM!!!)*/
console.log(xhttp.responseText);
}
};
// use method get and load the content of ajax_info.txt
xhttp.open("GET", "ajax_info.txt", true);
// send the request above
xhttp.send();
}
</SCRIPT>
</BODY>
</HTML>
Thank you for your advice.
but which text if xttp.open with source file is opened on the next line?
Let's take another example.
document.getElementById('some_button').onclick = function () {
console.log(document.getElementById("some_text_box").value);
}
It doesn't matter if the user hasn't typed anything in some_text_box at this point, because the function won't run until some_button is clicked.
Now back to XHR:
xhttp.onreadystatechange = function (){
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
};
… it doesn't matter that the request hasn't been sent yet, because the function won't run until the response arrives.
(OK, it will run every time the ready state changes, but the if statement means the meat of it won't run until the response arrives).

How to correctly set the request header in an ajax containing non-alphanumeric characters?

My HTML file contains a form with just a textarea whose contents are sent to a java servlet (called "Compiler"). The textarea text will always be java code, so it might include characters like +, %, =, etc.
I'm using ajax to get and display the response from the servlet.
But using ajax breaks the whole data being sent by the form, because it strips out part of the text or completely ignores the characters I mentioned above.
This is my html file:
<html>
<head>
<script type="text/javascript">
function objetoAjax(){
http_request= false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return http_request;
}
function devolver_resultado(){
var llamadaAjax = objetoAjax();
var codigo = document.getElementById('codigo').value;
llamadaAjax.open("POST",'Compiler',true);
llamadaAjax.onreadystatechange = function() {
if(llamadaAjax.readyState == 4){
document.getElementById("resultado").innerHTML = llamadaAjax.responseText;
}
};
llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
llamadaAjax.send('codigo='+codigo);
}
</script>
</head>
<body>
<form action="Compiler" method="post">
<textarea rows="18" cols="70" id="codigo" name="codigo"></textarea>
<input type="submit" value="Compile" onclick="devolver_resultado(); return false;">
</form>
<div id="resultado">
</div>
</body>
</html>
I've debugged the javascript to see if the problem was where I assign the textarea value to the "codigo" variable:
var codigo = document.getElementById('codigo').value;
(screenshot)
But this variable is being correctly set, so I suspect the request is being incorrectly encoded (screenshot).
I'm new to ajax, but I assume this is controlled by llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
From this page I get that I should encode the form as multipart/form-data. I tried adding the encoding type to the form: but this didn't help.
So, two questions here:
1) Is actually this line the faulty one? llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
If so, how do I fix it?
2) If that's not where the bug is, what else could be happening? (remember that removing all the ajax and leaving a plain form that calls my "Compiler" servlet works as expected, so the servlet is not buggy).
Thanks!
SOLVED.
All I needed was to encode the text before sending it:
llamadaAjax.send('codigo='+encodeURIComponent(codigo));

CKEditor4 Clipboard issue

I am trying to select all the content from a CKEditor instance and copy it to the clipboard when the user clicks a button on a different part of the screen. When the page initially loads, and I click the "Copy to Clipboard" button, the selectAll command works, but the copy command does not work. However, if I click the button a second time, everything works correctly.
Does anyone know how to resolve this issue? I am new to CKEditor, but this seems like a focus or timing issue. I'd rather not have to code phantom button clicks to make this work. Any help is greatly appreciated.
Here is my code. As you can see, I also tried wrapping the copy command in the "afterCommandExec" callback from the "selectAll" command. That didn't work either.
<html>
<head>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
var g_editorObj = new Object;
window.onload = function () {
g_editorObj = CKEDITOR.replace('editor1');
}
function doCopyClipBoard() {
try {
g_editorObj.focus();
g_editorObj.execCommand("selectAll");
g_editorObj.execCommand("copy");
//g_editorObj.on('afterCommandExec', handleCopy);
} catch (ex) {
alert(ex.Message);
}
}
function handleCopy() {
g_editorObj.execCommand("copy");
}
</script>
</head>
<body>
<input type="button" onclick="doCopyClipBoard()" value="Copy to Clipboard" /><br />
<textarea id="editor1" name="editor1" rows="10" cols="80">Testing this thing</textarea>
</body>
</html>
Please check if this order of things will work for you:
editor.focus();
editor.once( 'selectionChange', function() {
editor.execCommand( 'copy' );
} );
editor.execCommand( 'selectAll' );
or alternatively:
editor.execCommand( 'selectAll' );
setTimeout( function() {
editor.execCommand( 'copy' );
}, 0 );
Note that access to the clipboard is only possible in IEs. It's a matter browser limitations and there's no way to bypass that thing.

having trouble running a fadein-fadeout Image banner

I am new in jquery I desperately need some help in running this code.I am trying to create a fade in-fade out image banner with 4 images within div tag, with the help of a function fadingbanner() which calls itself recursively and is initiated by a settimeout function.But for some reason its not working.Please help....
<HTML>
<HEAD>
<script type= "text/javascript" src="C:\Documents and Settings\A\Desktop\jquery-1.9.1.js"></script>
<SCRIPT>
<div>
<img src = "C:\Documents and Settings\A\Desktop\web_files\temp1.jpg" id = "i1">
<img src = "C:\Documents and Settings\A\Desktop\web_files\temp2.jpg" id = "i2">
<img src = "C:\Documents and Settings\A\Desktop\web_files\temp3.jpg" id = "i3">
<img src = "C:\Documents and Settings\A\Desktop\web_files\temp4.jpg" id = "i4">
</div>
function fadingbanner()
{
$(document).ready(function(){
$("#i1").fadeOut(2000,function(){
$("#i2").fadeIn(2000,function(){
$("#i2").fadeOut(2000,function(){
$("#i3").fadeIn(2000,function(){
$("#i3").fadeout(2000,function(){
$("#i4").fadeIn(2000,function(){
$("#i4").fadeout(2000,function(){
fadingbanner();
});
});
});
});
});
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<IMG NAME = "bannerimage" src = "C:\Documents and Settings\A\Desktop\web_files\temp1.jpg" height = "200" width = "600" onload = "settimeout("fadingbanner()",1000)">
</BODY>
</HTML>
Take out the function and it should work ok. It is only defining a function and never running it. If it did run it, all it would do is schedule the code to run when the document finishes loading.
You also want to hide all but the first picture at the start.
So it should be like:
$(document).ready(function(){
$("#i2, #i3, #i4").hide();
$("#i1").fadeOut(2000,function(){
... all that other stuff
});
});
Here is a fiddle showing it: http://jsfiddle.net/ePBkX/1/
I borrowed the pictures there from the fiddle attached to this, which you might want to read: jQuery fade out then fade in

Problems with mouse events on newly created CKEditor instance

I'm trying to create a create a new CKEditor ver4 instance in response to the user clicking on an element. Due to the nature of the application, I can not use the "autoInline" feature as outlined in the CKEditor Sample. While the sample below does in fact create an editor instance, that instance has a significant problem. Inline instances are supposed to disappear when the user clicks away from them. In this example however, the user must first click away, click back into the instance, and then click away again. How can I prevent this?
<!doctype html>
<html>
<head>
<script src="jspath/ckeditor.js"></script>
<script>
var editor = null;
CKEDITOR.disableAutoInline = true;
function init() {
var e2 = document.getElementById("element2");
e2.addEventListener("click", function () {
if(!editor) {
editor = CKEDITOR.inline(e2);
editor.on('instanceReady', function () {
console.log("instanceReady")
console.log(editor.focusManager.hasFocus);
});
editor.on('focus', function() {
console.log("focus");
})
editor.on('blur', function() {
console.log("blur");
editor.destroy();
editor = null;
})
}
})
}
</script>
</head>
<body onload="init()">
<div tabindex="0" id="element2" style="background-color: yellow;" contentEditable = true>Element 2</div>
</body>
</html>
Despite the fact that editor.focusManager.hasFocus was true, the editor's element did not in fact have focus. Perhaps this is a bug? Anyway, adding editor.focus(); to the instanceReady function resolved the issue.

Resources