Javascript code for parsing the xml document - javascript

I want a javascript code for calling web script (http://10.0.2.2:8080/alfresco/service/api/login?u=admin&pw=admin) of alfresco remotely in android app using Phonegap and prase the return result and append this return result to other call of webscript of alfresco(http://localhost:8080/alfresco/service/sample/folder/Company%20Home?format=atom)..
please help me on this.
I have this sample code, how can i change it to my need...I want to invoke http://10.0.2.2:8080/alfresco/service/api/login?u=admin&pw=admin parse the return value and append it to one more call of webscript http://localhost:8080/alfresco/service/sample/folder/Company%20Home?format=atom .
<html>
<head>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script src="jquery-1.4.2.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
function bodyload(){
alert("We are calling jquery's ajax function and on success callback xml parsing are done");
$.ajax({url:'http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml',
url:'
dataType:'application/xml',
timeout:10000,
type:'POST',
success:function(data) {
console.log("Customers Tab",data);
$("#bookInFo").html("");
$("#bookInFo").append("<hr>");
$(data).find("Book").each(function () {
$("#bookInFo").append("<br> Name: " + $(this).find("name").text());
$("#bookInFo").append("<br> Address: " + $(this).find("address").text());
$("#bookInFo").append("<br> Country: " + $(this).find("country").text());
$("#bookInFo").append("<br><hr>");
});
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
alert("Error status :"+textStatus);
alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
$( "#bookInFo" ).append( XMLHttpRequest.responseXML);
}
});
}
</script>
</head>
<body onload="bodyload()">
<button onclick="bodyload()">Get Ticket</button>
<p id="bookInFo"></p>
</body>

For xml like
<test>
<something>
<data>Data1</data>
<other>Other1</usage>
</something>
<something>
<data>Data1</data>
<other>Other1</usage>
</something>
</test>
Use like this to parse
$.ajax({
type : 'GET',
url : "http://some-url:8080/test.xml",
data : {
key : "value"
},
dataType : "xml",
success : function(xml) {
data1 = $(xml).find('data').eq(0).text();
data2 = $(xml).find('data').eq(1).text();
other1 = $(xml).find('other').eq(0).text();
other2 = $(xml).find('other').eq(1).text();
},
error : function(xhr) {
alert("Error while loading!!!");
}
});
Let me know if it helped you..

Related

Trying to read from RSS Feed with Javascript but code does not work

I have been trying to get the code below to work but I have had no luck. I cannot figure out what I"m doing wrong. All I want to do is read the alerts from the link and post them into a list. I tried two methods but both don't produce any results. Can someone please point me in the right direction? thank you for your time.
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
FIRST METHOD
<script>
$.get('http://www.wmata.com/rider_tools/metro_service_status/feeds/rail_Advisories.xml?',
function (data)
{
$(data).find("item").each(function ()
{
var el = $(this);
console.log("Title");
});
});
</script>
SECOND METHOD
<script>
$.ajax({ url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('http://www.wmata.com/rider_tools/metro_service_status/feeds/rail_Advisories.xml?'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("Title");
});
}
}
});
</script>
</html>
Due to cross origin nature of the ajax call, use jsonp as the data type:
$.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('http://www.wmata.com/rider_tools/metro_service_status/feeds/rail_Advisories.xml?'),
dataType : 'jsonp',
success : function (data) {
console.log(data.responseData.feed.entries);
$.each(data.responseData.feed.entries, function (i, e) {
console.log(e.content);
$(".result").append("<p>" + e.content + "</p>");
});
}
});
Here is a working DEMO

AJAX Load not working Error occured: 404 error

This is my code and I'm trying to load html from demo_test.txt into it, but it won't work no matter what I try. I've tried changing it from txt to html as well and it still won't load.
The other ajax command such as appending the text works correctly its the load line which won't work?
<head>
<title>Flask AJAX Demo</title>
<!--<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style2.css') }}"> -->
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type=text/javascript
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type=text/javascript>
var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
<script type=text/javascript>
$(function() {
$("#submitBtn").click(function() {
$('#div1').load('dem_test.txt');
$.ajax({
type: "GET",
url: $SCRIPT_ROOT + "/echo/",
contentType: "application/json; charset=utf-8",
data: { echoValue: $('input[name="echoText"]').val() },
success: function(data) {
$('#echoResult').append("<br>");
$('#echoResult').append(data.value);
}
});
});
});
</script>
<strong>Enter a value to echo back:</strong>
<input type='text' size='10' id='echoText' name='echoText'>
<button type='button' id='submitBtn' name='submitBtn'>Submit via AJAX</button><br /><br />
<strong><div id='echoResult'></div></strong>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
This is what is in the demo_test.txt, this won't work if it is html either
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
EDIT:
I changed my load to this:
$('#div1').load('dem_test.txt', function(response, status, xhr) {
if ( status == "error" ) {
alert("Error occured: " + xhr.status + " " + xhr.statusText );
} else {
alert("Text loaded!");
}
});
But I get Error occured: 404 error , but the dem_test.txt file is in the same folder as the html file?
EDIT 2
I have tried this exact example as well found here:
https://stackoverflow.com/questions/16944723/load-method-in-jquery-give-me-404-not-found-error
BUT it won't work like his didn't either, what should the file location be?
It is better to use jquery load in this way;
$('#div1').load('dem_test.txt', function(response, status, xhr) {
if ( status == "error" ) {
alert("Error occured: " + xhr.status + " " + xhr.statusText );
} else {
alert("Text loaded!");
}
});
You can see alert if file is loaded

