How to forward content to log server with XMLHttpRequest()? - javascript

I'm trying to log the content from alert(allText); to another server, for example, www.otherwebsite/logger?log=allText() without the alert msg that is current popping.
In other words, how can I generate another request to a log server with the information of allText using XMLHttpRequest?
I'm currently using this script to load the content but I'm not sure how to generate another request to my log server with allText
<script>
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
readTextFile("http://null.jsbin.com/runner");
</script>
For testing, I was running the script with jsbin.com
Any advice and suggestions will be greatly appreciated.

Make a nested Post call to the api to which you want to post data:
<script>
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request finished. Do processing here.
}
}
xhr.send(allText);
}
}
}
rawFile.send(null);
}
readTextFile("http://null.jsbin.com/runner");
</script>

Related

JS: HTML is not dynamically changing

I am building an web that allows user to like a post when they click a button. CreateLike function calls API and creates a like object however, I would like to have the number of likes updated right away without reloading. I built another API that returns the number of likes for a post. Function LikeCount should put the number of likes into the p tag. It works initially when I load the page however, the value does not change when I click the button even though I can see that the API is called. (After reloading the page the number changes as expected) What am I doing wrong?
I have this HTML:
<p class="like-count" id={{post.id}}></p>
<script>LikeCount({{post.id}});</script>
<button type="button" class="btn-like" onclick="CreateLike({{user.id}},{{post.id}})"></button>
with JS functions:
function CreateLike (userid,postid) {
xhr = new XMLHttpRequest();
var url = "{% url 'likes' %}";
var csrftoken = getCookie('csrftoken')
xhr.open("POST", url, true);
xhr.setRequestHeader("X-CSRFToken",'{{ csrf_token }}')
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({csrfmiddlewaretoken:csrftoken,"user":userid,"post":postid});
xhr.send(data);
LikeCount(postid);
}
function LikeCount(postid) {
var xmlhttp = new XMLHttpRequest();
var url = "{% url 'likecount' id=112233 %}".replace("112233", postid);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = arr.like_count;
document.getElementById(postid).innerHTML = out;
}
}
Like count API looks like this:
{
"like_count": 1
}
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
LikeCount(); //Put your get like count here
} else {
// Handle Errors
}
}
Call LikeCount only after receiving the response of your POST request. Right now you're immediately sending a GET request without ensuring if the previous POST request got completed.
Added
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
var myArr = JSON.parse(this.responseText);
LikeCount(myArr.post);
}
};
before
xhr.send(data);
and it fixed the issue.

Can't receive in javascript XMLHttpRequest response from java server

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");
}
}
}
}

Download file from Dropbox using javascript dropbox api

I tried to download a file from Dropbox using Core Api with javascript.
Here is the method I have written.
function downloadFile(path) {
var url = "https://api-content.dropbox.com/1/files/auto/"+path;
var result;
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.send(path);
}
But I am always getting the status as 400. Don't know whats wrong. I got this below HTML as response.
<html>
<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx</center>
</body>
</html>
Edit 1 :
var url = "https://api-content.dropbox.com/1/files/auto/" + path;
var result;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
result = xhr.responseText;
}
}
xhr.open("GET", url, true);
xhr.setRequestHeader("access_token",token);
xhr.send();

cannot reach readystate=4

I go this AJAX code that worked fine, but when I moved it to a new file it stopped working.
I managed to find out that the readystate isn't 4 and status isn't 200.
The code was given to my in class by the teacher. It worked find until I made new file.
<script type = "text/javascript">
var request = false;
if (window.XMLHttpRequest)
request = new XMLHttpRequest();
else if (window.AciveXObject)
request = new ActiveXObject("Microsoft.XMLHTTP");
function login(PhpFile,divId,frm)
{
if (request)
{
var obj = document.getElementById(divId);
request.open("POST",PhpFile);
//setting the header
request.setRequestHeader('Content-Type','application/x-www-form- urlencoded');
request.onreadystatechange = function()
{
if (request.readyState == 4 &&
request.status == 200){
obj.innerHTML =request.responseText;
}
else
{
alert("here");
}
}
request.send("log="+frm.log.value+"&pwd="+frm.pwd.value);
}
}
</script>
if you alert(request.responseText) in that else case, that may give you more information
'application/x-www-form- urlencoded'
should be
'application/x-www-form-urlencoded'

Using XMLHttpRequest for Mozilla Extension development

I have some problems of calling a php file using Ajax in my
Mozilla Extension.
The javascript (Ajax) and php are both located at directory /myextension/content, I am call the php using
function ajaxFunction(){
var req = new XMLHttpRequest();
req.open('GET', 'myphp.php', true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
alert(req.responseText);
else
alert("Error\n");
}
};
req.send(null);
}
, and my php looks like
<? php
echo "Server Received with thanks!";
?>
I keep geting "alert("Error\n");".
Did i do anything wrong?
Well formatted Ajax code for Firefox:
var URL="http://yourdomain.com/Work.php?val=Test";
var objXmlHttp = null;
try
{
objXmlHttp = new XMLHttpRequest();
}
catch(e)
{return;}
objXmlHttp.onreadystatechange=function()
{
if ((objXmlHttp.readyState == 4 || objXmlHttp.readyState == "complete") && objXmlHttp.status == 200)
{
//Write code for success
}
else if (objXmlHttp.status == 404)
{
//OnError
}
else
{
//OnWait
}
}
objXmlHttp.open("GET", URL, true);
objXmlHttp.send(null);

Categories

Resources