Add loaded text to other loaded text - javascript

In Javascript, to add text to an already existing div I would use
document.getElementById("container").innerHTML = document.getElementById("container").innerHTML + "Text";
So that the text that is already present in the div wouldn't be deleted and to be able to reset what is written in the div by just using:
document.getElementById("container").innerHTML = "Text";
But, since I'm using jquery to load the text from a txt file with
$( "#container" ).load( "text.txt" );
That doesn't seem possible.
I'm not a big expert on neither JS or Jquery, but is there a way to mix the two to still be able to reset the text in a div or add text to it, while still fetching that text from an external file?
Hope I've been clear enough in explaining what I'm trying to do

Try using AJAX to fetch your data but not populate it:
$.ajax({
url: 'text.txt',
success: function(text){
document.getElementById("container").innerHTML += text;
}
});
Ajax is a lot more full featured - it's the 'harder' cousin of load(), so you can also add an error catcher (as well as a raft of other things):
$.ajax({
url: 'text.txt',
success: function(text){
document.getElementById("container").innerHTML += text;
},
error: function(e){
document.getElementById("container").innerHTML += 'Data could not be loaded! (' + e.statusText + ')';
}
});
You can learn more about AJAX at jQuery docs: http://api.jquery.com/jquery.ajax/

First of all:
You run the risk of loading a file, which may or may not be available. Meaning you could get a file load error. In order to stick with jQuery I would leverage AJAX to load the file like so:
JQuery code:
$(document).ready(function() {
$.ajax({
url : "text.txt",
dataType: "text",
success: function (data) {
data.appendTo("#container")
},
error: function(e){
// Show some error, for example:
alert("Data failed to load from text.txt file")
}
});
});
I believe that appendTo will be a much simpler version of what you've tried to accomplish via document.getElementById("container").innerHTML in order to replace the text. Give it a try and modify this to work exactly as you like. Let me know if you have any questions about it.
To make it clear to you, JQuery is an extension of the existing JavaScript language. Meaning, you can always use your JavaScript within your perceived JQuery code. You can learn how to use the strengths of JQuery to support your JavaScript code with added functionality, a great example of one is the AJAX implementation of file loading you see here. To learn more visit: Learn JQuery.

Related

Get content of h1 from external page with jquery load()

I have a mediawiki where I would like to get the content from into another page. So I have:
http://bourlo.net/wiki/index.php/Lunet
And would like to display parts of this in a bootstrap modal on another page:
http://bourlo.net/stack/
The heading of the wiki page is retrieved by:
$("#wikiModal h4.modal-title")
.load( "http://bourlo.net/wiki/index.php/Lunet .firstHeading");
That works, yeah! But I don't want the complete
<h1 id="firstHeading" class="firstHeading" lang="nl-informal">Lunet</h1>
In the <h4> from the modal, but only the content >>> Lunet
How can I do this?
You need to use other ajax method instead. For the example:
$.get("http://bourlo.net/wiki/index.php/Lunet", function(html){
var txt = $(html).find('.firstHeading').text();
$("#wikiModal h4.modal-title").text(txt);
});
So you want to extract the text only from your ajax returned text:
$.get( "http://bourlo.net/wiki/index.php/Lunet", function(html){
$("#wikiModal h4.modal-title").text( $(html).find('.firstHeading').text() );
});
That's because you with .load(), you cannot manipulate the responseText before inserting into the DOM. Let's acknowledge that you can actually do something like this:
$h4 = $("#wikiModal h4.modal-title")
$h4
.load( "http://bourlo.net/wiki/index.php/Lunet #firstHeading", function(){
$h4.find('#firstHeading').replaceWith(function(){
return $(this).text();
});
});
This is definitely more clumsy. But I bothered to put this out because, once in a while, you're constrained to use the .load version instead of the .get version by factors beyond your control.

How to format webpage before it is loaded javascript

