Can't get HTTP 201 response - javascript

I am trying to get HTTP 201 response from this code but I can't get. Please help me in solving the problems related to this code.
<html>
<body>
<center>
<h2>PAY</h2>
<div id="demo">
<button type="button" onclick="lol()">payhere</button>
</div>
<script>
function lol() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 | this.status == 201) {
document.getElementById("demo").innerHTML = alert(this.responseText);
}
};
xhttp.open("GET", "https://api.test.com/cors", true);
xhttp.withCredentials = true;
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send(JSON.stringify('{"returnUrl":"x","cancelUrl":"x","offerCredit":false,"experienceProfile":{"brandName":"test.com","noShipping":"true","addressOverride":false},"testLibraryVersion":"test/web/3.31.0","_meta":{}'));
}
</script>
</body>
</html>
Thanks

Http status in the form 2xx are really not something to be wished at client side. It is a response code that is sent by server depending on how it's coded there. 201 mainly means created but I can return 200 instead saying a Ok meaning whatever the code was supposed to do has been done. The error normally occurrs when there are missing headers or the content you sent is not correct. Please add accept header in your code like below:
xhttp.setRequestHeader("Accept", "application/json");

Related

Cross-Origin request blocked while Access-Control-Allow-Origin:* still reflect in the response

I found an endpoint that appears to be vulnerable to CORS misconfiguration and I tried this POC:
<html>
<body>
<div id="poc">
<button type="button" onclick="cors()"></button>
</div>
<script>
function cors() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("poc").innerHTML = alert(this.responseText);
}
};
xhttp.open("GET", "https://somedomain.com/vulnerable/endpoint", true);
xhttp.withCredentials = true;
xhttp.send();
}
</script>
Those headers are reflected in the response :
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
if the user is unauthenticated it returns 401 by default
why am I getting my request blocked?
If you are sending this from localhost, the client is running http.But it's requesting a https server.That's why it's showing the errors.However, you can disable CORS checking in chrome.
https://alfilatov.com/posts/run-chrome-without-cors/

Maintaining authentication using API and xhr

I'm getting to grips with using an API to display the data on a page refresh. SO the first part is to authenticate using form based authentication. So I have this:
<html>
<head>
<script type="text/javascript">
function CallWebAPI()
{
var request = new XMLHttpRequest(), data = 'username=admin&password=admin';
request.open('POST', 'https://localIP:8443/api/users/_login', true)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
request.setRequestHeader("Accept", "application/xml")
request.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
//}
}
request.send(data);
}
</script>
</head>
<body>
<div>
<div id="response">
</div>
<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />
</body>
</html>
So from the above, in the console browser I return a proper authentication message as thus:
SUCCESS
So I want to run another function to retrieve data now I'm logged in but it seems to reset back to 'unauthorised. All I did was create another function exactly the same except it was a GET rather than POST and added another button to test it. But it just kept returning 401: unauthorised. Am I doing it in the incorrect order or something?
I insert a second function like this:
function getChannelStats()
{
var stats = new XMLHttpRequest();
stats.open('GET', 'https://localIP:8443/api/channels/statistics?channelId=f237ae66-6c5b-4ffa-9396-0721eb575184', true)
stats.setRequestHeader("Accept", "application/xml")
stats.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(stats.responseText);
//}
}
stats.send();
}
request.send(data);
}
And add another button that class that function to get the responseText. I'm expecting an xml message with various numbers in it. But when I try to run it, it asks for me to authenticate - like it's not retaining it?

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Post form data to php without page refresh

I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.
<form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>
<script>
function posttophp() {
var xhttp = new XMLHttpRequest();
xhttp1.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("submitform").innerHTML = this.responseText;
}
};
xhttp.open("POST", "options.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("
function_Options1[]=function[]")
}
</script>
In php, I store function_Options1[] in another variable and use further.
Two ideas to try:
Maybe the script should be placed before calling the function, but not sure about this.
Try onclick="posttophp();"

How can I have a double Ajax request?

I have a problem: I'd like to have a double Ajax request, but I can't.
For example I have a page in PHP (rand.php) which returns a random number.
Code:
<?php
$rand = rand(0,10);
echo $rand;
?>
In an other page I want to create an Ajax request which get a random number from rand.php twice and write it in different div.
<head>
<script type="text/javascript">
http = new XMLHttpRequest;
function rando(div){
http.onreadystatechange = function(){
if (http.readyState == 4 && http.status == 200){
document.getElementById(div).innerHTML = http.responseText;
}
}
http.open("GET","rand.php",true);
http.send();
}
</script>
</head>
<body>
<div id="div1"></div><br />
<div id="div2"></div><br />
<button onclick="rando('div1');rando('div2')">Randomize!</button>
</body>
It doesn't work. Help me, please!
Yeah, as others have pointed out, your http is shared between all callers to rando. You should create a new one inside rando.
As an aside, that wont work on all browsers. You need to create a different type of http request object on early versions of Internet Explorer.
You have to initialize XMLHttpRequest every time you want to call rand.php:
<head>
<script type="text/javascript">
function rando(div)
{
var http = new XMLHttpRequest;
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
document.getElementById(div).innerHTML = http.responseText;
}
}
http.open("GET","rand.php",true);
http.send();
}
</script>
</head>
<body>
<div id="div1"></div><br />
<div id="div2"></div><br />
<button onclick="rando('div1');rando('div2')">Randomize!</button>
</body>

Categories

Resources