javascript how to parse numbers? - javascript

Hello so i'm trying to parse numbers that i get once i request page using http web request.But it seems that it fails me every time :/
Code that i use to make web request and parse:
var xhr = new XMLHttpRequest();
xhr.open('GET', "website url", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.);
}
}
I don't know what i need to write after dot i tried many options :(
Example of response that i get: {"status":1,"request":"1663758118"}
and i need to get only numbers
Html:
<pre>{"status":1,"request":"1663758118"}</pre>
So if somebody could help that would be great :)

If I understand your question correctly, and your code does correctly parse JSON string into JSON object, then you can do the following to retrieve data from JSON object
response.status // '1' as int
response.request // "1663758118" as string
Hope this answer can help you :)

After dot you need to put the property name in order to get the value.
If you need to convert a string to number you can add a + sign immediately before the string:
var response = JSON.parse('{"status":1,"request":"1663758118"}');
var stat = +response["status"];
var req = +response["request"];
console.log('status is: ' + stat + ' typeof is: ' + typeof stat);
console.log('request is: ' + req + ' typeof is: ' + typeof req);

If you need numbers from your response {"status":1,"request":"1663758118"}, you can use do this
const response = {"status":1,"request":"1663758118"}
const values = Object.keys(response).map(key => parseInt(response[key], 10))
console.log(values) // => [1, 1663758118]

Related

Update DOM with responses from several XMLHttpRequest

I am building a simple open source Chromium extension that retrieve some data from several urls and then update the DOM. I could find another way to do this than by adding the line to update the DOM inside the callback http1.onreadystatechange
My XMLHttpRequest requests were often stuck on http1.readyState = 3 so I have added a 3rd parameter to http1.open("GET"); to make the request synchronous like this:
http1.open("GET", url, false);
But I am still getting these errors:
results[1].join is not a function at XMLHttpRequest.http.onreadystatechange
annot read property 'join' of undefined at XMLHttpRequest.http.onreadystatechange
Even thought they don't prevent the script from running, I think this isn't the right way to do what I want. So here is my question: how to update the DOM with the responses from several XMLHttpRequest request? Let's say I need to retrieve and compare all the data before updating the DOM. Then is there a way to process all the data at once after we have retrieve all of them (cf my comment on the last line)?
Here is the relevant part of my script, the full script is available here:
var urls = [
["https://www.cnrtl.fr/morphologie/" + keyword, "vtoolbar", "morf_sound"], //best for plural
["https://www.cnrtl.fr/synonymie/" + keyword, "syno_format"],
]
// for test set keyword to any of this word : hibou, tribal, aller, lancer
var resultdiv = document.getElementById("result")
resultdiv.innerText = "requete en cours";
var results = [];
var errors = [];
urls.forEach((item, index) => {
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
parser = new DOMParser();
var ulr1response = parser.parseFromString(http.responseText, "text/html");
if (index == 0) {
//retrieve the data needed, save then in a list and push this list to the main list result
} else if (index == 1) {
//retrieve the data needed, save then in a list and push this list to the main list result
}
// update the DOM
if (results[1] == "") {
resultdiv.innerHTML = results[0].join(", ") + "</br></br>Pas de synonymes trouvés"
} else {
resultdiv.innerHTML = "<b>" + results[0].join(", ") + "</br></br>Synonymes:</b></br>● " + results[1].join('</br>● ')
}
} else {
errors.push(index);
resultdiv.innerText = "Erreur: " + index + " " + http.readyState + " " + http.status;
}
}
http.open("GET", item[0], false);
http.send(null); // null = no parameters
});
// it would be simplier if I could update the DOM here and not in http.onreadystatechange
If you want to execute some code once all requests have succeeded, you can try using Promise.all together with Fetch.
let keyword = "beaucoup";
let parser = new DOMParser();
let urls = [
["https://www.cnrtl.fr/morphologie/" + keyword, "vtoolbar", "morf_sound"], //best for plural
["https://www.cnrtl.fr/synonymie/" + keyword, "syno_format"]
];
let fetchPromises = urls.map(
item => fetch(item[0]).then(
response => parser.parseFromString(response.text(), "text/html")
)
);
Promise.all(fetchPromises).then(
results => {
// code in here executes once all fetchPromises have succeeded
// "results" will be an array of parsed response data
console.log(results);
}
).catch(console.error);

special chars are corrupted while sending the request result to another php page for debug

