Here is my code in javascript
<script type="text/javascript">
startingListener();
function startingListener() {
setInterval(function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.send();
var result = xhr.response;
console.log(result);
}
}, 100);
}
</script>
And my server on Java
public static void main (String... args) throws IOException, Exception {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(32081);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
System.out.println("begin");
outToClient.println("fu");
System.out.println("Received: done");
}
}
I just want to receive answer string in JS and work with it further.
So when I run server and run JS, they connected and I received in IDE send() from JS
After that I saw in console of Java that begin and done received, but in browser console I didn't see any answer and script just handled. What do I do wrong?
Thank you for your help
Your client code is missing a state change handler and using setInterval with 100 ms it is very heavy on the server. Here is a better JS. Your JAVA issue is another problem. Downvoters: Do comment
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
}
}
listener();
If you want to call listener repeatedly, you can do
function listener() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:32081/", false);
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
if (xhr.responseText != "done") {
console.log("server still busy");
setTimeout(listener,1000); // repeat the call
}
else {
console.log("finally done");
}
}
}
}
Related
I have a problem with uploading a file to a node server via HTML. In the page I have this input:
<input type="file" id = "csvFile" />
<input type="submit" name="submit" onclick="send_data()" />
Then I have the send_data function that looks like this:
function send_data(){
let file = document.getElementById("csvFile");
const xhr = new XMLHttpRequest();
xhr.open("GET", file, true);
xhr.setRequestHeader("Content-type", "text/csv");
xhr.onreadystatechange = () =>{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
console.log("done");
}
xhr.send();
}
Here there is the first problem, because the arrow function of the ready state never executes.
In any case, it's the first time I do something like this, so I don't know how I can make sure that my server gets the file and processes it. Can someone help me?
This should do the trick:
let file = document.getElementById("csvFile").files[0];
let xhr = new XMLHttpRequest();
let formData = new FormData();
formData.append("csvFile", file);
xhr.open("POST", '${your_full_address}');
xhr.onreadystatechange = function () {
// In local files, status is 0 upon success in Mozilla Firefox
if (xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(xhr.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
xhr.send(formData);
Refer: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
I am trying to call web service in html5 javascript. But XMLHttpRequest status value getting ZERO insted of 200 and responseText is empty. help me to solve the issue, My code below
<script type="text/javascript">
var xhr;
function Getdet()
{
try {
xhr = new XMLHttpRequest();
xhr.open('POST', "URL", true); // URL-->Webservice link
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.responseType = 'json';
}
catch(err)
{
alert(err.message);
}
}
function processRequest(e) {
try{
var prn=JSON.stringify(e);
alert("xhr.readyState-->"+xhr.readyState);
alert("xhr.status-->"+xhr.status);
alert("xhr response-->"+ xhr.response);
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.ip);
}
}
catch(err)
{
alert(err.message);
}
}
}
</script>
I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload
I have some issues with async requests. My website and api are on different ports, Access-Control-Allow-Origin header is set on API side correctly (because synchronious requests work just fine).
The following code always returns 'ERR'. I
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert( "ERR" + " Status: " + xhr.statusText + " Response: "+xhr.responseText ); //always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
};
xhr.send();
}
Set a listener for the returned async
function reqListener() {
console.log(this.responseText);
}
function load() {
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", reqListener);
xhr.open('GET', 'http://domain:8801/api/');
xhr.send();
}
Not putting in true/false makes it async by default
SO this is all wrong and the "submit" button is the issue - and the async operates differently - the sync waits for response, THEN submits while the async does not and it never returns prior to the submit action
I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}