0

I have created a file that automatically posts 3 identification fields (for authentication) to retrieve JSON results. It works fine (right now developed as proof of concept so ids are hard-coded). Upon success, the JSON is returned as an alert to the browser.

How can I return and format the JSON results on the screen?

Here is the working url: https://www.advantageengagement.com/REST/js_yes.html

<!DOCTYPE html>
<html>
<head>
     <title>Javascript POST Form</title>
     <meta charset="utf-8">
</head>
<body>
    <script type="text/javascript">
        var http = new XMLHttpRequest();
        var postdata= "id_eap=999&id_company=&password=AAA111BBB2";              
        http.open("POST", "https://www.advantageengagement.com/REST/content/read.php", true);
        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.onreadystatechange = function() {
             if(http.readyState == 4 && http.status == 200) {
                 alert(http.responseText);    
             }
        }
        http.send(postdata);
     </script>
</body>
</html>
  • Possible duplicate of [JSON.stringify output to div in pretty print way](https://stackoverflow.com/questions/16862627/json-stringify-output-to-div-in-pretty-print-way) – Dan O Jan 06 '19 at 20:14
  • there are many, many questions on Stack Overflow regarding how to display an API response inside the browser. Which have you tried, and why do they not apply here? – Dan O Jan 06 '19 at 20:15

2 Answers2

0

If I understand your question,

Depending on how you want to show the data, you can split the data showing up in your alert up on the "," and use each of those new individual items as data for a numbered/unordered list with JavaScript DOM manipulation.

Here's information on splitting the data: Syntax split(separator, limit)

Parameter
separator:  The character to separate the string. The separator itself is 
a string. If the separator is not present it returns the entire string. in 
your case you could use ",". 

limit : An integer specifying a limit on the number of substrings to be 
found. Make it big if you don't know how many individual items are in the 
object showing in your alert.

Here's information on the javascript: https://www.w3schools.com/js/js_htmldom_html.asp

bigPigB
  • 1
  • 4
0

You haven't exactly specified, how you want to format the JSON but I gave a shot and did accordingly.

You can use the below code.

http.onreadystatechange = function() {
             if(http.readyState == 4 && http.status == 200) {
             var a=http.responseText.split(" ");
            a.forEach((e)=> $('body').append(e + "<br>"))

             }
        }

The split function splits the JSON into an array upon every (" "). You can put any parameter in here with respect to which you want split. Then append each element in array with a line break.

ellipsis
  • 12,049
  • 2
  • 17
  • 33