Resposexml returns null value - javascript

I am new to ajax. I wanted to create a simple webpage where it contains a button if clicked returns image dynamically.But the responseXML returns null value. Here is part of javascript code:
function process()
{
if(xmlhttp.readyState==4 || xmlhttp.readyState==0)
{
xmlhttp.open("GET","image.php",true);
xmlhttp.onreadystatechange = handleserverresponse;
xmlhttp.send();
}else{
setTimeout('process()',1000);
}
}
function handleserverresponse()
{
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
xmlResponse = xmlhttp.responseXML;
imag = xmlResponse.documentElement.firstChild.data;
document.getElementById("divimg").innerHTML=imag;
}
else{
alert("something went wrong");
}
}
here is php code:
<?php
header('Content-Type:text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo "<res>";
echo "<img src="a.jpg"/>";
echo "</res>";
?>

Your HTTP request is asynchronous. xmlhttp.responseXML won't have some value until xmlhttp.readyState has the value of 4.
var url = "http://localhost/xml.php?type=xml";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseXML);
}
};
xmlhttp.send();
}
Additionaly, I don't think you need the setRequestHeader line. XML MIME type is required for response, not for request. Also, please respect good coding practices (don't forget var, DRY, etc.)

The reason responseXML was null because there is a mistake in PHP file.
I guess We cannot send HTML tags when content type is xml. Instead what we can do is echo source of image and modify JavaScript file to take that source and display using img tag.

Related

syntax error from external javascript

I'm trying to call an external .js file which will place text into one of my 's.
The script works perfectly when included in the index.php, but when using the following:
<script src="js/updates.js"></script>
into the index.php, it returns a syntax error in the updates.js.
<script type="text/javascript">
xmlhttp = new XMLHttpRequest();
setInterval(chatStatus(),3000);
function chatStatus()
{
xmlhttp.onreadystatechange =
function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status==200)
{
document.getElementById('chatStatus').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "phprequests/chatStatus.php", true); <------ this line returns syntax error.
xmlhttp.send();
}
</script>
Any help is appreciated. How comes this returns syntax error outside of the index.php file?
Removing the script headers from the external .js file solved the issue.
xmlhttp = new XMLHttpRequest();
setInterval(chatStatus(),3000);
function chatStatus()
{
xmlhttp.onreadystatechange =
function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status==200)
{
document.getElementById('chatStatus').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "phprequests/chatStatus.php", true); <------ this line returns syntax error.
xmlhttp.send();
}

Ajax in timer is affecting my server

I am using ajax so that i can read the content of a file from my server .I am calling a function where ajax is , in a timer.And this is affecting my server .It is crashing.If this is the correct way to do it , what's wrong?
Please give a few sugestions,because i don't know what its problem is.
I am calling first the function:"function(ctrl)".
function get(ctrl){
var content;
content=ctrl.id;
var getTextUpdate= setInterval(function () {
readdocument();
}, 1200);
}
function readdocument() {
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("area").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../user/test/read-text.php?user="+content,true);
xmlhttp.send();
}
Here it is the read-text.php file:
<?php
$rec_user=$_GET['user'];
echo($rec_user);
$chat = fopen($rec_user.".txt", "r") or die("Unable to open file!");
echo fread($chat,filesize($rec_user.".txt"));
fclose($chat);
?>
The problem with your code is that, you are not waiting for the response to get over. So over the time, you are sending request after request. This is going to use up all memory in due time. So first wait for the response before sending the next request.
How about this ?
function loadXMLDoc(ctrl) {
var content=ctrl.id;
var xmlhttp = new XMLHttpRequest();
var url = "../user/test/read-text.php?user="+content;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("area").value=xmlhttp.responseText;
setTimeout(loadXMLDoc(), 1200); //call the function again
} else if (xmlhttp.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
loadXMLDoc(ctrl);

Difficulty in handling the ajax call

I have a problem in which I am calling a url through ajax, but I am having some problem in handling the response.
The url is returning the response, when I directly call it from the browser, but when I am using it in my ajax call I am having some problem in handling it.
I have used both the property(responseText and responseXML) of the XMLHTTPREQUEST object.
my code is::
function postRequest(strURL)
{
var xmlHttp;
if (window.XMLHttpRequest) // Mozilla, Safari, ...
{
var xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) // IE
{
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'text/html; charset=ISO-8859-1');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
alert("Status =4");
alert(xmlHttp.responseXML);
alert(xmlHttp.responseText);
}
}
xmlHttp.send(strURL);
}
The url is:: http://www.amazon.com/gp/aag/ajax/paginatedFeedback.html?seller=A3QGTRL0G4B98R&isAmazonFulfilled=&isCBA=&marketplaceID=ATVPDKIKX0DER&asin=&ref_=aag_m_fb&&currentPage=1
Please suggest anything.
I think that you can't make calls to another domain. You can read more about AJAX Cross-Domain in G

