XMLHttpRequest returns no response & XML error - javascript

I am trying to submit XML data using XMLHttpRequest to an external API which returns response as XML.
I have written the following code but it is not getting any response. Though I am getting 200 http response. In Firebug i get response tab empty while the XML tab shows me this error "XML Parsing Error: no element found Location: moz-nullprincipal"
Can anyone please point the problem, I am running it on my local machine. Below is my complete code.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
var data;
data='<?xml version="1.0" encoding="utf-8" ?>';
data=data+'<LeadImportDatagram>';
data=data+'<CompanyKey>302455</CompanyKey>';
data=data+'<LeadInfo>;'
data=data+'<Category>Gutters Drains</Category>';
data=data+'<Subcategory>Broken Gutter Repair</Subcategory>';
data=data+'<OfferName>First month free with one year contract</OfferName>';
data=data+'<Contact>Graham Carpenter</Contact>';
data=data+'<Company>Union Boxing Company</Company>';
data=data+'<Address>34 Railroad Rd.</Address>';
data=data+'<Address2></Address2>';
data=data+'<City>Newark</City>';
data=data+'<State>DE</State>';
data=data+'<Zip>34852</Zip>';
data=data+'<Country>United States</Country>';
data=data+'<Phone>800-842-2345</Phone>';
data=data+'<PhoneExt>113</PhoneExt>';
data=data+'<AltPhone>315-342-5468</AltPhone>';
data=data+'<AltPhoneExt></AltPhoneExt>';
data=data+'<Mobile>315-985-4984</Mobile>';
data=data+'<MobileExt></MobileExt>';
data=data+'<Fax>800-842-2346</Fax>';
data=data+'<FaxExt></FaxExt>';
data=data+'<EMail>graham#unionboxing.com</EMail>';
data=data+'<PotentialValue>900</PotentialValue>';
data=data+'<Comment>We are looking for a reliable and prompt pest control provider.</Comment>';
data=data+'<SourceCode>LEADFCTRY</SourceCode>';
data=data+'<SourceDescription>Lead Factory Lead Distributors</SourceDescription>';
data=data+'<SourceType>1</SourceType>';
data=data+'<SourceClassCode>AGGREGATOR</SourceClassCode>';
data=data+'<SourceClassDescription>Service Aggregators</SourceClassDescription>';
data=data+'<TimeRange>9am-5pm</TimeRange>';
data=data+'<SEligibleDate>10/1/08</SEligibleDate>';
data=data+'<EEligibleDate>10/31/08</EEligibleDate>';
data=data+'<LeadCost>27.00</LeadCost>';
data=data+'<ProviderID>9843</ProviderID>';
data=data+'<Questions>';
data=data+'<QuestionNode>';
data=data+'<Question>Have you previously had service done by Ace Pest Control?</Question>';
data=data+'<Answer>No</Answer>';
data=data+'</QuestionNode>';
data=data+'<QuestionNode>';
data=data+'<Question>Are you currently receiving service from any other pest control operator?</Question>';
data=data+'<Answer>No</Answer>';
data=data+'</QuestionNode>';
data=data+'<QuestionNode>';
data=data+'<Question>When was the first time you noticed your pest problem?</Question>';
data=data+'<Answer>We first noticed the problem in July 2006 when we saw damage to one of the walls in the basement.</Answer>';
data=data+'</QuestionNode>';
data=data+'</Questions>';
data=data+'</LeadInfo>';
data=data+'</LeadImportDatagram>';
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
//xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp=new ActiveXObject("MSXML2.ServerXMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
alert("Ready state: "+xmlhttp.readyState)
alert("Status: "+xmlhttp.status)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseXML;
} else if (xmlhttp.status==404) {
alert("XML could not be found");
}
}
xmlhttp.open("POST","http://www80.mypestpac.com/xml/importlead.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-type","text/xml");
xmlhttp.send(data);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>

data='<?xml version="1.0" encoding="utf-8" ?>';
data=data+'<LeadImportDatagram>';
data=data+'<CompanyKey>302455</CompanyKey>';
data=data+'<LeadInfo>;'
Line 13 has to be
data=data+'<LeadInfo>';
instead of
data=data+'<LeadInfo>;'
That is causing the XML error you get.

Related

ajax php call not returning anything

