issue getting elements from XML [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to retrieve some data from my XML file and I want to insert it inside an unordered list. This is how my Ajax code looks like:
var request;
//For backward compatibility
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET','data.xml');
request.onreadystatechange = function(){
// if((request.readyState === 4) && (request.Status===200)){
console.log(request.responseXML);
var items = request.responseXML.getElementByTagName('name');
alert('hello');
var ouptput = '<ul>';
for (var i = 0; i >= items.length; i++) {
output += '<li>' + items[i].firstChild.nodeValue + '</li>';
}
output += '</ul>';
document.getElementById('update').innerHTML = output;
//}
}
request.send();
This code doesn't read my XML file, it gives me an error saying 'Response XML is null(Type error)' I tried to use this in a server(localhost) but it didn't work either.
Can someone please give me an idea how to solve this? Thank you.

i used jQuery to solve this... this is how i did this.....
<script>
$(document).ready(function(){
$(".update").append("<ul></ul>");
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: function(xml){
$(xml).find('book').each(function(){
var sTitle = $(this).find('title').text();
var sprice = $(this).find('price').text();
$("<li></li>").html(sTitle + ", " + sprice).appendTo(".update ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>

Related

How to reload number without refresh [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My .php is reading some variables from pos.txt and I need to show them live, without refreshing the page. I've used <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">, but it's annoying. I've read something about ajax, but I can't really understand how it works.
$line = file_get_contents('pos.txt');
list($date, $time, $x, $y, $z) = explode(' ', $line);
For this you have to use AJAX. You have to learn this http://www.w3schools.com/ajax/default.asp.
Once you learn it you will use it allways.
Just make a ajax call from your display page to your php file.
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && xmlhttp.status==200)
{
var response = ajax.responseText;
// Here is your response
}
}
ajax.open("POST", "request/path/response.php");
ajax.send(any_data);
Details
http://api.jquery.com/jquery.ajax/
$.ajax({
url: "[_YOUR_URL_]/post.txt",
}).done(function(data) {
$("#some_id").val(date.find("some data").text);
});
The code of above obvisouly won't work, but the code you will use can be that simple.
And as stated above once you go ajax you wont go back.
Using the jQuery wrapper makes the ajax bunches easier. You will want to spend an hour or two reading about it as well as looking at various samples
The easiest way is to use jquery ajax:
http://api.jquery.com/jquery.ajax/
You want to do something like this:
$.ajax({
url: "pos.txt",
}).done(function(data) {
var split = data.split(' ');
var date = split[0];
var time = split[1];
var x = split[2];
var y = split[3];
var z = split[4];
//then insert these variables into the elements you need
$('#date').val(date);
});
Try this it will work:
<html>
<head>
<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && xmlhttp.status==200)
{
var response = ajax.responseText;
document.getElementById('get-data').innerHtml = response;
}
}
ajax.open("GET", "pos.txt");
ajax.send(any_data);
</script>
</head>
<body>
<div id="get-data">
</div>
</body>
</html>

Using HTML Tags in Wordpress Page. Getting Error: "Unexncaught SyntaxError..."

I am retrieving data from Parse in my Wordpress page fine. I can append the names of my objects into a page in Wordpress, but as soon as a try to append a HTML tag like <h1> or <p>, I get an error within my Chrome console:
Uncaught SyntaxError: Unexpected token ILLEGAL
Below is the code within my wordpress page that works without errors:
<div id="list1"><h1>Beer List</h1></div>
<div id="list2"><h1>Tap List</h1></div>
<script type="text/javascript">
if (typeof jQuery != 'undefined') {
Parse.initialize("", "");
var Objs = Parse.Object.extend("Obj");
var query = new Parse.Query(Objs);
query.ascending("name");
query.find({
success: function(results) {
var obj1String = '';
var obj2String = '';
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' '+object.get('name')+'</br>';
if(object.get('isObj2') == true){
obj2String = obj2String +' '+object.get('name')+'</br>';
}
}
jQuery( "#list1" ).append( obj1String );
jQuery( "#list2" ).append( obj2String );
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
</script>
But when I add, for example a tag to one of my objStrings, I get the error. i.e.:
obj1String= obj1String +'<h1>'+object.get('name')+'</h1></br>';
Here is how the page is rendering, any why the error is happening. It seems to be adding a line break when it sees those tags:
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' //line break added here
<h1>'+object.get('name')+'</h1>
<p></br>';
if(object.get('isObj2') == true){
objString = obj2String +' '+object.get('name')+'</br>';
}
I have see other threads for this error (i.e. here). But I could not get any suggestions there to work.
Any help would be greatly appreciated, thanks!
I've had a similar problem to this before and I fixed it by making sure all the HTML tags in the JavaScript are on the same line.
As for wordpress template files you can read more about it here http://codex.wordpress.org/Page_Templates. Simply it will allow you to use a PHP file as a template to display that page.

If textfield is empty do not send! - Help JavaScript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So to understand what I'm asking go to http://quicknews.99k.org/java_chat.html
It's a chatbox that I've made with JavaScript.
When you click "send" it would keep sending... is there an if/else statement for JS?
my code:
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function(){
var message = $('textarea').val();
var old = $('#content').html();
$('#content').html(old + '<p>' + message);
});
});
</script>
Yes, it has if/else statement, you may try this
$('button').click(function(){
var message = $('textarea').val();
var old = $('#content').html();
if(message.length==0) return false;
$('#content').html(old + '<p>' + message);
});
I would do this
$('button').click(function(){
var message = $('textarea').val();
if (!message) return false;
var old = $('#content').html();
$('#content').html(old + '<p>' + message);
});
If you want to bar any submit request when textarea is empty, try this:-
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function(e){
var message = $('textarea').val();
var old = $('#content').html();
//We are checking if the length of the message is zero
if(message.length==0)
//Cancel form submission
e.preventDefault();
else {
$('#content').html(old + '<p>' + message);
//Empty the textbox when you are done
$('textarea').val('');
}
});
});
</script>

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

getJSON doesn't work on the server but does locally

I am using jQuery for a cascading check box, but the getJSON command dosen't work on the server (locally it works fine). It couldn't find the data.json file (see error debug).
Part of the script:
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script>
$(function() {
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("data.json?callback=?", function(data) {
var key = $dropdown.val();
var vals = [];
switch(key) {
case 'BR9':
vals = data.BR9.split(",");
break;
case 'base':
vals = ['Please choose from above'];
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});
});
});
});
</script>
Error from firebug:
GET http://______my url site ____/data.json 404 NOT FOUND x 25ms
If I change the line
$.getJSON("data.json", function(data) ...
to
$.getJSON("data.json?callback=?", function(data) ...
it doesn't work either.
Can anyone help me?
Have you tried giving the full path to you json file?
$.getJSON("http://www.mywebsite.com/folder/data.json?callback=?", function(data) {});
Is the page you are making JSON call from and the page you are making the call to are on the same domain ? JSON doesn't support cross domain calls and you would need to use JSONP.

Categories

Resources