i have an RegistrationResponseMessages.xml:
<messages>
<error>
<code id="501">Couldn't retrieve the HTML document because of server-configuration problems.</code>
<code id="502">Server busy, site may have moved ,or you lost your dial-up Internet connection.</code>
</error>
<success></success>
</messages>
trying to read contents of code id 501 and 502 with javascript, but it not works.
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("errorCode403").innerHTML = getElementsByTagName(501)[0].childNodes[0].nodeValue);
displaying it here:
<label id="errorCode403" style="font-weight: 600; color: red;">give some error</label>
what is my problem?
It's ajax, you have to wait for the data to be returned, then you have to access it the right way:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onload = function() {
var xmlDoc = this.responseXML,
value = xmlDoc.getElementsByTagName('501')[0].childNodes[0].nodeValue;
document.getElementById("errorCode403").innerHTML = value;
}
xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
xmlhttp.send();
Not sure about the traversal in the XML, as 501 sounds like a strange tagName ?
EDIT:
to get a list of the ID's you do this inside the onload handler:
xmlhttp.onload = function() {
var xmlDoc = this.responseXML,
var codes = xmlDoc.getElementsByTagName('code');
var array = [];
for (var i=0; i<codes.length; i++) {
array.push( codes[i].id );
}
console.log(array);
}
Related
I'm doing a Twitter API request that returns JSON of all tweets containing #awkward . Here's the successful response on a server: http://babbage.cs.missouri.edu/~atgvyc/php/election_tweets/index.php
But I want to be able to use that JSON in my JavaScript and parse through it with a for-loop to pull out certain information (particularly the geotags and location). I thought I could do this with AJAX and then JSON.parse, but it's not working the way I thought it would.
Any suggestions?
Here's my PHP script:
<?php
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => "XXX",
'oauth_access_token_secret' => "XXX",
'consumer_key' => "XXX",
'consumer_secret' => "XXX"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=#awkward&geocode=38.949926,-92.330037,35mi&result_type=recent';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
?>
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample elections tweets</title>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = JSON.parse(xmlhttp.responseText);
//here's where i'd like to put a for-loop
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<body>
Ok, I think I know what you are trying to do now. There really isn't an out of the box "for each" like there is in php, which is why a lot of frameworks implement there own (jQuery's $.each()), or make prototypes. But, you may be able to do what you need with the below. You can replace all the console.log() with alert() if you want, but it gets hectic not being in Chrome's dev tools (f12 on most machines). Also, if Dale Musser is still there tell him hello! MIZ
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var json = JSON.parse(xmlhttp.responseText);
//log entire json struct to developer console for easy viewing
console.log(json);
//you can reference individual pieces of json by doing something like
//json.statuses or json.statuses[2]
var statuses = json.statuses;
for(var i=0;i<statuses.length;i++){
var curStatus = statuses[i];
//access bits directly
var tweetAuthor = curStatus.user.name;
var tweetTime = curStatus.created_at;
//iterate hashtags
var hashtags = curStatus.entities.hashtags;
for(var k=0;k<hashtags.length;k++){
console.log("Hashtag: " + hashtags[k].text);
}
//iterate all elements of tweet
for(var key in curStatus){
var attrName = key;
var attrValue = curStatus[key];
console.log("attribute name: " + attrName);
console.log("attribute key: " + attrValue);
if(attrName = "text") {
//Do something with tweet texts... like:
//document.getElementById("statuses").appendChild(attrValue);
}
}
}
}
}
xmlhttp.open("GET","index.php",true);
xmlhttp.send();
}
I am working on a webpage that needs to store data on the server in a .json file.
Here is what I have tried so far:
Javascript code:
// variable j = our json
var j;
function loadDoc(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
j = xmlhttp.responseText;
}
}
xmlhttp.open("GET","things.json",true);
xmlhttp.send();
}
loadDoc();
function rewrite(){
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
};
};
xhr.open("POST", "write.php", true);
xhr.send("data=" + j);
};
The PHP file:
<?php
$data = $_POST['data'];
file_put_contents('things.json', $data);
?>
Note, in other parts of my code the j variable is changed.
My problem is that after the PHP script is making the JSON file blank. Am I doing anything wrong? Is php receiving the JSON properly? If so, how can I fix that?
Cheers!
If you vote down, please tell me why.
To POST data like an HTML form, add an HTTP header with setRequestHeader(). (w3school page)
so it must be :
xmlhttp.setRequestHeader("Content-type","application/json");
I am calling a asmx web service like this
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var data = xmlhttp.responseText;
var xmlDoc = xmlhttp.responseXML;
}
}
xmlhttp.open("GET", "https://Service/ServiceName.asmx/method?query=data1&count=1",true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send();
even after the readystate being 4, I get responseXML as null and responseText as empty. whereas the url
"https://Service/ServiceName.asmx/method?query=data1&count=1"
works perfectly in the browser.
Please help.
Use a relative path:
with(new XMLHttpRequest)
{
open("GET","/Service/ServiceName.asmx/method?query=data1&count=1",true);
setRequestHeader("Foo", "Bar");
send("");
onreadystatechange = handler;
}
function handler(event)
{
!!event.target && !!event.target.readyState && event.target.readyState === 4 && ( console.log(event) );
}
If that doesn't work, try loading the URL from JavaScript to check for routing issues:
window.location = "/Service/ServiceName.asmx/method?query=data1&count=1"
My javascript XML parsing code works fine when I load it in firefox using local HTML & XML files, however when i build my app in visual studio 2012 (HTML5 javascript app) using the same code it fails to parse the XML file.
<script type="text/javascript">
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "pages/home/example.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
//Content
txt = xmlDoc.getElementsByTagName("Symbol")[0].childNodes[0].nodeValue;
document.write(txt + " ");
You can get responseXML only after load.
var xmlDoc
xmlhttp.open("GET", "pages/home/example.xml", false);
xmlhttp.onload = function(){
xmlDoc = xmlhttp.responseXML
}
xmlhttp.send();
Hello I want to get xml from Google Weather
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp= new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.send(null);
xmlDoc=xmlhttp.responseXML;
It`s not working . Thanks
XMLHttpRequest is asynchronous. You need to use a callback. If you don't want to use a full-fledged library, I recommend using Quirksmode's XHR wrapper:
function callback(xhr)
{
xmlDoc = xhr.responseXML;
// further XML processing here
}
sendRequest('http://www.google.com/ig/api?weather=london&hl=en', callback);
If you absolutely insist on implementing this yourself:
// callback is the same as above
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
callback(xmlhttp);
};
xmlhttp.send(null);
Edit
As #remi commented:
I think you'll get a cross domain access exception : you can't make an ajax request to an other domain than your page's. no ?
Which is (for the most part) correct. You'll need to use a server-side proxy, or whatever API that Google provides, instead of a regular XHR.
You can't do this via javascript to to it being a cross-domain request. You'd have to do this server-side.
In PHP you'd use CURL.
What you are trying to do can't be done with Javascript.
Ok here is the code :
<html>
<body>
<script type="text/javascript">
var xmlhttp;
var xmlDoc;
function callback(xhr)
{
xmlDoc = xhr.responseXML;
// further XML processing here
}
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
callback(xmlhttp);
};
xmlhttp.send(null);
alert(xmlDoc);
</script>
</body>
</html>
It doesn`t returns any errors but alert returns undefined.