I want php to return a value to ajax. I'm following W3 schools example but no joy.
Here is the javascript/ajax code:
function createReport() {
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) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)
createReport();
and later in the body section of the html I have:
<div id="report">Report will be placed here...</div>
If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:
<?php
echo 'return this to ajax';
?>
My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?
I personally do not think the w3cschools a good place to learn ( see http://www.w3fools.com/ ).
It may be that the problem occurs because of the order that you set the ajax, you did:
XMLHttpRequest/onreadystatechange/open/send
is preferable (if you do not follow this order may occur several flaws in older browsers):
XMLHttpRequest/open/onreadystatechange/send
Note: do not worry, the "open(...)" does not start listeners.
Listeners only work after the "send(...)"
Another reason may be that you did not create "error handling" of XMLHttpRequest.status, it serves to verify faults in the server response.
Try this:
<script>
function XHR(){
if(window.XMLHttpRequest){//outers browsers
return new XMLHttpRequest();
} else if(window.ActiveXObject){//IE
try{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(ee) {//IE
try{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(ee) {}
}
}
return false;
}
function createReport(){
var xhr = XHR();// call ajax object
if(xhr){
xhr.open("GET", "test.php", true);//setting request (should always come first)
xhr.onreadystatechange = function(){//setting callback
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("report").innerHTML=xhr.responseText;
} else {//if the state is different from 200, is why there was a server error (eg. 404)
alert("Server return this error: " + String(xhr.status));
}
}
};
xhr.send(null);//send request, should be the last to be executed.
} else {
alert("Your browser no has support to Ajax");
}
}
</script>
<div id="report">Report will be placed here...</div>
<script>
createReport();//prefer to call the function after its div#report
</script>
To prevent cache, replace:
xhr.open("GET", "test.php", true);
by
xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);
At first glance I don't see anything wrong on your js code, so I bet it will probably be a problem locating test.php in your folder structure.
With firebug check the call your javascript AJAX it's doing, and check if the file test.php is being correctly assesed.
I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).
Possible factors:
Missing <script></script> tags
Make sure you have JS enabled.
Make sure your browser supports it.
You may have forgotten to change the button's call to the proper function.
Working and tested code using FF 26.0 and IE version 7
Pulled from W3 Schools Website (example) and slightly modified to prove this works.
Result when clicking on the Change Content button:
return this to ajax - as per your PHP code.
<!DOCTYPE html>
<html>
<head>
<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)
{
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP used: (test.php)
<?php
echo 'return this to ajax';
?>
Other possible factors:
If on a local machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly.
If on a hosted service, make sure PHP is available for you to use.
Files are not in the same folder as executed from.
try{
request = new XMLHttpRequest();
}catch(trymicrosoft){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request = false;
}
}
}
if(!request)
{
alert("Error initializing XMLHttpRequest!");
}
function Create_Ajax_Query(LinkToFile,Parametrs)
{
window.document.body.style.cursor='progress';
request = new XMLHttpRequest();
var url = LinkToFile;
var params = Parametrs;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = newinfo;
request.send(params);
}
function newinfo()
{
if(request.readyState==4 && request.status == 200){
window.document.body.style.cursor='default';
alert(request.responseText);
}
}
Hope its useful!
The code looks correct. it runs just fine on a local environment.
I would advise to look at the "Network" tab in the developer tools to detect any errors may occurs on the server side. You can also use console.log() to follow the javascript actual flow:
function createReport() {
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() {
console.log(xmlhttp); //to show the entire object after statechage.
console.log(xmlhttp.readyState); //to show specific parameter.
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}

Reading a simple text file using AJAX. Access Denied error on open function

I just started learning Ajax and I am stuck here.
I created 3 files
1. HTML File with code:
<html>
<head>
<script language="javascript" src="../AjaxLearning.js">
</script>
</head>
<body>
<div id="gethelp">
<h3>Text should Change</h3>
</div>
<input type='button' onclick='knowYourBrowser()'
value='Know Your Browser'>
<input type='button' onclick='loadXMLDoc()' value='Need Help?'>
</body>
</html>
A Text file placed at same directory where the html file is placed
text in the file is:
I am here to help you
A java script file placed at a location above the html file
function knowYourBrowser()
{
alert("I reached here");
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
alert ("IE7+, fox, chrome, netscape");
}
else
{
alert ("IE5, 6");
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
/* Read a text file from the directory*/
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('gethelp').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","Help.txt",true);
xmlhttp.send(null);
}
but I am getting the below error message
SCRIPT5: Access is denied.
AjaxLearning.js, line 39 character 2
I dont know what I am missing here. Please point out the gaps.
Thanks in Advance
Himanshu
Hosted the file on xampp and tried to read the file from the server itself. It worked. Looks like IE has issues reading local resources.

Javascript code using xhr is not working?

Below is the response from server (as per google chrome rest-client):
Below is the code snippet I'm using to post some data to our server. I want to get back data as xml ouput.
Keeping in mind the concept of same origin policy i uploaded this piece of code onto our sever as a html page, but not getting any response.
Is there anything wrong with my code or is my approach wrong?
<html>
<head>
<script type="text/javascript">
function getToken()
{
var xmlhttp;
var txt,x,i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert("stage 1");
xmlhttp.onreadystatechange=function()
{
alert("stage 2");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("stage 3");
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("token");
alert("stage 4");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("myDiv").innerHTML=txt;
}
}
alert("stage 5");
xmlhttp.open("POST","http://abc.mysite.com:9090/myapi/xxx",true);
xmlhttp.send("op=login&pass=xxx");
}
</script>
</head>
<body>
<center><h2>UserPreview:</h2></center>
<br />
<div id="myDiv"></div>
<br />
<button type="button" onclick="getToken()">GetToken</button>
<div data-role="footer" data-position="fixed" data-theme="a"><h4>Ver: 1.1(17112)</h4> </div>
</body>
</html>
<response><token>8768768768768768</token></response>
You have to take into account that: for AJAX calls, you can only access the same hostname (and port / scheme) as your page was loaded from. The same domain always and the same PORT:
How exactly is the same-domain policy enforced?
In the past I use this for the IE version, I suppose for possible compatibility issues:
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
I always put the code like this:
var THEURL="http://mysite.abc.com:8080/myapi/xxx"
var data="op=login&pass=xxx";
http.open("POST",THEURL, true);
http.onreadystatechange = function(){
};
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", data.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(data);
Can't you use jquery? It is much more efficient.
To make an ajax call:
http://api.jquery.com/jQuery.ajax/
For example:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
The sooner you use Jquery the sooner your work will get faster.
If the element called token in your xml file is an xml element, and not an attribute then you replace the following lines by -
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
by -
txt += (window.ActiveXObject)?x[i].childNodes[0].text : x[i].childNodes[0].textContent;
I didn't ask you wheter your XHR is returning you the XML properly or not.

