Displaying XML information in HTML from a Public XML source - javascript

I'm looking for a very basic way to display one piece of XML data from this public source in html: http://avwx.rest/api/metar.php?station=KTPF
Here is what I have so far, with no luck:
<script type="javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
dataType: "xml",
url: "http://avwx.rest/api/metar.php?station=KTPF",
success: xmlParser
});
});
function xmlParser(xml)
{
$(xml).find("Raw-Report")
{
$("#metar-text").append('<marquee class="metar-marquee">' + $(this).find("Raw-Report").text() + '</marquee>');
};
};
</script>
I have a div in the HTML with the id #metar-text that I would like scrolling (hence the conc. marquee tags) I only need to display the Raw-Report text.

Your code require some corrections to work.
<script type="javascript">
$(document).ready(function(){
$.ajax({//this part is OK
type: "GET",
dataType: "xml",
url: "http://avwx.rest/api/metar.php?station=KTPF",
success: xmlParser //note that success receives 3 arguments
});
});
function xmlParser(data, state, xhr)
{
var xml = xhr.responseXML; //xml document is here
if($(xml).find("Raw-Report").text()) //that is exists and not empty
{
$("#metar-text").append('<marquee class="metar-marquee">'
+ $(xml).find("Raw-Report").text()
+ '</marquee>'); //**this** is $.ajax in this context
};
};
</script>

Related

How can I do a conditional statement so ajax fetchs the correct xml document

