How to extract data from AJAX's responseText? - javascript

When I use responseText, I get all the data. From <HTML> to </HTML>. How to I extract specific parts of it? For example, I have this code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tester</title>
</head>
<body>
<table>
<tr>
<td><a name="Name"></a>Name</td>
<td>John</td>
</tr>
<tr>
<td><a name="Email"></a>Email</td>
<td>john#aol.com</td>
</tr>
<tr>
<td><a name="Address"></a>Address</td>
<td>123 Elm Street</td>
</tr>
<tr>
<td><a name="City"></a>City</td>
<td>Los Angeles</td>
</tr>
<tr>
<td><a name="State"></a>State</td>
<td>CA</td>
</tr>
</table>
</body>
</html>
And Then I need to just extract like the city part Los Angeles. How would I go about doing this? I can't do responseText.getElementByTagName, or anything like that.
Here's the AJAX call:
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 pageContents = xmlhttp.responseText;
document.getElementById("myDiv").innerText = pageContents;
}
}
xmlhttp.open("GET","content.html",false);
xmlhttp.send();

For a pure JavaScript solution, try (untested):
var city = responseXML.getElementsByName('City').parentNode.nextElementSibling.childNodes[0].getAttribute('textContent');
That said, a JavaScript library, like jQuery, to do the heavy lifting sure makes your code a lot easier to read (as well as cross-browser friendly).

jQuery names this (sort of) easy:
alert($('table').find('tr').eq(3).find('td').eq(1).html()) ---> Los Angeles

Related

Getting data from Google docs into Javascript

