cannot reach readystate=4 - javascript

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'

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.

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

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>

AJAX xmlhttp.open sumit data using POST method

I am trying to send a form data using POST method and xmlhttp.open
Please help find the error in my code
function submitChat() {
if (form1.msg.value == '' ) {
alert ('ALL FIELDS ARE MANDATORY');
return;
}
var xmlhttp = new XMLHttpRequest();
var msg = form1.msg.value;
var params = 'msg=helloooooooo';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'rtest.php?rid=14', true);
xmlhttp.send(params);
}
Everything is fine and it is working with GET method. but POST method is not working. Please help.

Display server message after form submission without JQuery

I have a form that is supposed to display a feedback message from the server once it is submitted in <div id="resposta"></div>
I can't use JQuery on my page because it is also using Mootools and it's really a mess to avoid the conflicts with those two (I tried all sorts of things I don't to bother you with). Therefore, I must use pure JavaScript here.
Once the form is submitted (after validation) it calls the function getResposta below:
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
};
function getResposta(){
var resposta = document.getElementById("resposta");
var request = getXmlHttp();
request.open("POST", "thanks.php", true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState != 4) return;
if (request.status == 200) {
resposta.innerHTML = '<p>' + request.responseText + '</p>';
} else {
alert("Erro: "+request.statusText);
}
};
}
}
thanks.php:
<?php
echo "thank you";
?>
It seems that thanks.php isn't being called, although the form is correctly filled in and sent to the server.
I've tried typing in the absolute path to the file but it didn't work. So, what is wrong with this code?
Thanks for any help!

Timeout method after hitting the url

We have the following method to invoke the URL using ajax.
Currently after hitting the url we are using the response.
So we want to put a timeout for reposne.So when we invoke the url if the response didn't came after 2sec then call one more method and if resp comes within two seconds call other mehtod.
We have tried using the timeout,but unable to made it working with the code.
function ajaxCall(url1) {
var ajaxresp = null;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url1, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
ajaxresp = xmlhttp.responseText;
//function call
getAdResponse(ajaxresp);
}
}
}
}
Please advice me how to proceed.
Try smth like this
xmlhttp.open("GET",url1,true);
xmlhttp.onreadystatechange= function (){
if (xmlhttp.readyState==4){
if (xmlhttp.status == 200){
ajaxresp = xmlhttp.responseText;
}
}
xmlhttp.send();
setTimeout(function() {
if(ajaxresp) {
dosmth(ajaxresp);
} else {
dosmthelse();
}
}, 2000);

Categories

Resources