Ok. I am making a website on github using html and javascript. Earlier, I was using a template to make simple, formatted webpages. I got it to work, but it has an annoying bug: the unformatted webpage shows up before the formatted one. I am using the latest version of jquery (2.1.4) hosted from google and the javascript below:
var heading = document.getElementById("heading").innerHTML;
var pghead = document.getElementById("pghead").innerHTML;
var pgtext = document.getElementById("pgtext").innerHTML;
var template = function () {
var tmp = null;
$.ajax({
'async': false,
'dataType': 'html',
'url': "https://jediguy13.github.io/template.html",
'success': function (data) {
tmp = data;
}
});
return tmp.split("derp");
}();
document.write(template[0] + heading + template[1] + pghead + template[2] + pgtext + template[3]);
document.getElementById("heading").innerHTML = "";
document.getElementById("pghead").innerHTML = "";
document.getElementById("pgtext").innerHTML = "";
And here's a sample webpage:
<div id="heading">Test</div>
<div id="pghead">Test</div>
<div id="pgtext">This is some text in the main body of the webpage</div>
As you can see from the 'async': false. line, Jquery is requesting the template webpage at the same time as the main thread. However, there is always a slight delay in the formatting. I'm betting it is because the document.write is called near the end. What is a better way to get the browser to display just the formatted page?
Example page: website
Don't use document.write(). Ever. If you have an HTML snippet, just attach it to the desired node like this:
$("body").html(template[0] + ...);
If the page is originally empty and all the content is loaded with AJAX, then you'll see a white page that then is filled with your code.
In your case it will NOT be empty as I can guess, so you have to clear the HTML immediately after you fetch it:
heading = $("#heading").html();
$("#heading").html("");
This will minimize the original exposure of the HTML.
At this point you may want to fade it in slowly, like this:
$("body").hide();
// ... make AJAX call and attach it as shown above
$("body").fadeIn();
The fadeIn() is a touch of class you might as well replace with show().
Make the AJAX call asynchronous and put all of this into the AJAX success() method.
This is all together in a complete rewrite. Just copy+paste and tell me if it's working:
var heading, pghead, pgtext;
$("body").hide();
heading = $("#heading").html();
pghead = $("#pghead").html();
pgtext = $("#pgtext").html();
$("#heading").html("");
$("#pghead").html("");
$("#pgtext").html("");
$.ajax({
'async': true,
'dataType': 'html',
'url': "https://jediguy13.github.io/template.html",
'success': function (data) {
template = data.split("derp");
$("body").html(template[0] + heading + template[1] + pghead + template[2] + pgtext + template[3]);
$("body").fadeIn();
}
});
Okay, so first off I'm going to say you shouldn't rely on JS to format your entire page unless you're hosting a single-page application, and even then... probably not the entire page.
To answer your question, the only way to not show the unformatted page is to hide your content until the page loads. Give your body tag or container style='display:none;' and then when your JS has finished executing, show the content with by calling something like $('body').show().
one of my favourite tricks is to place a loader div and keep the content hidden and the loader visible until all JS based layout changes are completed. provided you have the luxury of using Jquery (or CSS3) you can use an easing effect on the opacity to give it a much better feel.

Parsing returned HTML from jQuery AJAX request