Parse json using ajax

I receive a json file from a python server, which I try to parse using ajax to display the values according to the categories(e.g.data_provider,census) in separate drop down menus .But i constantly get the following error:
Uncaught Error: Syntax error, unrecognized expression: [{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"h1","summ_level":"160"},{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"p1","summ_level":"050"}]
Kindly help me out ! Below is the code I wrote.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function codeAddress() {
var ajax = $.ajax({
//data : params,
type : "GET",
crossDomain: true,
dataType: "json",
//jsonp: "callback",
//callbackParameter: "callback",
//contentType : "application/x-www-form-urlencoded",
url : "http://0.0.0.0:8080/"
});
ajax.done(function() {
var response=ajax.responseText;
var json = jQuery.parseJSON(response);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
});
ajax.fail(function() {
alert("fail");
});
ajax.always(function() {
alert("done");
});
}
</script>
</head>
<body id="b1" onload="codeAddress();">
</body>
</html>
Because you're setting datatype to json, I'd guess you do not need to parse the JSON yourself. Please note that the parsed response is provided in the done method's first argument, see this example from the jQuery docs:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
})
.done(function( data ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
});
If you're already using jQuery, just let them do the grunt work for you!
$.getJSON("http://0.0.0.0:8080/", function(json){
// do your JSON work here
});
If for whatever reason you can't use $.getJSON, in your $.ajax request, set a success callback function like the one i have over here.

Why isn't this jquery.get function working?

I've been trying to create a small page and all it does is update some values from a source document. The page loads fine, but I don't get the results from the requested source. The .fail function runs, but the textStatus and errorThrown values don't appear in the alert() window that pops up.
I'm very new to javascript and jquery. I'm trying to bash this together with pieces found from the web to figure it out but nothing seems to be working. Mainly, it's the response I think I'm falling down on...
Anyway, here's the code:
<html>
<head>
<title></title>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function update() {
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890/linearlist.xml",
dataType: "xml"
}).done(function (res) {
//alert(res);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
}
function GetData() {
update();
setTimeout(function () {
GetData();
}, 50);
}
});
</script>
</head>
<body>
<script type="text/javascript">
GetData();
</script>
<div class="result"> result div</div>
</body>
</html>
UPDATE:
I've update my code re: #Ian's answer. It's still not working, sadly. I'm not getting the textStatus or errorThrown results either. I've tried debugging with Internet Explorer through VS2012 but it's not getting me far. If I put the URL into a webpage, I can view the XML document.
$.get does not accept one parameter as an object literal; it accepts several: http://api.jquery.com/jQuery.get/#jQuery-get1
You might be thinking of the $.ajax syntax: http://api.jquery.com/jQuery.ajax/
Anyways, call it like:
$.get("http://192.168.2.86:15890//onair.status.xml", {}, function (res) {
var xml;
var tmp;
if (typeof res == "string") {
tmp = "<root>" + res + "</root>";
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(res);
} else {
xml = res;
}
alert("Success!");
}, "text");
Or use $.ajax:
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890//onair.status.xml",
dataType: "text"
}).done(function (res) {
// Your `success` code
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
Using the fail method, you can see that an error occurred and some details why.
Depending on what/where http://192.168.2.86:15890 is, you may not be able to make AJAX calls due to the same origin policy - https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript
I know you have some logic in your success callback, but I'm pretty sure if you specify the dataType as "text", the res variable will always be a string. So your if/else shouldn't really do much - the else should never execute. Either way, if you're expecting XML, it's probably easier to just specify the dataType as "xml".

django-ajax json response

I have a django url : '127.0.0.1:8000/showsym' mapped to view returning json response
def get_symptoms(request):
bp=BodySubPart.objects.get(body_subpart="head")
data1=bp.symptoms.all()
data = serializers.serialize('json', data1)
return HttpResponse(data,mimetype='application/json')
now i am trying to parse this in ajx_form.html and code for that is :
<html>
<head>
<title>Hist</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
(function() {
$.get('127.0.0.1:8000/showsym/', function(data1) {
alert(data1);
});
});
</script>
</body>
</html>
but it is not giving me any output
the page is coming blank
please help me here somebody
It is because your code tries to get the url: /127.0.0.1:8000/showsym/
Change 127.0.0.1:8000/showsym/ to /showsym/.
I suggest you use $.getJSON and name urls, assuming the url name of /showsym is showsym:
$(document).ready(function() {
$.getJSON('{% url showsym %}', function(data, textStatus, jqXHR) {
alert(data);
})
})

Categories

Resources