PHP to javascript JSON.Parse twice - javascript

I have this in PHP
$invalid_code_msg = ['error' => 'Invalid purchase code. Please double check your purchase code and try again!'];
throw new Exception(json_encode($invalid_code_msg));
In js:
var xhr = new XMLHttpRequest;
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.onreadystatechange = function () {
if (this.readyState === 4){
if (this.status === 200) {
var data = JSON.parse(xhr.responseText);
console.log(data, data.error)
//here data is still a string unless I parse it twice?
}
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("pc=" + purchase_code.value);
I am trying to figure out why data is still a string unless I parse it twice?
data is still a string after first JSON.parse
{"error":"Invalid purchase code. Please double check your purchase code and try again!"}

Related

I am trying to make a post request using javascript to my fast api app. But it is giving error INFO. 422 Unprocessable Entity

// variables for getting Original URL
const form2 = document.getElementById("form2");
const resultContainer2 = document.querySelector(".result__container2");
const longUrl = document.querySelector(".longurl");
//for decoding the url (Retrieving Original URL)
form2.addEventListener("submit", (e) => {
e.preventDefault();
var formData = new FormData();
formData.append("shortUrl", e.target.shortUrl.value);
formData.append("customCode", e.target.shortUrl.value);
let data = {}
for(let pair of formData.entries()) {
data[pair[0]] = pair[1]
}
console.log(data)
let xhr = new XMLHttpRequest();
xhr.open("POST", "/api/v2/original", true);
// Set the request header
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log("Done")
}
}
//Displaying the Original long URL
xhr.onload = function () {
const response = JSON.parse(this.responseText);
console.log(this.status);
console.log(response);
if(this.status ==200) {
resultContainer2.style.display = "flex";
longUrl.innerHTML = `ORIGINAL LONG URL :- <a href=${response.longUrl}>${response.longUrl}</a>`
}
else {
alert(`An error occurred, ${response.detail}`)
}
};
//using JSON for transfering data in between, as per task requirement (JSON Object to JSON string)
xhr.send(JSON.stringify(data));
})

Javascript API polling

I have RestAPI endpoint providing simple response with single flag "needUpdate" true/false.
I am trying to write Javascript polling function which calls this endpoint and in case that needUpdate=true, it reloads whole web page.
var url = "https://www.example.com/api";
var needUpdate;
function poll(){
setTimeout(function(){
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function(e) {
if (this.status == 200) {
const myObj = this.response;
var needUpdate = myObj["needUpdate"];
console.log('needUpdate', needUpdate); // console
}
};
xhr.send();
if(needUpdate == true){
location.reload();
} else {
poll();
}
}, 3000);
}
var json = JSON.stringify(poll());
It calls API every 3 seconds as expected and also states proper value of needUpdate into console. But reload does not happen.
It seems that needUpdate value is actualy undefined on the place where I tried to set a condition.
Can you please help me?
move condition inside xhr.onload function
var url = "https://www.example.com/api";
var needUpdate;
function poll(){
setTimeout(function(){
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function(e) {
if (this.status == 200) {
const myObj = this.response;
var needUpdate = myObj["needUpdate"];
console.log('needUpdate', needUpdate); // console
if(needUpdate == true){
location.reload();
} else {
poll();
}
}
};
xhr.send();
}, 3000);
}
var json = JSON.stringify(poll());

Byte array from backend is converted to something else on front-end

[Route("encrypted")]
[HttpGet]
public sbyte[] Encrypted()
{
var mm = System.IO.File.ReadAllBytes("C:\\test\\" + "fill.txt");
sbyte[] sbt = new sbyte[mm.Length];
Buffer.BlockCopy(mm, 0, sbt, 0, mm.Length);
return sbt;
}
when I hover over with mouse it shows following bytes (which is correct):
But when I check on the front-end (javascript). It becomes a different arrayBuffer:
Here is the front end code:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/encrypted/', true);
xhr.responseType = 'arraybuffer'; //i have tried without this line too
xhr.onload = function (e) {
if (this.status === 200) {
console.log("received from server--------");
console.log(e.currentTarget.response);
console.log("received from server-------");
}
};
xhr.send();
You did not ask a specific question, but I think this might help.
Your controller action is responding with JSON. Dumping json to the console shows the same array values on the front-end as does dumping sbt to the console on the back-end. Here is the front-end code that dumps the values.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/values', true);
xhr.responseType = 'json';
xhr.onload = function (e) {
if (this.status === 200) {
console.log("json");
const json = e.currentTarget.response;
console.log(json);
console.log("json");
}
};
So, you're sending a JSON array.
As an aside, here are some links about the arraybuffer response type.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

AJAX POST request with response

As the title states, I'm looking to make a POST request using JavaScript and also get a response. Here's my current code:
var request = new XMLHttpRequest();
request.open('POST', 'test.php', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success
console.log(request.responseText)
} else {
// Server-side Error
console.log("Server-side Error")
}
};
request.onerror = function() {
// Connection Error
console.log("Connection Error")
};
request.send({
'color':'red',
'food': 'carrot',
'animal': 'crow'
});
With test.php being:
<?php
echo $_POST['color'];
?>
This should return 'red' but instead returns nothing.
This seems like a simple problem but I could only find solutions for people using jQuery. I'd like a solution that does not rely on and libraries.
The send method takes a string rather than an object, perhaps more like:
var request = new XMLHttpRequest();
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
console.log(request.response)
} else {
console.log("Server-side Error")
}
};
request.onerror = function() {
console.log("Connection Error")
};
request.open('POST', 'test.php', true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.send('color=red&food=carrot&animal=crow');
The JavaScript problem
You are trying to send a generic Object, so it gets converted to a String ("[Object object]"), and the data is lost.
Convert the data to a FormData object instead.
var data = {
'color':'red',
'food': 'carrot',
'animal': 'crow'
};
var formData = new FormData();
Object.keys(data).forEach(function (key) {
formData.append(key, data[key]);
})
request.send(formData);
The PHP problem
All of the current solutions simply log the source code of "test.php" to the console as opposed to logging 'red' to the console
This is an issue unrelated to your code. It is also a FAQ. See: PHP code is not being executed, instead code shows on the page

function to return string in javascript

I am trying to call an ajax request to my server for json data using a function. If I console out the resp variable inside the ajax function it will show the data successfully. If i try to set the ajax function to a variable, and then console that variable it returns undefined. Any ideas who to make the function request the data and then set ti to a variable to be consoled?
function jsonData(URL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
return resp;
}
}
xhr.send();
}
jsonString = jsonData(http://mywebsite.com/test.php?data=test);
console.log(jsonString);
This is actually pretty simple.. Change your call to by synchronous..
xhr.open("GET", URL, false);
That being said this will block the browser until the operation has been completed and if you can use a callback instead it would likely be preferred.
function jsonData(URL, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
cb(resp);
}
}
xhr.send();
}
jsonData("http://mywebsite.com/test.php?data=test"
, function(data) { console.log(data); });

Categories

Resources