What I'm trying to do seems simple: get an HTML page through $.ajax() and pull out a value from it.
$(function () {
$.ajax({
url: "/echo/html",
dataType: "html",
success: function (data) {
$('#data').text(data);
$('#wtf').html($(data).find('#link').text());
},
data: {
html: '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a id="link">content<\/a><\/li><\/ul><\/body><\/html>'
}
});
});
The problem is that jQuery refuses to parse the returned HTML.
The fiddle I'm play with this in isn't working in the mean time, so there's little else I can do to provide a working example.
UPDATE: My new fiddle is working fine, but it seems the problem is that in my actual project I'm trying to parse a large, complex bit of HTML. Is this a known problem?
Your code works fine. You just aren't using jsFiddle's API correctly. Check the docs for /echo/html/ (http://doc.jsfiddle.net/use/echo.html#html):
URL: /echo/html/
Data has to be provided via POST
So, you need to update your AJAX call to use POST. Also the trailing slash is needed.
$(function () {
$.ajax({
url: "/echo/html/",
type: "post",
dataType: "html",
success: function (data) {
$('#data').text(data);
$('#wtf').html($(data).find('#link').text());
},
data: {
html: '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a id="link">content<\/a><\/li><\/ul><\/body><\/html>'
}
});
});
DEMO: http://jsfiddle.net/hcrM8/6/
If you would like to parse it, jquery has a nifty trick :)
ParsedElements = $(htmlToParse);
Console.log(ParsedElements);
You now have DOM elements you can traverse without placing them in the body of the document.
jQuery.parseHTML()
http://api.jquery.com/jQuery.parseHTML/
str = "hello, <b>my name is</b> jQuery.",
html = $.parseHTML( str ),
nodeNames = [];
// Gather the parsed HTML's node names
$.each( html, function( i, el ) {
nodeNames[ i ] = "<li>" + el.nodeName + "</li>";
});
Some thing is wrong with your ajax on fiddle
http://jsfiddle.net/hcrM8/5/
var html= '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a class="disabled" id="link">content<\/a><\/li><\/ul><\/body><\/html>';
h = $.parseHTML(html);
$('#data').text(h);
$('#wtf').html($(h).find('#link').text());
Why don't you just use the load method?
$( "#wtf" ).load( "/echo/html #link" );
Or, here's your fiddle fixed and working:
http://jsfiddle.net/hcrM8/4/
I had the same problem and i fixed encapsulating requested html code into just one container element.
Bad Example:
Linkname
<p>Hello world</p>
Jquery couldnt convert this to element, because it wishes to convert a single element tree. But those are not having a container. Following example should work:
Right Example:
<div>
Linkname
<p>Hello world</p>
</div>
All answers do not point to the real problem, jQuery seems to ignore the head and body tag and creates an array of nodes. What you normally want is, extract the body and parse it.
Take a look at this helpful answer, I do not want to copy his work: https://stackoverflow.com/a/12848798/2590616.
I am facing the same problem, and it is not because you are doing something wrong.
it's because the "link" tag is not supposed to have any innerHTML returned, it's explicitly excluded in jquery, you will find some where this line:
rnoInnerhtml = /<(?:script|style|link)/i,
This tag in HTML is supposed to link to external style sheet.

jQuery .ajax() is breaking TinyMCE 3.5.6