I try to get data from google spreadsheets and everything is allright when I'm testing html page locally. But when I load my html file and javascript file into server nothing works.
Here is the code of html file "page.htm":
<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body
onload= "Data();">
<table>
<form name="Team">
<tr>
<td>
<input size="19" name="tName" readonly >
</td>
</tr>
</form>
</table>
</body>
</html>
And js file "teams.js":
function Data() {
var url="https://docs.google.com/spreadsheets/d/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/pub?&gid=0&range=A1&output=csv";
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status==200){
document.Team.tName.value = xmlhttp.responseText;
}
};
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
Google doc
Tried this on my own server - got a following CORS error on the browser's console:
This means that you cannot directly access the url with your browser, because the Google's server is not sending back a required header field that would allow this.
A way around this is to use an alternative API, that can provide us with JSONP format output for the Google Spreadsheet:
So consider this JavaScript:
function Data(response) {
document.Team.tName.value = response.feed.entry[0].gs$cell.$t;
}
And the following HTML:
<html>
<head>
<title>
</title>
<script type="text/javascript" src="teams.js" >
</script>
</head>
<body>
<table>
<form name="Team">
<tr>
<td>
<input size="19" name="tName" readonly >
</td>
</tr>
</form>
</table>
<script src="https://spreadsheets.google.com/feeds/cells/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/1/public/values?alt=json-in-script&callback=Data&range=A1"></script>
</body>
</html>
And it should work perfectly.
This works as, rather than your won code, the Google's own server calls the Data function with the proper data - a method called JSONP that allows cross-domain data requests. Requesting data from another domain is blocked by default in the browsers. The only exception is the file:// protocol, which allows some requests to any domains, as there is no origin domain to match the rules. This explains why your code worked on the local, but not after it had been uploaded to the server.
When I run the code it works, fills the input with the csv file value. When I try to run the link on How do you Import data from a Google Spreadsheet to Javascript? got cross origin block from my browser.
If you can't run the script below you should try allowing CORS on your browser or perhaps try with ajax.load to get the file.
<html>
<head>
<title>
</title>
<script type="text/javascript">
function Data() {
var url = "https://docs.google.com/spreadsheets/d/18WEeF3d9pJWYK1sheNHgc0KOi845cjyZgJ8x6TVisFM/pub?&gid=0&range=A1&output=csv";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.Team.tName.value = xmlhttp.responseText;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
</script>
</head>
<body onload="Data();">
<table>
<form name="Team">
<tr>
<td>
<input size="19" name="tName" readonly>
</td>
</tr>
</form>
</table>
</body>
You should see it something like:

Ajax code not working to search data

i am using normal ajax to search from data base when form submit but the code is not working . There are two date field i want to search data between two dates if i use separate page the code is working but in ajax it is not working .any help will be appreciate Thank you
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="datepicker/javascript/jquery-1.9.1.min.js"></script>
<link rel="stylesheet" href="datepicker/css/default.css" type="text/css" />
<script type="text/javascript" src="datepicker/javascript/zebra_datepicker.js"></script>
<script>
$(document).ready(function() {
$('input.datepicker').Zebra_DatePicker();
$('#strt_dt').Zebra_DatePicker();
});
$(document).ready(function() {
$('input.datepicker').Zebra_DatePicker();
$('#end_dt').Zebra_DatePicker();
});
</script>
<script>
function showStd(tstfrm) {
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) {
document.getElementById("replace").innerHTML=xmlhttp.responseText;
}
}
var strt_dt = document.getElementById('strt_dt').innerHTML;
var end_dt = document.getElementById('end_dt').innerHTML;
xmlhttp.open("GET","test2.php?strt_dt="+strt_dt+"&end_dt="+end_dt, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="" method="post" onsubmit="return showStd(this);" name="tstfrm" id="tstfrm">
<fieldset>
<p><label>Start Date:</label><input name="strt_dt" type="text" class="text-long" id="strt_dt" /></p>
<p><label>End Date:</label><input name="end_dt" type="text" class="text-long" id="end_dt" /></p>
<input name="serch" type="submit" id="serch" value="search"/>
</fieldset>
</form>
<div id="replace" style="height:500px; width:1000px; border:1px solid #000;">
</div>
</body>
</html>
and here is the below test2.php for search
<?php
include '../dbconn.php';
$strt_dt=$_REQUEST['strt_dt'];
$end_dt = $_REQUEST['end_dt'];
?>
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td width="137"><b>Name</b></td>
<td width="154"><b>Contact</b></td>
<td width="407" align="center"><b>Action</b></td>
</tr>
<?php
$qry=mysql_query("SELECT * FROM std_register WHERE reg_dt BETWEEN '".$strt_dt."' AND '".$end_dt."'");
while($row=mysql_fetch_array($qry))
{
?>
<tr>
<td><?php echo $row['std_name1']." ".$row['std_name2'];?></td>
<td><?php echo $row['std_phno'];?></td>
</tr>
<?php
}
?>
</table>
Dude i can see in your code that you are using jQuery on the page.
can use jQuery provided methods for Ajax requests.
$.get
$.post
And more verbose method $.ajax for your work you need jQuery to make it cross browser.
$.get('/test2.php?date='+date,function(response){
//use server response to manipulate dom
});

compare responseText with another string

I have index.html file having code like this:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function ajaxObj(str){
var xmlhttp;
if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlhttp=false;
}
}
else{
try{
xmlhttp=new XMLHttpRequest();
}
catch(e){
xmlhttp=false;
}
}
if(!xmlhttp)
alert("cant create the xmlHttp object");
else
//alert("objet created");
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
// alert("in ready state");
var resp=xmlhttp.responseText;
document.getElementById("div1").innerHTML=resp;
if(resp=="pal"){
document.getElementById("div2").innerHTML="text is pal";
}
else{
document.getElementById("div2").innerHTML="text is something else";
}
}
}
xmlhttp.open("GET","mainJsp.jsp?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input type="text" name="userInput" onblur="ajaxObj(this.value)"/>
</td>
</tr>
<tr>
<td>
<div id="div1"></div>
</td>
</tr>
<tr>
<td>
<div id="div2"></div>
</td>
</tr>
</table>
</body>
</html>
and mainJsp.jsp having code like this:
<%
String textValue=request.getParameter("q");
if(textValue.equals("pal")){
out.println(textValue);
}
/*if(textValue.equals("mohit")){
out.println(textValue);
}*/
else{
out.println("else");
}
%>
whether i enter 'pal' or something else in text box in index.html. only else statement 'text is something else' in javascript function get executed. if statement never get exexuted. Please help
Here is a fiddle with this working. The formatting around your code was a little confusing to me, sorry about that. I took a couple liberties. Let me know if you have a problem with it!
if(textValue === "pal"){
alert("If");
}
else{
alert("else");
}
Fiddle
StackOverflow about '===' operator

TypeError: Obj.[function] is not a function

TypeError: Obj.EnableLog is not a function
in firefox version 23.0.1
But in earlier firefox version my javascript code is working,
Here is my javascript code,
document.write('<applet code="BiomAPI.Legend.class" width="0" height="0" archive="BiomAPI.jar" id="Obj"></applet>');
document.write('<script language="vbscript" type="text/vbscript" src="LegendScript.vbs"> </script>');
function GetFeature (sUserID,iFingerID)
{
if(navigator.appName == "Microsoft Internet Explorer")
{
vbscript:vGetFeature (sUserID,iFingerID,hdnVerifyFeature);
}
else
{
if(hdnVerifyFeature==null)
alert("Invalid Hidden Field Argument Passed");
else
{
document.getElementsByName("Verify")[0].value = "";
var lsFeature = null;
Obj.EnableLog(0);
Obj.WindowTitle("Sample");
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(1);
Obj.SessionID("abcde");
Obj.TimeStamp("Wednesday");
Obj.SaveImage(1);
Obj.GetFeature(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
Obj.WindowTitle("");
if (lsFeature != null)
{
document.getElementsByName("Verify")[0].value = lsFeature;
}
else
{
alert("Fingerprint not captured");
}
}
}
}
And my html code is,
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body>
<script language="javascript" type="text/javascript" src="LegendScript.js"> </script>
<table id="tableid" width="500" style="height: 100">
<tr align="center">
<td>
Verification</td>
</tr>
<tr>
<td>
Verification Template</td>
<td>
<input type="text" name="Verify" id="hdnVerifyFeature" runat="server" /></td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" id="btnRecog" value="Recognition" style = "width:150" onclick="GetFeature('0','0')" /></td>
</tr>
</table>
</body>
</html>
This javascript code is not working in mozila firefox 23.0.1. But this code will work in earlier mozila firefox versions, Please anyone tell solution this problem. How to enable or work javascript in firefox version 23.0.1. I want to work in firefox 23.0.1.
Thanks in advance.
I think the problem is that you are relying on non-standards behaviour to access the div by its id. You should create a reference to the div first:
var Obj = document.getElementById("Obj");
Here is some further discussion on global id refs across different browsers:
Is there a spec that the id of elements should be made global variable?

getting the value of an object node - javascript

newbie here .. wondering why in the table i get something called '[object node]' and not the actual value?
<script type="text/javascript">
window.onload = wonfunction;
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","sc2xml.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
function wonfunction() {
var homestead = xmlDoc.getElementsByTagName("sc2cash");
document.getElementById('num1').innerHTML = homestead[0];
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<table width="200" border="1">
<tr>
<td>Players</td>
<td id="num1"></td>
</tr>
<tr>
<td> </td>
<td> </td>
To answer your comment:
In IE8 atleast you can use the .text property of a node like so:
var myNodes = xmlDoc.getElementsByTagName('node');
document.getElementById('result').innerHTML = myNodes[0].text;
Some good articles are alistapart AJAX and a MS blog with some good examples too.
Here is a jsfiddle that works fine in IE8.

Categories

Resources