Answer the question
In order to leave comments, you need to log in
Ajax page auto-refresh how to fix error?
//Объект XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
//Получаем объект XMLHttpRequest
function createXmlHttpRequestObject(){
var xmlHttp;
//Если исп IE
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
//Если другой браузер
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
//Если не получилось создать объект XMLHttpRequest
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
//Делаем HTTP - запрос
function ajax()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
//Получаем имя юзера,в форме полю ввода присвоено имя Name
name = encodeURIComponent(document.getElementById("Name").value);
//передаем введенное имя сценарию ajax.php
xmlHttp.open("GET", "ajax.php?name=" + name, true);
xmlHttp.onreadystatechange = processServerResponse;
//делаем запрос к серверу
xmlHttp.send(null);
}
else
//Если соединение занято , делаем повтор через 1 секунду
setTimeout('ajax()', 1000);
}
//Эта фнкция выполняется автоматически при получении ответа от сервера
function processServerResponse()
{
if (xmlHttp.readyState == 4)
{
// статус 200 - транзакция прошла успешно
if (xmlHttp.status == 200)
{
//Извлекаем XML , которые мы получили от сервера
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
helloMessage = xmlDocumentElement.firstChild.data;
//Обновляем страницу - выводим полученный от ajax.php результат
//В див с именем OurMessage
document.getElementById("OurMessage").innerHTML = '<i>' + helloMessage + '<i>';
//перезапуск через 1 секундну
setTimeout('ajax()', 1000);
}
//Если статус <> 200, значит , произошла ошибка
else
{
alert("Ошибка доступа к серверу: " + xmlHttp.statusText);
}
}
}
<?php
//XML output
header('Content-Type: text/xml');
//XML header
echo "<? xml version="1.0" encoding="UTF-8" standalone="yes" ?>";
// print the <response> element
echo '<response>';
// получаем имя юзера
$name = $_GET['name'];
echo htmlentities($name) . ', хорошего Вам дня!';
//конец <response>
echo '</response>';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
Введите ваше имя:
<input type="text" id="Name">
<input type="button" value="submit" name="mySubmit" onclick="ajax();">
<div id="OurMessage"></div>
<script src="ajax.js"></script>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
this is just so wrong
//перезапуск через 1 секундну
setTimeout('ajax()', 1000);
You have a bunch of mixed code, in which you probably don't understand what's going on. Try to simplify and minimize everything. To make a simple request, look at what answers come in, try to process them, and so on. For example, here is a piece of code that will send a request to the server once a second and receive data, so insert them where necessary. In case of any errors, a message will be displayed in the console, but the code will continue to work.
async function update() {
try {
const name = encodeURIComponent(document.getElementById("Name").value);
const response = await fetch("ajax.php?name=" + name);
const text = await response.text();
document.getElementById("OurMessage").innerHTML = '<i>' + text+ '<i>';
}
catch (err) {
console.warn(err);
}
setTimeout(async () => await update(), 1000);
}
(async () => {
await update();
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question