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.
Related
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.
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
ajax code:
function getdata(str)
{
if (str == "") {
document.getElementById("yer").innerHTML = "";
return;
} else {
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("bus").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo site_url('money_c/taxcalculator1'); ?>?q="+str,true);
xmlhttp.send();
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
}
}
controller:
function taxcalculator1()
{
$bt=$_GET['q'];
echo $bt;
}
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
As soon as you have started the Ajax request sending with this:
xmlhttp.send();
You leave the page with this:
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
… which aborts the Ajax request, removes the place you are trying to edit with innerHTML and destroys the JavaScript that would be trying to do that anyway.
If you want to use Ajax then:
Put the data you want to show to the user the response from taxcalculator1
Use onreadystatechange to show it to the user
Don't leave the page before that happens (remove the window.location line).
If you want to load an entirely new page:
Don't use Ajax
Just submit a form to a URL
Display the data you want the user to see (in the form of an HTML document) in the response to that request
raise.js:
window.onload=init;
function init(){
var submit=document.getElementById("submit");
submit.onclick=sub;
}
function sub(){
var url="raise.php";
var title=document.getElementById("title");//title of a question
var content=document.getElementById("inputContent");//content of a question
var checktype=document.getElementsByName("type");
var type;//type of a question
if(checktype[0].checked){
type="java";
}
else if(checktype[1].checked){
type="c++";
}
else{
type="html";
}
var point=document.getElementsByTagName("select");
var reward=point[0].value;//reward point
url=url+"?title="+title.value;
url=url+"?content="+content.value;
url=url+"?type="+type;
url=url+"?reward="+reward;
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
alert("asde");
}
}
xmlhttp.open("GET",url,true);
xmlhttp.setRequestHeader("Content-Type","utf-8");
xmlhttp.send();
}
raise.php:
<?php
echo "<script>alert('123')</script>";
$title=$_GET['title'];
$content=$_GET['content'];
$reward=$_GET['reward'];
$type=$_GET['type'];
?>
that confuses me alert('123') is not executed but alert("asde") is ,I want to know why..and am I right while trying to retrieve these data with php...I'm not very familiar with ajax...please show me some codes based on my data..thank you very much..
A script element won't do anything unless it is part of a rendered HTML document.
The server returns it to the browser, then it sits in xmlhttp.responseText where you are ignoring it.
(That said, even if you didn't ignore it, you might still have problems).
You simply not attaching the response body (the JavaScript) to your DOM, try:
// ...
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
alert("asde");
alert(xmlHttp.responseText);
// here you have to attach xmlHttp.responseText to your DOM
}
}
// ...
This should alert you "asde" and after that "script>alert('123')/script>"
You better use Jquery with Ajax to POST or GET data instead of only Ajax. You can have a look here jquery ajax. Here you will find out where alert should be used.
got this file 'functions.php':
<?php
function test ($url){
$starttime = microtime(true);
$valid = #fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
echo "Status - Failure";
} else {
echo "Status - Success";
}
}
test('google.com');
?>
I want to run it every 10seconds or so, i was told to use ajax request but i dont completely understand how it works. I tried creating a new file 'index.php', and then had this written in it:
<script>
var milliSeconds = 10000;
setInterval( function() {
//Ajax request, i dont know how to write it
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
</script>
I put both files into ftp but nothing happens, can someone help me write a propper ajax request?
Edit: eddited typo, still doesnt work tho
var milliSeconds = 1000;
setInterval( function() {
var xmlhttp;
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log ( xmlhttp.responseText );
}
}
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
You have to load xmlhttp request object according to the browser ( xmlhttp=new XMLHttpRequest(); ), then set an event handler when the xmlhttp state changes ( xmlhttp.onreadystatechange=function() ). When it changes check if the status is 200 (success) then do whatever you want with the response. ( I printed it to console )
So, it sounds like your only problem is that you don't know how to write an XHR request. Take a look at Using XMLHttpRequest. Comment on this answer with your questions.
xmlhttp.open("POST","funkction.php",true);
should be:
xmlhttp.open("POST","functions.php",true);
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>');
?>