0

I am trying to get certain data from my database on my (1) HTML page and display it on the (2) HTML page.

My codes for (1) html file:

<html>

<head>
    <script src="example.js"></script>
</head>

<body>
    .
    .
    .
    <button item="' + count + '" onclick="getData(this)">Example</button>
    .
    .
    .
</body>

</html>

And the JS for it:


        .
        .
        .
        var currentIndex = 0;

        //This function is to display the details of an individual item
        function getData(element) {
            var request = new XMLHttpRequest();

            request.open("GET", "/theroute", true);
            request.setRequestHeader("Content-Type", "application/json");
            request.onload = function () {
                var example = JSON.parse(request.responseText);

                var item = element.getAttribute("item");
                currentIndex = item;

                document.getElementById("data1").textContent = example[item].name;
                document.getElementById("data2").src = example[item].age;
            }
            request.send();
        }
        .
        .
        .

I want to get these data in my (2) HTML page (for example):

<html>

<head>
    <script src="example.js"></script>
</head>

<body>
    <h4 id="data1"></h4>
    <h4 id="data2"></h4>
</body>

</html>

I saw this Get data from one html file and display it using another html file, but I'm not sure how to use this for my case here.

Sorry, I am new to this, so giving a detailed explanation for your solution would be very helpful. I am using vanilla JS only so please no jQuery. Any help would be appreciated

CBCH
  • 127
  • 1
  • 3
  • 14
  • The above snippets are a little unclear. Are you generating the initial HTML with a serverside language and database? ( php & mysql perhaps ) You cannot have two elements with the same ID ( `

    ` ) and you cannot send the response of an ajax call to another HTML page and hope that it will be there next time you look...
    – Professor Abronsius Jan 24 '20 at 09:59
  • sorry, for the ID part it was a typo. And yes, I am trying to get data from mysql database. – CBCH Jan 24 '20 at 10:03
  • fetching data from the db to display on the same page? That is easy. Fetching data to display on another page ( different from the page making the request ) is an entirely different problem and will not be done like this. Please clarify which – Professor Abronsius Jan 24 '20 at 10:05
  • I am fetching the data to display on another page. – CBCH Jan 24 '20 at 10:09
  • who will see the data on the other page? Will that person be on both pages simultaneously? – Professor Abronsius Jan 24 '20 at 10:29
  • No. Picture it like a search list, where i click on one of the items, it brings me to the item's page. But I want to get the item data / id and send it over to the 2nd page. – CBCH Jan 24 '20 at 10:37
  • OK - that is an important distinction to make. – Professor Abronsius Jan 24 '20 at 10:41
  • sorry about the incovenience – CBCH Jan 24 '20 at 10:43
  • ok, can you show the response data or the JSON data? – Professor Abronsius Jan 24 '20 at 10:45
  • Also - the `dataset` attribute might be of interest. They allow you to legitimately assign custom `data-PARAM=VALUE` type attributes to HTML elements. By convention you should not add your own attributes to html elements for the markup to remain valid. – Professor Abronsius Jan 24 '20 at 10:47
  • The output of `console.log(request.responseText)` is `[{"_id":1, "name":"test","age":10}] – CBCH Jan 24 '20 at 10:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/206578/discussion-between-ramraider-and-cbch). – Professor Abronsius Jan 24 '20 at 11:31

1 Answers1

1

I hope this might prove of use to you. The button(s) have had the custom item attribute replaced with the dataset equivalent to ensure the html is valid. Normally I'd suggest also using external event handlers rather than adding onclick=getdata() to the elements inline but for brevity here they remain.The function, when invoked by clicking a button, will construct the relevant querystring to send to the endpoint ( for you it would be /theroute?id=X&name=Y&age=Z etc ) which queries the database and sends the response back. The response is used to generate the menu of hyperlinks which take the user to page 2 when clicked. I think this is what you were trying to explain. You could copy the entire code and create a new page to see in action.

<?php

    if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['item'] ) ){
        ob_clean();

        /* 
            emulate "/theroute" and send some data back to the ajax callback.

            This data would really be fetched from the database but below is
            simply randomly generated data for display/test purposes.
        */


        $payload=[];
        $item=$_GET['item'];
        for( $i=0; $i < 10; $i++ ){
            $payload[]=[
                'id'    =>  $i,
                'name'  =>  'Geronimo '.uniqid().' '.$item,
                'age'   =>  mt_rand(16,80)
            ];
        }
        exit( json_encode( $payload ) );
    }

?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script>
            function getData( e ) {
                var xhr = new XMLHttpRequest();
                var ul=document.getElementById('menu');
                /* The above PHP code is to emulate the real endpoint /theroute */

                xhr.open( "GET", location.href +'?task=fetch&item='+e.target.dataset.item, true );
                xhr.setRequestHeader( "Content-Type", "application/json" );
                xhr.onload = function() {
                    var json = JSON.parse( xhr.response );
                    json.forEach(obj=>{

                        var id=obj.id;
                        var name=obj.name;
                        var age=obj.age;

                        var li=document.createElement('li');
                            li.appendChild( createhyperlink(id,name,age) );                     
                        ul.appendChild( li );
                    });
                }
                xhr.send();
            }

            function createhyperlink(id,name,age){
                var a=document.createElement('a');
                    a.href='page2.html?id='+id+'&name='+name+'&age='+age;
                    a.innerHTML='View '+name;
                return a;
            }

        </script>
    </head>
    <body>
        <ul id='menu'></ul>
        <?php
            for( $i=1; $i <=10; $i++ ){
                echo "<button data-item='{$i}' onclick='getData(event)'>Example #{$i}</button>";
            }
        ?>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • So sorry about this but im only using vanilla JS. – CBCH Jan 24 '20 at 11:26
  • the above is vanilla javascript – Professor Abronsius Jan 24 '20 at 11:27
  • i don't have php available for my case – CBCH Jan 24 '20 at 11:28
  • Ok - the PHP is not important. I used PHP here simply to create the initial HTML (buttons) and to process the ajax request ( which would be some other server side language unknown to me and undisclosed in question )... the important bit is processing the ajax response and creating suitable `links` to take the user to page 2 – Professor Abronsius Jan 24 '20 at 11:30
  • Sorry for the late reply, let's discuss at https://chat.stackoverflow.com/rooms/206578/discussion-between-ramraider-and-cbch – CBCH Jan 24 '20 at 13:36