Problem with Sending XML Requests

Writing a basic XML file reader into an HTML page. I am having trouble reading from the XML file. Here's my set up: I have three text fields and a button. When the button is pressed, the request is put in to grab three pieces of XML and to populate the three text fields. However, I am running into trouble with the status of the request. I am getting the status code 0, instead of 200. According to my research (http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/282972), I think it has to do with cross domain blocking. I have tried putting the source XML both locally and on a server.
<html>
<head>
<script type="text/javascript">
function displayQuotes()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
//if (xmlhttp.readyState==4 && xmlhttp.status==200)
//{
document.getElementById("quote1").innerHTML=xmlhttp.status;
  //}
}
xmlhttp.open("GET","http://filebox.vt.edu/users/yiuleung/project5/letter.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("quote1").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("quote2").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("quote3").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body>
<div id="quote1" style="margin:0;padding:0;position:absolute;left:65px;top:319px;width:250px;height:16px;text-align:left;z-index:2;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 1</font></div>
<div id="quote2" style="margin:0;padding:0;position:absolute;left:65px;top:389px;width:250px;height:16px;text-align:left;z-index:3;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 2</font></div>
<div id="quote3" style="margin:0;padding:0;position:absolute;left:65px;top:458px;width:250px;height:16px;text-align:left;z-index:4;">
<font style="font-size:13px" color="#000000" face="Arial">Quote 3</font></div>
<input type="button" id="shuffle_button" name="" value="Shuffle" onClick=displayQuotes() style="position:absolute;left:316px;top:228px;width:96px;height:25px;font-family:Arial;font-size:13px;z-index:10">
</body>
</html>
You use xmlhttp.open("GET","letter.xml",true); - it open XMLHttpRequest in async mode. But next two lines of your code expected to work in sync mode. You need to switch to sync mode: xmlhttp.open("GET","letter.xml",false); or (better) to modify code for work in async mode, as in example below:
function displayQuotes()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","letter.xml",true);
xmlhttp.onreadystatechange=function() {
console.info(xmlhttp.readyState,"|",xmlhttp.status,"|",xmlhttp.statusText); // for debugging only
if(xmlhttp.readyState===4&&xmlhttp.status===200) {
// HTTP OK
xmlDoc=xmlhttp.responseXML; // maybe var xmlDoc ???
document.getElementById("quote1").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("quote2").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("quote3").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
};
xmlhttp.send(null);
}
Using XMLHttpRequest in MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Sending GET and POST AJAX requests at the same time

i just would like to know if it is possible sending GET and POST AJAX requests at the same time and if it is how to do it using the XMLHttpRequest object.
Thanks all for helping :D
Send the request as a POST. An HTTP request can only have one method, but nothing is stopping you from using parameters on a POST URL.
If you POST to http://example.com/form?foo=bar, you'll still be able to access foo as a GET parameter.
Here's an example using jQuery:
$.post("http://example.com/form?" + $.param({foo: "bar"}), {text: tinyMCEBody})
Without jQuery, that would look more like this:
…
request.open("POST","form?foo=bar",true);
request.send("text=" + encodeURIComponent(tinyMCEBody));
…
Do you mean you'd like to send some query string values along with your POST? Surely it's just a case of appending them the post URL?
Could you just make two instances of the XMLHttpRequest? So you could have:
Get
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp1=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function()
{
if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp1.responseText;
}
}
xmlhttp1.open("GET","ajax_info.txt",true);
xmlhttp1.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
POST
<html>
<head>
<script type="text/javascript">
function loadXMLDoc2()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp2.responseText;
}
}
//Set POST params
var params = "lorem=ipsum&name=binny";
xmlhttp2.open("POST","ajax_info.txt",true);
xmlhttp2.send(params);
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc2()">Change Content</button>
</body>
</html>
All I changed was the name of the object xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP") and xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP")
Taken from W3Schools
http://www.w3schools.com/ajax/default.asp

Categories

Resources