Ajax resending XMLHttpRequest

I've got a client side js/ajax script like this:
<p>server time is: <strong id="stime">Please wait...</strong></p>
<script>
function updateAjax() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==3 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
}
if (xmlhttp.readyState==4) {
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
}
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
window.setTimeout("updateAjax();",100);
</script>
And a on the server side:
<?php
echo 6;
for ($i=0; $i<10; $i++) {
echo $i;
ob_flush(); flush();
sleep(1);
}
?>
After first 'open' and 'send' it works ok, but when the server finishes the script and xmlhttp.readyState == 4 then the xmlhttp resends the request but nothing happens.
Instead of re-using the same XHR object all the time, try repeating the function with a new object. This should at least fix incompatibility issues as you listed.
Try re-calling your Ajax function inside the callback of it, if you want to loop it infinitely.
if (xmlhttp.readyState==4) {
updateAjax(); //or setTimeout("updateAjax();",100); if you want a delay
}
I'd also suggest putting your .innerHTML method inside the .readyState==4, which is when the requested document has completely loaded, and .status==200 which means success. Like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
updateAjax(); //or setTimeout("updateAjax();",100);
}
Also, if you want your Ajax to be cross-browser, you should test if the browser supports the XHR object which you're using:
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
I just typed the code above but it should work just fine to add compatibility with older versions of IE and other browsers.

Problem in getting Http Response in chrome

Am trying to get http response from php web service in javascript, but getting null in firefox and chrome. plz tell me where am doing mistake here is my code,
function fetch_details()
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest()
alert("first");
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP")
alert("sec");
}
xhttp.open("GET","url.com",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;
alert(xmlDoc.getElementsByTagName("Inbox")[0].childNodes[0].nodeValue);
}
I have tried with ajax also but am not getting http response here is my code, please guide me
var xmlhttp = null;
var url = "url.com";
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
alert(xmlhttp); //make sure that Browser supports overrideMimeType
if ( typeof xmlhttp.overrideMimeType != 'undefined')
{
xmlhttp.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert('Perhaps your browser does not support xmlhttprequests?');
}
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4)
{
alert(xmlhttp.responseXML);
}
};
}
// Make the actual request
xmlhttp.send(null);
I am getting xmlhttp.readyState = 4 xmlhttp.status = 0 xmlhttp.responseText = ""
plz tell me where am doing mistake
Your doing a cross domain request.
You are only allowed to do xmlhttp requests to the same host.
I can't read any of that but Chrome has a JavaScript console that will probably tell you what you're doing wrong.
It's a cross-domain issue, to resolve it the server response header should contain "access-control-allow-origin"
If your server is coded in PHP, the header should be like the following example:
<?php
header('Content-type: text/html');
header('Access-Control-Allow-Origin: *');
$uri = 'http'. ($_SERVER['HTTPS'] ? 's' : null) .'://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
echo('<p>This information has come from ' . $uri . '</p>');
?>

Categories