I am a beginner. The problem I am dealing with is probably very simple to solve ;) I am working on a web page where the text content is loaded from external html files into the div. This is done when a user clicks on a menu item.
This is my code html :
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/menu.css">
<script type="text/javascript" src="js/js.js"></script>
</head>
<body>
<div>
<ul>
<li><a id="teachers" href="#" name="teachers" onclick="getdata()">
Teachers
</li>
</ul>
</div>
<div id="page" name="" >
bla bla bla ...
</div>
</body>
</html>
And this is my code ajax:
var _xhr;
function getdata(){
_xhr= new XMLHttpRequest();
_xhr.onreadystatechange=callback;
_xhr.open("POST", "teachers.html", true);
_xhr.send();
function callback(){
var _target = document.getElementById("page");
_target.innerHTML=_xhr.responseText;
}
}
I would like to load the html file (teachers.html) into the div (id="page") when I click on the link (Teachers)
Please could someone help me.
Thanks in advance.
try changing POST to GET and see if that works.
for this case i recommend to user jQuery Load function. its easy to use and fit your needs. you can find more in the following link: http://api.jquery.com/load/
Its pretty hard to know if you don't tell us what happened. I´ve figure out (maybe) a problem
Try Change your code to
function getdata(){
function callback(){
var _target = document.getElementById("page");
_target.innerHTML=_xhr.responseText;
}
_xhr= new XMLHttpRequest();
_xhr.onreadystatechange=callback;
_xhr.open("POST", "teachers.html", true);
_xhr.send();
}
How about using an ajax call?
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
Documentation: http://api.jquery.com/jquery.get/
Have you tried bringing the var _xhr; inside the function?
i tried the below.. it worked
function getdata(){
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("get","techers.html",false);
xmlhttp.send();
document.getElementById("page").innerHTML=xmlhttp.responseText;
}
Related
I'm really new at this and I need a random button on my page that would show a new line of information in a div every time someone click on the random button. I was also wondering if there is over 800 lines is it possible to put it in an outside file as txt or html.
Here is what I got so far and well it doesn't work and I'm getting confuse... Please help
<script type="text/javascript" src="jquery-2.2.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#text').hide();
$('a#random').click(function(){
$('#text').toggle();
})
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
document.getElementById('#text').innerHTML=textarray[rannum];
}
var textarray = [
"Hello",
"How are you",
"Good Bye"
];
$("#text").load()
})
</script>
<body>
<div id="text">Line to Show</div>
RANDOM
</body>
Uh. Pretty much this:
$('a#random').click(function(){
$('#text').toggle();
RndText(); //you're good
});
Although I will point out that RndText() uses document.getElementById when it could use $("#text") instead. (there's a .html() method that will write the value instead of the .innerHTML property).
document.getElementById is also not currently working because you used "#text" instead of "text", jQuery uses CSS selectors, getElementById does not.
Add execution of RndText when you clicks on Random button.
$('a#random').click(function(){
$('#text').show();
RndText();
})
This will give you a button and you can run this code by clicking the button below. However, I did not quite understand you second part of the question: 800 lines in separate file, what do you wanna do with it? Tell me so that I can helo you further...
Editted:
<?php
$data = file_get_contents('demo.txt');
$lines= split("\n",$data);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
var textarray = <?php echo json_encode($lines); ?>;
function RndText() {
var rannum= Math.floor(Math.random()*textarray.length);
$('#text').text(textarray[rannum]);
console.log(textarray[rannum]+" "+rannum+" "+textarray.length);
}
$(document).ready(function(){
$('#text').hide();
$('#random').click(function(){
$('#text').show();
RndText();
});
});
</script>
<body>
<div id="text"></div>
<button id="random">RANDOM</button>
</body>
I want to load some contents via ajax when click on a tabbar item in jquery mobile.
How can i do this?
<div data-role="tabs" id="tabs">
<div data-role="navbar">
<ul>
<li>Discover</li>
<li>My-chats</li>
</ul>
</div>
<div id="one" class="ui-body-d ui-content">
<div data-role="fieldcontain">
<!--load data via ajax-->
</div>
</div>
<div id="two">
<!--load data via ajax-->
</div>
</div>
When click on discover tab i want to load some data through ajax to that tab.
How to do this?
please help me.
Hope helps you!
(function(window, $) {
function TabCtrl() {
var self = this;
self.loadData = function(url) {
return $
.get(url)
;
};
$('[data-ajax]').click(function(event) {
event.preventDefault();
var tab = $(this).attr('href').replace('#', '');
self
.loadData(tab)
.then(
function(success) {},
function(error) {}
);
});
}
$(document).ready(TabCtrl);
})(window, window.jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#my-custom-tab" data-ajax>Load Me</a>
Try this. If you already using jQuery then ignore the first line.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
// Make sure all DOM is loaded
$(document).ready(function(){
// Fired when you click the link
$('#discover-tab').click(function(e){
// Prevent the link from continuing it's normal action
e.preventDefault();
// Fetch the result of a URL
$.get( "ajax/test.html", function( data ) {
// Fill the DIV with ID of 'one' with that result
$( "#one" ).html( data );
});
});
});
</script>
bind it to a javascript function which executes the ajax call like this:
Discover
javascript function:
function ajaxcallfunction(){
window.location.href = window.location.href + "#one";
//Enter your ajax call here
}
I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.
<html>
<head>
<title>textbox</title>
<script type="text/javascript">
function readBOX() {
var txtinput = document.getElementById('txtinput').value;
document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
}
</script>
</head>
<body>
<p> Type</p>
<input type="text" id="txtinput" />
<input id="open" type="button" value="READ" onClick="readBOX()" />
<form>
<textarea name="text" rows="20" cols="70">loaded text here</textarea>
</form>
</body>
</html>
You have to use something like its posted in this Answer
jQuery
$(document).ready(function() {
$("#open").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$("#text").text(data);
}
});
});
});
Read more on the jQuery Documentation of .ajax()
Non jQuery
I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia
Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object
Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
This is how I load text into a textarea
Main.css
.textbox{
font-size: 12px;
float : left;
height : 197px;
width : 650px; }
Default.html
<!DOCTYPE html>
<html>
<head>
<!-- Charactor set allowed to use -->
<meta charset="utf-8"/>
<title>Text from .txt file to TextArea</title>
<!-- External stylesheet -->
<link rel="stylesheet" href="main.css" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea class="textbox" id="Brief" readonly></textarea>
<script> $( "#Brief" ).load( "text.txt" ); </script>
</body>
</html>
google textarea to find format of text area
One of the easiest way is to request the server to return the pre-filled textarea
(Here's an example using PHP):
<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>
Note: Something similar can be done with any server-side scripting language.
In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.
Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):
Pure JS:
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
function readBOX() {
function reqListener () {
document.forms[0].text.value = this.responseText;
}
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", filePath, true);
oReq.send();
}
But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:
jQuery:
function readBOX() {
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
$.ajax({
url: filePath
}).done(function(data){
document.forms[0].text.value = data;
});
}
Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.
Hope this helps :)
window.addEventListener('DOMContentLoaded', (e) => {
let input = document.getElementById('input');
// load default.txt into input box
try {
let fileToLoad = './default.txt';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', fileToLoad, false);
xmlhttp.send();
input.innerHTML = xmlhttp.responseText;
} catch(DOMException) {
input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
}
});
Good day, friends. I can't make zeroclipboard working with my page. In HTML page I have:
<script type="text/javascript" src="ZeroClipboard.js"></script> //Script was loaded successfully.
...
<button id="copy_clipboard">Test me</button>
<script>
ZeroClipboard.setMoviePath('http://olymp/ZeroClipboard.swf'); //Path correct. It's local php server
var clip = new ZeroClipboard.Client();
clip.setText('test');
clip.glue('copy_clipboard');
</script>
This return me an error:
ZeroClipboard.setMoviePath is not a function
After deleting
ZeroClipboard.setMoviePath('http://olymp/ZeroClipboard.swf');
I got an error:
ZeroClipboard.Client is not a constructor
Hope this would help a little bit:
Try using:
ZeroClipboard.setDefaults({moviePath: 'http://olymp/ZeroClipboard.swf'});
And also:
var clip = new ZeroClipboard();
For your another question, try using :
clip.on('dataRequested', function(client, args){
clip.setText("YOUR TEXT HERE");
});
instead of using clip.setText alone :)
sometimes you need to init the zeroclipboard client on document ready
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/ZeroClipboard.min.js"></script>
<script>
$(document).ready(function() {
var client = new ZeroClipboard($('#buttonId'), {
moviePath : 'util/ZeroClipboard.swf'
});
});
</script>
<input type="button" id="buttonId" data-clipboard-target="inputId" />
<input type="text" id="inputId" />
will copy in cplipboard the contents of the input text, for me it worked also for localhost
I am using zend framework on windows. I want to implement ajax in my project first time. I searched for help and created a very simple ajax functionality.
IndexController.php
public function indexAction() {
}
public function oneAction() {
}
public function twoAction() {
}
index.phtml
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/AJAX.js"></script>
<a href='http://practice.dev/index/one' class='one'>One</a>
<a href='http://practice.dev/index/two' class='two'>Two</a>
<br /><br />
<div id="one">one.phtml content comes here</div>
<div id="two">two.phtml content comes here</div>
AJAX.js
jQuery(document).ready(function(){
jQuery('.one').click(loadOne);
jQuery('.two').click(loadTwo);
});
function loadOne(event) {
event.preventDefault();
jQuery.ajax({
url: '/index/one',
success: function( data ) {
jQuery('#one').html(data);
}
});
}
function loadTwo(event) {
event.preventDefault();
jQuery.ajax({
url: '/index/two',
success: function( data ){
jQuery('#two').html(data);
}
});
}
Above code is working and loading data of one.phtml and two.phtml in 'one' and 'two' DIVs respectively when its link is clicked. You can see that I have to create separate jquery function for each link and also have to add new class for each link tag.
What I want to do ?:
I want to use only one jquery function for all AJAX requests and don't want to hard code url and success attributes in that function.
When I add "AJAX" class to any link tag then it should load content using AJAX.
Thanks.
for simple loading of data in divs i would use the load method
HTML
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/AJAX.js"></script>
One
Two
<br /><br />
<div id="one">one.phtml content comes here</div>
<div id="two">two.phtml content comes here</div>
JS
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event){
event.preventDefault();
var target = '#' + jQuery(this).attr('rel');
var href = jQuery(this).attr('href');
jQuery( target ).load( href );
});
});
Use a single class to identify all links that should use ajax calls instead of their normal use. And add a rel attribute to those links that will contain the id of the container div..
Simple and Nice. No Jquery required. Check this out:
Bjax
Usage:
<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />
Finally, include this in the HEAD of your html:
$('a').bjax();
For more settings, checkout demo here:
Bjax Demo
Maybe this:
function loadData(url, callback) {
jQuery.ajax({url: url, success: callback});
}
loadData('/index/one', function( data ) {
jQuery('#one').html(data);
})
loadData('/index/two', function( data ) {
jQuery('#two').html(data);
})
To make this even more compact you could define the same callback for both and then have the handler decide which element the response data should be written to.
Compact version:
$(function(){
$('.one').click(loadOne);
$('.two').click(loadTwo);
});
function loadOne(event) {
event.preventDefault();
$('#one').load('/index/one');
}
function loadTwo(event) {
event.preventDefault();
$('#two').load('/index/two');
}