I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.
Related
I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
P.S-I know this has been asked. But the answers are too complicated for me to comprehend, besides I'm a newbie in JavaScript/jQuery 2.1.4.
Whenever I start my web app project, this error occurs. But the thing about this error is that it didn't stop the function from executing so it's good. Anyway I don't want to see this error, because I want my app to be error free; so I traced it up and here is my code:
//populate locations select options
$(document).ready(function(){
$.ajax({
type: "GET",
url: "asset_management/poploc", //the script to call to get data
data:'', //you can insert url argumnets here to pass to api.php
dataType: 'json', //data format
success: function(data){ //on recieve of reply
$.each(data, function(index,item){
$("#pop_loc").append("<option value=\""+item.location_id+"\">"+item.location_name+"</option>");
});
}
});
});
Kindly check please.
It is because on a text string, it $.each doesn't work. You need to parse the data as a JSON:
success: function(data) {
// Add this following line.
data = JSON.parse(data);
Also you can get rid of:
dataType: 'json',
Make sure you give a validation before $.each():
success: function(data) {
// Add this following line.
data = JSON.parse(data);
// validate here
if (data.length > 0) {
$.each(data, function(index, item) {
I have a performance problem when loading a website over the network stored on an internal server. The performance issue is down to the multiple AJAX requests made in my Javascript file constantly trying to access an XML file and then getting an Image from a XML node or a Name from an XML node.
Is there a way I can merge the AJAX requests together to reduce the amount of requests from the client device to the XML file stored on the server.
My code is as below:
function getimage(getID,XMLImageID)
{
$("#" + getID).empty();
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLImageID).each(function(){
var image = $(this).find("image[href]").attr("href");
$('#'+ getID).append($("<img"+" class="+"Timages"+" src=\"" +image+"\"/>"));
});
},
error: function() {
alert("(getImage) An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect.");
}
});
}
function getdept(getid,XMLID)
{
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
getid = parentTag.id;
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLID).each(function(){
var dept = $(this).find('Dept').text();
var id = $(this).attr("id");
var sName = $(this).find('Name').text();
$("#"+getid).append('<div class="Team_People" onmouseover="area_hover1(this);area_hover2(this)" href="#p'+id+'">'+dept+'<br />'+sName+'</div>');
});
},
error: function() {
alert("(getHierPeopleDept)An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect.");
}
});
}
The AJAX response uses a simplified code below, I just need to merge the code above to make it more neater rather than having multiple ajax requests. Not sure if this is possible (whether adding multiple parameters would work)?
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLID).each(function(){
//Get something from XML node
});
},
});
}
If anyone could guide me in the right direction that would be much appreciated!
Thanks
Regards
AJ
Create a global XML variable and query that with your function calls...
var XML = null;
function fetchXML(){
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(data){
XML = data;
},
error:function(){ alert('something went wrong');})
}
function getImage(id) {
$(XML).find(id).each(){ ... };
}
funcition getDept(id) {
$(XML).find(id).each(){ ... };
}
I'm working on getting info for an artist from last.fm servers and I need to be able to read the picture of the artist they have on their servers. You can view an example XML return statement here. As you can see, there are many images for each artist (small, medium, large, extralarge, and mega). I need to be able to ready any of these and get the appropriate value back.
I'm new to reading XML/DOM through Javascript, so I'm sure it's fairly simple, but the extra attribute of "size" in the XML file is throwing me for a bit of a loop. Thanks!
This gets the first image for example.
$.ajax({
url: "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&api_key=ac74a1e6fae52bc5f55a8a6f30b84db9",
type: "GET",
dataType: "html",
success: function(data) {
var xml = $.parseXML(data)
$(xml).each(function()
{
alert($(this).find("lfm>artist>image[size]:first").text());
});
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
alert("failure");
}
});
}
use $.parseXML to create a kind of x-document.. then you can find stuff from it with jquery selectors.
getXMLNode(retObj.responseXML, "thatField");
function getXMLNode(xml, nameOfField) {
return $($.parseXML(xml)).find(':first').find(nameOfField).text();
}
Something to this effect should return all image sizes:
$.ajax({
type: "GET",
url: "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&api_key=ac74a1e6fae52bc5f55a8a6f30b84db9",
dataType: "xml",
success: function (xml) {
// Parse the xml file and get data
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$xml.find('image').each(function () {
console.log($(this).text())
});
}
});
I am trying to parse an xml response using jQuery and just output an element the a page but i am unsuccessful in this.
Below is the code that I am using for the response & parsing of it.
$.ajax({
url: UCMDBServiceUrl,
type: "POST",
dataType: "xml",
data: soapMessage,
success: UCMDBData,
crossDomain: true,
contentType: "text/xml; charset=\"utf-8\""
});
alert("Sent2");
return false;
}
function UCMDBData(xmlHttpRequest, status, msg)
{
alert("Came back1");
$(xmlHttpRequest.responseXML).find('tns:CIs').each(function()
{
alert("Came back2");
$(this).find("ns0:CI").each(function()
{
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
});
});
}
I am receiving alerts for "Came back1" but it doesnt appear to be going any further. Below is the XML Response that I am trying to parse using my above jquery code. The text that I am ultimately trying to return out of the response is in this element
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header />
<soapenv:Body>
<tns:getFilteredCIsByTypeResponse xmlns:ns0="http://schemas.hp.com/ucmdb/1/types" xmlns:ns1="http://schemas.hp.com/ucmdb/ui/1/types" xmlns:ns2="http://schemas.hp.com/ucmdb/1/types/query" xmlns:ns3="http://schemas.hp.com/ucmdb/1/types/props" xmlns:ns4="http://schemas.hp.com/ucmdb/1/types/classmodel" xmlns:ns5="http://schemas.hp.com/ucmdb/1/types/impact" xmlns:ns6="http://schemas.hp.com/ucmdb/1/types/update" xmlns:ns7="http://schemas.hp.com/ucmdb/discovery/1/types" xmlns:ns8="http://schemas.hp.com/ucmdb/1/types/history" xmlns:tns="http://schemas.hp.com/ucmdb/1/params/query">
<tns:CIs>
<ns0:CI>
<ns0:ID>4d030502995a00afd989d3aeca2c990c</ns0:ID>
<ns0:type>nt</ns0:type>
<ns0:props>
<ns0:strProps>
<ns0:strProp>
<ns0:name>name</ns0:name>
<ns0:value>prodoo</ns0:value>
</ns0:strProp>
</ns0:strProps>
<ns0:booleanProps>
<ns0:booleanProp>
<ns0:name>host_iscomplete</ns0:name>
<ns0:value>false</ns0:value>
</ns0:booleanProp>
</ns0:booleanProps>
</ns0:props>
</ns0:CI>
</tns:CIs>
<tns:chunkInfo>
<ns0:numberOfChunks>0</ns0:numberOfChunks>
<ns0:chunksKey>
<ns0:key1 />
<ns0:key2 />
</ns0:chunksKey>
</tns:chunkInfo>
</tns:getFilteredCIsByTypeResponse>
</soapenv:Body>
</soapenv:Envelope>
So my question is that how do I properly parse the data? I believe the code syntax is correct but I am not getting the expected returned results. I would appreciate any help, thanks.
EDIT
I have modified my code to the following like the suggestion, but still no luck:
$.ajax({
url: UCMDBServiceUrl,
type: "POST",
dataType: "xml",
data: soapMessage,
success: UCMDBData,
crossDomain: true,
contentType: "text/xml;"
});
alert("Sent2");
return false;
}
function UCMDBData(data, textStatus, jqXHR) {
alert("Came back1");
$(data).find('tns:CIs').each(function () {
alert("Came back2");
$(this).find("ns0:CI").each(function () {
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
document.AppServerForm.outputtext.value = document.AppServerForm.outputtext.value + "http://localhost:8080/ucmdb/cms/directAppletLogin.do?objectId=" + $(this).find('ns0:ID').text() +"&infopane=VISIBLE&navigation=true&cmd=ShowRelatedCIs&interfaceVersion=8.0.0&ApplicationMode=ITU&customerID=1&userName=admin&userPassword=admin";
});
});
}
When I execute the only alert message i receive back is "Came back1" which means that the code is still not going through the xml properly with jquery. Any other suggestions?
The namespace-scoped names need to be handled a little differently. According to this answer:
jQuery XML parsing with namespaces
you would need to use an attribute selector [#nodeName=tns:CIs] instead.
You may need to drop the "#" for jQuery versions later than 1.3. Another suggestion is to escape the colon: .find('tns\:CIs'), which is hacky because it conflates the syntactic prefix with the semantic namespace (the uri). So if the prefix changed this method would break. A more correct answer will recognize the mapping of prefix to namespace uri. The jquery-xmlns plugin for namespace-aware selectors looks promising in that respect.
Your jQuery success function is of the wrong form. It needs to be of the form
function UCMDBData(data, textStatus, jqXHR) {
alert("Came back1");
$(data).find('tns:CIs').each(function () {
alert("Came back2");
$(this).find("ns0:CI").each(function () {
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
});
});
}
In addition, in your $.ajax function, change the contentType line to be contentType: "text/xml" instead of what you have before (assuming that you're sending XML to the server).
See the jQuery.ajax() documentation for more information.
Based on your comment, why do something crazy with jQuery? Just use javascript itself!
var open = '<ns0:ID>';
var close = '</ns0:ID>';
var start = obj.indexOf(open) + open.length;
var end = obj.indexOf(close);
var result = obj.slice(start, end);
Here's a jsfiddle that shows it in action.
Probably the right syntax would be
success: function(xml) {
$(xml).find('tns:CIs').each(function() {
......