i am trying to create a script that gets the requests in the network tab and sends it to a debug page ,the requests are aes-128-cbc encrypted but they are RAW not base64 so some special chars exist,the problem is that special chars are somehow sent corrupted to the debug page.
for example:
"A test" (without the quotes) is encrypted with
key test1234
and iv 1235569767556087
using the php code
openssl_encrypt("A test",'aes-128-cbc',"test1234",OPENSSL_RAW_DATA,"1235569767556087");
gave the following result : ��)���,�AM9�,�
which is represented in an integer array as
[191,242,41,173,235,176,231,44,232,65,77,2,57,170,44,175]
when the encrypted string is sent to the debug page it becomes as following
[239,191,189,239,191,189,41,239,191,189,239,191,189,239,191,189,44,239,191,189,65,77,2,57,239,191,189,44,239,191,189]
as you can notice each � is represented by 3 bytes (239,191,189) instead of the actual byte
i use google chrome and the js code is as the following:
var SendDebugRequest = function(url,posted_data,callback){
var xhr = new XMLHttpRequest();
xhr.open('POST', "http://127.0.0.1/debug.php", true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response,xhr.responseURL);
} else {
callback(status, xhr.response,xhr.responseURL);
}
};
xhr.send(posted_data);}
Promise.all(UI.panels.network._networkLogView._dataGrid._rootNode._flatNodes.map( function(node){
var temp = [];
temp[1] = node._request._requestHeaders;
node._request._requestFormDataPromise.then(function(data) { temp[0] = data;});
node._request.contentData().then(function(data) { temp[2] = data.content;});
return temp;})).then(function(daata){
var posted_data = "encrypted_text=" + encodeURIComponent(daata[0][2]) + "&form_data=" + encodeURIComponent(daata[0][0]) ;
SendDebugRequest('',posted_data,function (status,response,resp_url){});});
so any idea about how can i solve the problem?
thanks in advance
EDIT:
as suggested in the comment , i tried using FormData instead of encodeURIComponent but also gave the same result
i changed
var posted_data = "encrypted_text=" + encodeURIComponent(daata[0][2]) + "&form_data=" + encodeURIComponent(daata[0][0]) ;
SendDebugRequest('',posted_data,function (status,response,resp_url){});});
to
var formData = new FormData();
var encrypted_text = new Blob([daata[0][2]], { type: "application/octet-stream"});
formData.append('encrypted_text', encrypted_text);
formData.append('form_data', daata[0][0]);
SendDebugRequest('',formData,function (status,response,resp_url){});
and removed the line
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
EDIT 2 :
The problem is due to chrome giving the text response instead of the actual raw hex response , do you have any idea about how can i achieve this? searching yielded no results , i don't mind using an extension as long as i can send the data to the debug page

JSON XMLHttpRequest POST/PUT to Cherrypy application - getting no data

I want to create a Singlepage Application following REST principles. I have managed to make both GET and DELETE work, but i also need to PUT or POST data.
After failing for some time, i looked around and found some sample code here https://gist.github.com/EtienneR/2f3ab345df502bd3d13e
which, first of all, taught me that setting a request header may be helpful. With that done, however, and following the exact example, I'm still getting "None" for the field i expect to receive data on.
I may be missing something absolutely basic, and looking around some more i just can't find out what it is.
on the javascript side i've got:
update_px (path_spl, success_ppl, fail_ppl, formdata) {
this.success_p = success_ppl;
this.fail_p = fail_ppl;
var data = {};
data.firstname = "John";
data.lastname = "Snow";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", path_spl, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var users = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
}
and on the python side of things:
def POST(self, path_spl="NoPathError", id = None, data_opl=None):
print("POST called with path_spl " + path_spl )
if(id != None) :
print(" and id " + id)
print (data_opl)
#process data
return ' '
The method is exposed; output shows I'm receiving the correct path and ID, but data is just None even after swapping in this sample code i found.
Where am i going wrong?
I have found a way to get it to work.
1) ** was missing on the expected data - that alone didn't help, now i was getting an empty dict instead of None
2) i replaced the content type; the header is now
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
with that, i am receiving:
{'{"firstname":"John","lastname":"Snow"}': ''}
Which actually leads me into another question - how did {"firstname":"John","lastname":Snow"} become a key with an empty value during json-ification? But anyway. That's for another day to find out; i can work with what i'm getting now.

String replace not working with value returned from a XMLHttpRequest request

I have a (Laravel) PHP code that returns a long string in this way:
echo json_encode([
'created' => $count,
'total' => $num_stores,
'progressValue' => round((100 / $num_stores) * $count, 2),
'token' => str_repeat('|',1024*64)
]);
I need to get this string in javascript and clean it, removing all "|" character. But it seems not working.
This is my javascript code:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
try {
if (xhr.readyState == 4) {
alert('[XHR] Done');
} else if (xhr.readyState > 2) {
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var cleanedResponse = new_response.replace(/[|]/g, '');
console.log('CLEANED RESPONSE: ' + cleanedResponse);
var result = JSON.parse( cleanedResponse );
console.log('AFTER THE PARSE');
xhr.previous_text = xhr.responseText;
}
} catch (e) {
console.log(xhr.responseText);
alert("[XHR STATECHANGE] Exception: " + e);
}
};
xhr.open("POST", "...", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-CSRF-TOKEN", jQuery('meta[name="csrf-token"]').attr('content'));
xhr.send(params);
I always get the exception when I try to parse JSON, and in the console I still see the "|" characters in the "cleanedResponse" variable.
How is it possible if I replace them?
When xhr.readyState == 3, then xhr.responseText holds only partial data - 3 means that the response has not yet been fully downloaded. You probably try to parse only partial JSON string that is not complete and therefore not valid and parsable. Wait for downloading complete response (xhr.readyState == 4) and then try to clean and parse JSON.
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState for further explanation of XHR states.

How to pass all the params as a single object while making ajax call

I have the below js code:
xmlhttp = GetXmlHttpObject();
if (xmlhttp != null) {
var url = "/support/residential/outage/serviceOutage?cbrnum=" + cbrnum + "&btn=" + btn + "&outagetkt=" + outagetkt;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("thankyoucontent").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(null);
}
This calls a servlet by passing certain params in query string. Now my question is , can we bind all the params into a single object , send that object alone in query string and use the object in the servlet to retrieve the param values? Is it possible?
Yes, you can send the data as JSON to the server:
var data = {cbrnum: cbrnum, btn: btn};
var url = "...?data=" + encodeURIComponent(JSON.stringify(data));
Then on the server side, retrieve the value of data and parse the JSON into native data types (Converting JSON to Java).
Note though that browsers often impose a length limit on the URL. If you have a lot of data, do a POST request instead.

Categories

Resources