I have a simple code to fetch a xml file and display it as a drop down list. However, I would like to fetch the xml file according to a condition. If it equals to study1 then .ajax selects ctc3.xml, else it selects ctc5.xml.
My code was working fine if I was fetching a specific xml file, but the conditional does not work.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script lang="Javascript"> $.noConflict();
jQuery(document).ready(function($) {
var myField = $("#myList") var myOutputField = $("#myOutput").parent().parent().find("input");
myOutputField.attr("readonly",true);
var studyID="${studyName}";
if (studyID!="Test"){
$.ajax({
type: "GET",
url: "includes/ctcae3.xml",
dataType: "xml",
success: parseXML
});
}
else {
$.ajax({
type: "GET",
url: "includes/ctcae5.xml",
dataType: "xml",
success: parseXML
});
}
function parseXML(xml){
$(xml).find("atccode").each(function(){
myField.append($("<option />").val($(this).attr("code")).text($(this).find("description").text()));
});
myField.val(myOutputField.val());
}
myField.change(function(){
myOutputField.val(myField.val());
myOutputField.change();
});
});
</script><select id="myList"> <option val="None"/>None </select> `
problem resolved. Clearly my brain was already fried. It was just a matter of adding the ';' to var myField = $("#myList");

Pass PHP array to external jQuery $.ajax

Basically what I want to do is get an array that has t.php, and alert it with JavaScript with the response of t.php.
The problem is that the variable doesn't exist in this file...
So, how you can pass this variable to JS?
I tried with 'return':
return $sqlData = $q->query_array_assoc();
But doesn't work.
Here is my $.ajax code:
<script type="text/javascript">
$(document).ready(function(){
$('#brand').change(function(e){
console.log(e);
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value }
})
.done(function(msg){
$('#debug').html(msg);
var pArray = <?php echo json_encode($sqlData);?>
for (var i = 0; i < pArray.length; i++) {
alert(pArray[i]);
};
});
});
</script>
Note: I sent
data: { type: 1, brand: this.value }
To validate a switch statement in the .php file, but there isn't problem with that. I get the data from the database and fetch in the variable $sqlData;
So the array has data, the problem is get it with $.ajax
in your php file, you need to echo instead of return
echo json_encode($q->query_array_assoc());
in javascript code:
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value },
success: function(data) {
$('#debug').html(data);
// if you want to use it as array
var json_data = JSON.parse(data);
}
});
Make 2 files please, a "t.php" file and a "t.html" file and add my code there. Run the code and see response. You just have to work with the response to get the values se perated by comma "," !!!
/******************** UPDATED ***********************/
//t.php
<?php
$a = array();
$a[]=1;
$a[]=2;
$a[]=3;
echo "$a[0],$a[1],$a[2]";
?>
//t.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
$.ajax({
method: "GET",
url: "t.php",
data: { },
dataType: "html", //expect html to be returned
success: function(response){
//$("#debug").html(response); //Outputs the html of php file into #dialog div
alert(response);
document.getElementById("debug").innerHTML = (response); //Outputs the html of php file into #dialog div
}
})
}
</script>
<button onclick="fun()">Call Ajax Fun</button>
<div id="debug"></div>
Did this help?

Access Javascript variable in php in same page

Hi I am facing problem with json data. Here is my js code.
<script>
$(function(){
$.ajax({
url:"http://example.com/salary?from=USD&to=GBP",
dataType: 'jsonp',
success:function(json){
alert(json['to']);
},
error:function(){
alert("Error");
},
});
});
</script>
I want to use json data in PHP in same page.
I know that you cannot assign Javascript value to PHP variable.
Is there way to do this?
Or is possible to do similar task in php (Jquery Ajax cross domain) like above javascript code ?
Any help?
your js code
var my_json_obj = new Object();
my_json_obj .name = "Lanny";
my_json_obj .age = "25";
my_json_obj .location = "China";
var json_str = JSON.stringify(my_json_obj);
<script>
$(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "my.php",
data: {
postData: json_str
},
success: function (data) { alert(data) },
eror: function (data) { alert(data) }
});
});
</script>
your my.php file
$postData=$_POST['postData'];
$my_obj=json_decode($postData,true);
$name=$my_obj['name'];
$age=$my_obj['age'];
$localtion=$my_obj['location'];
You could do that with AJAX.
You need a script, which will give javascript vars to the PHP Script, like:
var PHPFile = 'PHPFile.php?arg1=' + arg1 + '&arg2=' + arg2;
In the "PHPFile.php" you can access them by
$arg1 = $_GET["arg1"];
$arg2 = $_GET["arg2"];
Or you could do that with jquery $.ajax-> data, too.
You can access them by
$arg1 = $_POST["arg1"];
$arg2 = $_POST["arg2"];
Something like that:
result = $.ajax({
type: 'POST',
async: false,
url: 'PHPFile.php',
data: ({
arg1: arg1,
arg2: arg2
})
}).responseText;
alert(result);
EDIT:
If you want to do that with a json-object, try this:
json_decode();
http://www.php.net/manual/en/function.json-decode.php
http://www.php.net/manual/en/function.json-encode.php

load data using jquery multiple div

I have the below jquery function to load data from database which works fine, however I would like to show that same data again over the same page, When I do that it doesn't work. it will only shows for the first one. could someone help me out?
<script type="text/javascript">
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(loadData, 1000);
}
});
};
</script>
<div style='display:inline' id='responsecontainer'></div><!--only this one is displayed-->
<div style='display:inline' id='responsecontainer'></div><!-- I want it to show me the same data here too-->
ID of an element must be unique in a document, use class attribute to group similar elements
<div style='display:inline' class='responsecontainer'></div>
<div style='display:inline' class='responsecontainer'></div>
then use class selector
$(document).ready(function () {
loadData();
});
var loadData = function () {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function (response) {
$(".responsecontainer").html(response);
setTimeout(loadData, 1000);
}
});
};
The ID selector will return only the first element with the given ID

JavaScript - Results Displaying in IE but not Chrome or FF

So, i'm new to Javascript, let's get that out of the way.
Anyway, I have the following code that works in IE, but not in Chrome or FF. It's supposed to grab the data from the Reddit RSS, then just output it, that's it. It only is working in IE. Can anyone explain what I'm doing wrong here?
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
document.write(result);
</script>
</head>
</body>
</html>
yes, this code doesn't look right. it's a race condition. document.write executes immediately. the ajax may or may not have set the result in time. you need to add the result to the page in the success event...something like:
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get', dataType: 'html',
async: false,
success: function(data) {
$("#some-div").html(data);
} });
You have race condition due to $.ajax being asynchronous. Display the result in the success handler instead, so that the request is guaranteed to have finished.
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
document.write(data);
}
});
Update
Since you set async to false, the above statement isn't applicable. However, I haven't ever found a good reason to use document.write(), which might be part of your issue. Try using another method to inject the data into your page such as .html(), .append(), alert(), etc. And it wouldn't hurt to do this inside document.ready either.
$(document).ready(function() {
var result = null;
$.ajax({
url: "http://www.reddit.com/.rss",
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
alert(result);
$("body").append(result);
});
What about processing in this manner:
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://www.reddit.com/.rss', function(feed) {
var entries = feed.entries,
feedList = '';
for (var i = 0; i < entries.length; i++) {
feedList += '<li>' + entries[i].title + '</li>';
}
jQuery('.rssfeed > ul').append(feedList);
});
HTML:
<div class="rssfeed">
<h4>RSS News</h4>
<ul></ul>
</div>
sample: http://jsfiddle.net/QusQC/

Categories

Resources