I want to load a *.txt file and insert the content into a div.
Here my code:
js:
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
success : function (data) {
$(".text").html(data);
}
});
});
});
html:
<div class="button">
<input type="button" id="lesen" value="Lesen!" />
</div>
<div class="text">
Lorem Ipsum <br />
</div>
txt:
im done
If i click on the button firebug report following error:
Syntax-Error
im done
I donĀ“t know what to do :-(
You need to add a dataType - http://api.jquery.com/jQuery.ajax/
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
});
});
You could use jQuery.load(): http://api.jquery.com/load/
Like this:
$(".text").load("helloworld.txt");
The .load("file.txt") is much easier. Which works but even if testing, you won't get results from a localdrive, you'll need an actual http server. The invisible error is an XMLHttpRequest error.
You can use jQuery load method to get the contents and insert into an element.
Try this:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
e.g:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
Try
$(".text").text(data);
Or to convert the data received to a string.
<script type="text/javascript">
$("#textFileID").html("Loading...").load("URL TEXT");
</script>
<div id="textFileID"></div>
Related
I am working on a 'Wikipedia Viewer' project, where you enter a search term and see a list of Wikipedia search results, but it is far from complete.
Until now I have just written the code to display the first search term. But it doesn't work.
My HTML:
<div class="container-fluid">
<div class="searchAndButtons">
<input type="text" id="search">
<button class="btn" id="searchBut">Search</button>
<form action="https://en.wikipedia.org/wiki/Special:Random"><button class="btn">Random Wiki Article</button>
</form>
</div>
<div class="searchResults">
</div>
</div>
My CSS:
.container-fluid{
padding:5%;
}
.searchAndButtons{
text-align:center;
}
My Javascript:
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("#search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Where am I going wrong? When I run the code in Codepen and check the console, it shows an error "TypeError: document.getElementById(...) is null".
My project on codepen - link
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Update your JS code with this. id gets value by 'search' not '#search'
UPDATE: To add headers you can do the following
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1', //your request URL
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo'); //your header key and value
}
});
});
I'm using jQuery form plugin to send ajax requests. Which you can find on below url
http://malsup.com/jquery/form/
This is my jQuery code
$(document).ready(function()
{
$('#SubmitForm').on('submit', function(e)
{
e.preventDefault();
$('#submitButton').attr('disabled', '');
$(this).ajaxSubmit({
target: '#output',
success: afterSuccess //call function after success
});
});
});
function afterSuccess()
{
$('#submitButton').removeAttr('disabled'); //enable submit button
}
This code is displaying out put on the div id output and each time i submitted code will remove the old out put and display the new one. What i want to do is, keep the old out and display the new out put on top of the old output. Can someone tell me how to do this.
What you could do, is alter your afterSuccess method a little bit. What I did was:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
The whole fiddle is available here
The whole code of javascript:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
$(document).ready(function()
{
$('#submitButton').click(function(e)
{
$('#submitButton').prop('disabled', true);
$('#SubmitForm').ajaxSubmit({
data: {
html: "<p>Text echoed back to request</p>",
delay: 1
},
success: afterSuccess,
url: '/echo/html/'
});
});
});
and of course assuming following html structure
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<body>
<form id="SubmitForm" method="POST">
<input type="button" id="submitButton" value="submit"/>
</form>
<div id="output">
test
</div>
</body>
I have a problem with Jquery. I have an xml file that I use to load a list of video information. On each element in the XML I need to see an effect with jquery (fadetoggle etc).
The problem is that it does not work, I show you the code
<script type="text/javascript">
$(document).ready(function(){
$.ajax({ type:"GET", url:"menu.xml", dataType:"xml",
success: function(xml){
$(xml).find("food").each(function(){
var nome = $(this).find('nome').text();
var ingredienti = $(this).find('ingredienti').text();
$("#listapizza").append("<li class=\"list\"><a class=\"acla\" href=\"#\">"+nome+"</a> <div class=\"divHide\" style=\"display:none\">("+ingredienti+")</div></li>");
});
},
error: function(request, error, tipo_errore) { alert(error+': '+ tipo_errore); }
});
$(".acla").click(function(){
$(this).next().fadeToggle(1500);
});
});
</script>
This is a container of list
<ul id="listapizza">
</ul>
I can not understand why it does not work
Tnx
Use event-delegation since it is dynamically appended.
$("#listapizza").on("click", ".acla", function(){
$(this).next().fadeToggle(1500);
});
I'm new to jquery and javascript and have no idea how to solve this problem: I have a simply jquery chat and there is a div with the id 'show_messages' in which I load all the messages from my ajax request. All works fine, the only problem ist, that the div for show messages gets longer and longer and I have absolutely no idea how to implement a scrollbar. I tried to use the jquery scroll function, but I hasn't worked and I don't know how to use it right. How can I make a simple scrollbar like in the facebook messenger or in similar messengers.
My Code:
<div id="message_dialog" class="message_box">
<div id="show_messages"></div>
<div id="feedback"></div>
<form action="#" method="post" id="message_form">
<label>Say something:</label>
<textarea id="message"></textarea>
<input type="submit" id="send_message" value="Send Message">
</form>
</div>
...
$(document).ready(function(){
$('#start_conversation').click(function() {
$('#message_dialog').dialog();
var interval = setInterval(function() {
$.ajax({
type : "POST",
url: 'get_messages.php',
success: function(data) {
$('#show_messages').html(data);
}
});
}, 1000);
return false;
});
});
$('#message_form').submit(function() {
var username = ...
var message = ...
$.ajax({
type : "POST",
url: 'send_message.php',
data: { 'username' : username, 'message' : message },
success: function(data) {
$('#feedback').html(data);
$('#feedback').fadeIn('slow', function() {
$('#feedback').fadeOut(6000);
});
$('#message').val('');
}
});
return false;
});
Setting a max-height property and overflow-y to auto doesn't solve the problem ?
#show_messages{
max-height:200px;
overflow-y:auto;
}
Let's say for example that a message is displayed within his proper div, you can scroll to the last message by using this function.
$("#show_messages").scrollTop($("#show_messages").children('div').last().offset().top);
I suggest to use AlternateScroll jquery plugin:
http://www.dynamicdrive.com/dynamicindex11/facescroll/
It's very useful and you can easily customize it. Hope this helps.
I already tried several methods getting my xml-script parsed in java, but i can't figure it out!
I have 2 files.
mysql_get.php is returning an XML script if it is called.
post_alert.html is fetching the XML script from mysql_get.php over jQuery $.post(..) as shown below:
function init2() {
var response;
$.post("mysql_get.php", function (data) {
response = data;
alert(response)
});
var xml;
xml = $.parseXML(response);
alert($(response).find("item").each(function () {
$(this).attr("id")
}));
}
After hit a button which call init2(), i get the response message in xml style as i can see by the alert popup.
<?xml version="1.0" encoding="uft-8"?>
<root>
<collection collection="locationPoint">
<item id="1">
<latitude>23.4442</latitude>
<longitude>51.2341</longitude>
</item>
<item id="2">
<latitude>2849.24</latitude>
<longitude>213.132</longitude>
</item>
</collection>
But the alert doesn't popup "1" in addition as I wished for correct parsing.
What am I doing wrong?
Here are a couple of things:
Line 1 of you xml file should read UTF-8 not UFT-8
Line 2 should be deleted, else make sure you have a closing tag, invalid xml
Then here is a little example that I hope helps:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
</head>
<body>
<div id="dc"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'mysql_get.php',
type: 'post',
dataType: 'xml',
success: function(data) {
$(data).find('item').each(function () {
$('#dc').append($(this).attr('id') + '<br/>')
});
},
error: function(data) {
$('#dc').html('error');
}
});
});
</script>
</html>
The A in AJAX stands for asynchronous. The code after $.post(..) is executed right after $.post is called, regardless of the response state.
You have to move the var xml..-code inside the $.post call.
Also, .each() only loops through the elements, without returning the IDs. Use .map() to create an object consisting of the ids, and .toArray() to get an array representation of it.
function init2() {
$.post("mysql_get.php", function(data) {
var response = data;
var xml = $($.parseXML(response));
alert(response.find("item").map(function () {
return $(this).attr("id")
}).toArray() );
});
}
Take a look at XML manipulation with jQuery