I've built a simple CMS with multiple layers of jQuery.ajax(), like so:
function navto(destination, pageToEdit, insertInto) {
// use JQuery's ajax method to control main navigation
if (pageToEdit == "undefined") {
var request = $.ajax({
url: destination
});
} else {
var request = $.ajax({
type: "POST",
url: destination,
data: pageToEdit
});
}
request.done(function(msg) {
if (insertInto) { $(insertInto).html( msg ); }
else { $("#mana_content").html( msg ); }
//alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( textStatus + ". This page could not be found." );
});
}
For example, index.php uses <li class="child" onclick="navto('inc/edit_pages.php');">Edit Pages</li> to load edit_pages.php into <div id="content"></div>
edit_pages.php uses $(document).on("click", "a.editPage", function(e) { load_page_for_edit(e); return false; }); (where load_page_for_edit() gathers and readies the information to be sent to the navto() function) to send something like edit_page.php?t=template.php&c=contentID
edit_page.php uses those values to look up the info it needs in the corresponding databases and then outputs something like template.php&c=content into its own <div id="page_to_edit"></div>... again, with another navto().
A user can then click on $('.edit_text') elements to un-hide a div with a TinyMCE textarea (called $('#editor')) inside.
The content is captured by var content = $('.edit_text').html()
Here's the problem: when I try to load the content variable into the TinyMCE textarea -- $('#editor').html(content); -- the textarea does not receive it. I can immediately follow this up with alert($('#mana_editor').html());, which outputs the correct content, but with HTML characters made safe (eg, <p> becomes <p&rt;). However, the content does not load into TinyMCE.
I'm guessing that I have an .ajax scope issue? That perhaps jQuery is trying to $('#editor').html(content); to a non-existent #editor on the template.php (recall that the #editor is on edit_page.php)? Any good resources for figuring out multiple layers of .ajax?
Tid-bits, clues, and things I've tried:
All of my jQuery functions are in a functions.js file, except for the TinyMCE init, which is at the end of edit_page.php.
Only index.php links to functions.js
I'm using TinyMCE 3.5.6, jQuery plugin package and jQuery 1.7.2.
I've attempted TinyMCE's pseudo-selector as well ($('textarea:tinymce') instead of $('#editor')), which throws an error in Firebug: "Error: Syntax error, unrecognized expression: tinymce" in jq.min.js (line 4).
After a user makes their changes in TinyMCE, an update button will load the new content into the $('.edit_text') that was clicked. Instead of loading what I type in, it loads the "safe" HTML mentioned above -- as though TinyMCE was bypassed entirely.
If I don't use the whole CMS and start by manually typing `get_page.php?t=template&c=content' into FireFox it works fine.
If I don't load TinyMCE, the jQuery will load the content into the textarea
This guy might be on to something... seems similar, but I'm not sure what his head.js contains, how to implement head.ready();, or if his problem is the same as mine.
This is my first project using Ajax, so I have a lot to learn. Any insights/suggested reading/solutions would be greatly appreciated!
Here's the problem: when I try to load the content variable into the
TinyMCE textarea -- $('#editor').html(content); -- the textarea does
not receive it. I can immediately follow this up with
alert($('#mana_editor').html());, which outputs the correct content,
but with HTML characters made safe (eg, becomes <p&rt;).
However, the content does not load into TinyMCE.
You need to know that tinymce is not equal your textarea.
On initialization of an editor instance the former textarea gets hidden and tinymce creates a contenteditable iframe - the tinymce editor. The former textarea gets updated with the actual content of the editor from time to time (on special events).
So what i think what you want to achieve is to write your content into the editor. To do this addressing the textarea using jQuery won't work (as you found put yourself).
You need to employ the javascript tinymce API here:
tinymce.get('your_former_textarea_id_needs_to_be_here').setContent(content);

How to open an html page in and html div?

The question might be a little misleading as I don't want to know how to open a html document in a div ,but I asked the question as I am currently facing a problem where I can't replace the html file which I have already placed in a div
I have already placed a html file in a div using ajax like this:
$.ajax({
url: 'calender.aspx',//this is html.aspx file
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);//mainBar is the div
}
});
this file gets placed on page load i.e document.ready function ,till here everything is fine.....my trouble starts when I want to replace the file,what I do is call a javascript function say replaceFile() on button click and write the same code to replace the file (changing the url of course)
like this
function replaceFile()
{
$.ajax({
url: 'Another.aspx',
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);
}
});
}
but this doesn't work,please help me out!
I guess your binding is not working when you try to click on the content you loaded via ajax . So you might want to change the binding of onclick from
$("#someButtonId").click(function(){
replaceFile();
});
to
$(document).on("click","#someButtonId",function(){
replaceFile();
});
jQuery on works with current and future elements.
with this function you will load the page into the element named result
.load( url , data, complete(responseText, textStatus, XMLHttpRequest)] )
function replaceFile(url)
{
$('#result').load(url, function() {
alert('Load was performed.');
});
}
replaceFile('htmlfile.html');
You can load this in Firebug and set a break point at $(".mainBar").html(data); to make sure it's being called. You don't have a failure handler, so it's possible that it's actually receiving an HTTP failure code, not a success code.
I'd also look at the network traffic under the Net tab to see what the request/response looks like. That's an easy way to find out what is really going on with most AJAX calls. IE9 has similar developer tools if you want to use it and not Firefox or Chrome.

Categories

Resources