I'm attempting to create a dashboard that logs into an API then refreshes certain data elements that is fully automated. I can login and authenticate but after googling unsure how to 'chain' the GET request after the 'POST'
I've tried watching a few youtube tutorials and creating functions, attaching them to buttons and divs but I just can't get the data to display. The first batch of code completes and logs in OK, but then sits there and times out. I tried just adding a second open and making the login synchronous but it failed
<script type="text/javascript">
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send();
I'm expecting the login to be done behind the scenes and not visible, and just have the GET request show data in a div (I'll try and tidy up the xml response when I get the data working first).
In your code you never use your data variable :
const xhr = new XMLHttpRequest();
var data = 'username=user&password=password';
xhr.onreadystatechange = function()
{
if (xhr.readyState == "4")
{
if (xhr.status == "200")
{
console.log(xhr.responseText);
}
if (xhr.status = "404")
{
console.log("FnF");
}
}
}
xhr.open('post','https://apiServer:8443/api/login', true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.setRequestHeader("Accept", "application/xml")
//xhr.open('get', 'https://apiServer:8443/api/resource/items', true);
xhr.send(data); // <====== HERE
Related
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.
So here is my request in javascript:
var requestGenre = new XMLHttpRequest();
requestGenre.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
//loadMovieList(this.responseText);
console.log(this.responseText);
}
};
requestGenre.open("POST", "MovieGenre.php", true);
requestGenre.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
requestGenre.send("requestedGenre="+e.target.innerText);
}
The Problem:
In this.responseText i do get the exact data that I need but only after the complete html of the MovieGenre.php page.
I don't understand what im missing I've done the same request in other pages and it worked.
Any help is greatly appreciated!
I have two AJAX calls, one in native JavaScript and another with JQuery, which call a PHP Script. The JQuery one is working, but the JavaScript one not. Here goes the code:
JQuery:
$.ajax({
url: "/Tests/index.php",
method: "POST",
data: {'Id': "2"}
});
Native JavaScript:
var Data = {Id: "2"};
XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.send(JSON.stringify(Data));
PHP Script:
echo var_dump($_POST);
The one with JQuery returns 2, but the JavaScript one, doesn't return anything. All the data is seen through the console of the web browser.
Try this code:
var Data = {"Id": "2"};
var XHR = new XMLHttpRequest(); // declared XHR var
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.send(Data); // sending data without converting to string
Reference: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
I'm learning and trying to write a simple stock quote tool using Python-Flask and Javascript.
I specifically want to learn plain Javascript. My code is working, but what I don't understand is when I'm watching the developer console, I get 3 error messages printed before I get the successful console.log(response).
Is it simply that the code loops 3 times before the response comes back, so it logged 'ERROR' each of those times before finally returning the 200 status? Would someone explain it to me or point me to a good article/post?
My event listener:
document.getElementById("btn_quote").addEventListener("click", getQuote);
The ajax call:
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value
var shares = document.getElementById("shares").value
var url = "/quote/"+ticker+"/"+shares
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
console.log(response);
}
} else {
// TODO, handle error when no data is available.
console.log('ERROR');
return false;
}
};
request.open('GET', url);
request.send();
}
It's not returning separate HTTP status codes, its returning different ready states.
Change your console.log("ERROR");. To console.log(request.readyState);.
Then you will see what it is reporting and why.
i think you should be checking your readyState values with the actual values of the response. For you reference, following are the possible values of readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
So you could basically check it to be 4 in your case:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
//response statements
} else {
//error statements
}
};
Basically, ajax calls will get notified for the following events which is called as readyStateChange event.
For most cases, you used to get 4 ready state changes based on the speed of the connection (rare cases only only one if it's very quick) and you should check whether it is 4 which means the response is completed now.
To check whether the request is suceess or not, you should check the request.status === 200 which means success and can check for other http status code for errors like 404, 500 etc.
document.getElementById("btn_quote").addEventListener("click", getQuote);
document.getElementById("btn_quote_error").addEventListener("click", getQuoteError);
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
function getQuoteError(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow404.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
<input type="text" id="ticker"/>
<input type="text" id="shares"/>
<input type="button" id="btn_quote" value="Get Quote" />
<input type="button" id="btn_quote_error" value="Get Quote Error" />
I have a js file, containing a folder myFunc(phone_number)
Now when this js function is called, I want to make a POST request to the URI https://pay.something.in:443/FetchPhone/ passing the json {'phone_number' : 10 digit phone no. } as input to the request
and show its output in a new window.
Can somebody tell me how do I do that?
Seems to me like you want to make a POST request with xhr.
var xhr = new XMLHttpRequest();
xhr.open('POST', "https://pay.something.in:443")
xhr.setRequestHeader("Content-type", "application/json");
xhr.send( '{"phone_number" : 4455566677 }' );
xhr.onreadystatechange = function(){
if (xhr.readyState != 4) return;
if (xhr.status != 200 && xhr.status != 304) {
alert('HTTP error ' + req.status);
return;
}
console.log(xhr.responseText);//this is your response
window.sessionStorage['response'] = xhr.responseText;
window.open('Your window');//The data is accessible through sessionStorage.
}