2

On my HTML page I have a script that sends a database query via PHP. Now I need to pass the array with the results (an associative array) back to my HTML page to populate some textareas.

Questions (I am new to PHP):

1- Can the array be passed as it is or it needs to be encoded/decoded or serialized/unserialized (and how)?

2- Once the array reaches the HTML script can I cycle through its elements via a loop (I mean, is it possible to make a loop inside an HTML script?)

3- If the latter is not possible, how could I then instruct PHP to populate a given textarea on the HTML page?

Edited (now with code):

//HTML
<script>
    function PopulateTextAreas() 
    {
        var arrayTextAreasNames = ["name","surname","dob"];

        //Now pass this to php
        var xhttp = new XMLHttpRequest();

        var jsonstring = JSON.stringify(arrayTextAreasNames);
        var encoded = encodeURIComponent(jsonstring);

        xhttp.open("GET", "LoadFromDb.php?hId=" + "&arrayTextAreasNames=" + encoded, true);

        xhttp.onreadystatechange = function() 
        {
            if (this.readyState == 4 && this.status == 200) 
            {
                    var decoded = json_decode(this.responseText);
                    console.log(decoded); //Not working

          //A loop would then follow to separate each element of the array and then populate the corresponding textareas is a way similar to below:
           //document.getElementById("name").value = this.responseText; 
           //document.getElementById("surname").value = this.responseText;
           //document.getElementById("dob").value = this.responseText;
            }
        };
        xhttp.send(); 
    }
</script>  




//PHP
    //The associative array is built in a loop like this
    $ArrayDbEntryName_and_itsValue[$i] [$DbItemName] = $DbItemValue;

    //and it looks like the follow one:

array(3) {
  [0]=>
  array(1) {
    ["name"]=>
    string(1) "paul"
  }
  [1]=>
  array(1) {
    ["surname"]=>
    string(2) "green"
  }
  [2]=>
  array(1) {
    ["dob"]=>
    string(8) "1/1/1980"
  }

    //Then the array is echoed back to the HTML page like this
    $ResultStringified = JSON.stringify($ArrayDbEntryName_and_itsValue);
    echo encodeURIComponent($ResultStringified);
jeddi
  • 651
  • 1
  • 12
  • 21
  • You don't process anything with HTML. You can loop with PHP and echo HTML with it. Filling the textarea would only work on page load with PHP, otherwise you need client script like javascript/jquery – GrumpyCrouton Jul 14 '17 at 19:53
  • The terms you use make your question sound confusing and it is not immediately clear what you mean. For example, HTML cannot loop through anything, so I am guessing you are talking about a JavaScript script of a jQuery script that is located inside the HTML page. And when you say the script sends a query via PHP, I am guessing you mean that it is sent via HTTP protocol *to* a PHP script on the server. You can send an array from PHP to the JS script inside HTML page, it is typically done by using json_encode, and then having JS script decode the JSON string into a JavaScript array – Dennis Jul 14 '17 at 20:40
  • Thanks for the clarifications. I have edited the question with some code to better explain myself. – jeddi Jul 14 '17 at 21:10

4 Answers4

2

Edit: Following information is according to the OP(before the code by the poster was included).

  1. Arrays from PHP can't be passed to HTML. Instead you convert that array to a more usable format that can be then sent to HTML. For that generally you use JSON (Javascript Object Notation) format. For Example, lets say you create an associative array in your PHP file.

    $info = ["firstname" => "somename", "age" => 25, "address"=>["home"=>"something1","collage"=>"something2"]];
    

    Now you will have to convert $info into JSON format. You use following funtion to do that.

    $jsoninfo = json_encode($info);
    

    JSON format just consist of name-value pairs. Name is "firstname" and it's value is "somename". That was the first name-value pair. And so on. Since you want to display it on HTML you echo the $jsoninfo:

    echo $jsoninfo;

    This is how it will look on HTML.

    {"firstname":"somename","age":25,"address":{"home":"something1","collage":"something2"}};
    

    But you said you want to populate this into a textarea in HTML. Hence I am using this instead of that simple echo. This will create a textarea element and put the whole value $jsoninfo inside that textarea element.

    echo "<textarea>".$jsoninfo."<textarea>"; // this is not a good practice to send value to HTML like this way, since you asked about it I had to write like that. You will need javascript to actually play with the JSON object and then write it to HTML.
    
  2. Unlike array, from JSON you have to use name from a name-value pair to fetch its associated value. And you will need javascript for that. I am showing you.

    Since this is not a tutorial on javascript I am going direct.

    Assume you have an empty paragraph element as well(we will need this) in your html page and it's id is "p1". Like following:

    <p id='p1'></p>
    

    Now we will use following javascript code inside HTML or from external js file that have already been included to HTML. Here I am writing it as inline script inside HTML.

    <script>
    var getfromtextarea = document.getElementsByTagName("textarea")[0].innerHTML; //get the JSON object from textarea and save it into a javascript variable named getfromtextarea
    var get2 = JSON.parse(getfromtextarea); //JSON.parse() function is used to convert JSON object into javascript plain object so that we can get the value associated to its name(remember name-value pair), you will understand this is next line.
    document.getElementById("p1").innerHTML = get2.firstname; //this will write/print "somename"(without quotes) inside the p element that we had created in HTML.
    </script>
    
  3. Many things are possible, you just will have to learn techniques and go by rules. I hope it helps you understand something.

falero80s
  • 368
  • 6
  • 12
  • Wonderful explanations. Many thanks! One last thing please. Now I get my array back to the HTML doc like this: var JSONObject = JSON.parse(this.responseText); On the console it looks something like this: [{"name":"john"},{"surname":"green"},,{"dob":"1\/1\/1940"}] Now I need to extract in a loop each singe object's name ("name","surname", "dob") along with its relative value so that I can assign each one to different textareas that already exist on the page. How can I make this loop? – jeddi Jul 15 '17 at 19:36
  • @jeddi It can be done too. Now you need to convert JSONObject into javascript array. This has already been explained in here. [link]https://stackoverflow.com/questions/38824349/convert-object-to-array-in-javascript all you need to do is use "String(e)" instead of "Number(e)" (because you want to keep the name as string instead of number in name-value pair. var result = Object.keys(JSONObject).map(function(){ return [String(e), JSONObject[e] ]; }); You can now get name value from result[0][0] and it's value from result[0][1] for first name-value pair. – falero80s Jul 15 '17 at 20:19
  • @jeddi [I am assuming you are already familiar with "for" or "while" loop.] Now after that, since JSONObject is an associative array, you need two "for" loops, one for getting the index number of arrays(pairs) inside that associative array and second for getting name-value from that pairs. Here is how values will be accessed; result = [ [2], [2], [2] ], result[0] = ["name":"john"], result[0][0] = "name", result[0][1] = "john"......I think you got that. For for loops you need to get correct size of elements. Use result.length to get the length of your associative array. – falero80s Jul 15 '17 at 20:55
  • Actually my outputs are as follows: console.log(result[0]); //["0", Object { name="john"}] console.log(result[0][1]); //Object { name="john"} What I need to extract is the clean strings: "name" and "john" – jeddi Jul 17 '17 at 13:38
  • @jeddi result[0] points to first element that is "0"(what you are seeing). Use result[1] and you will see console.log(result[1]) // Object {name:"john"}. But you need to fetch john, for that use, console.log(result[1].name). – falero80s Jul 17 '17 at 20:38
  • @jeddi it looks like you somehow made all this a little complex. All you have to do is (1) echo values in JSON style by using json_encode() from PHP. (2) Save those values in some variables in Javascript by using JSON.parse() function. (3) Now in javascript you either get value directly by using its name from name-value pair, [OR] you use this [link]https://stackoverflow.com/questions/38824349/convert-object-to-array-in-javascript funtion to firstly convert that JSON object into an array in javascript and then finally use index number to get values. – falero80s Jul 17 '17 at 20:47
0

1.If you want to pass an array, you can use JSON format. Look about it http://php.net/manual/en/function.json-encode.php

2.HTML is a markup language, not script. To cycle through an array in a browser, you can use Javascript. Or you can generate HTML-page on server side with PHP.

3.As an example:

<?php
/**
 * This is .php file
 *
 * @var array $rows Array of data which you would to show in textarea
 */

?>

<textarea>
    <?php
    foreach ($rows as $key => $value): ?>
        <p id="<?= $key ?>"><?= $value ?></p>
    <?php endforeach; ?>
</textarea>
buildok
  • 785
  • 6
  • 7
0

I am thinking of something like this:

On PHP side:

echo '<div id="my_array" style="display:hidden">' . json_encode($myArray) . '</div>';

On HTML/JavaScript side:

<script>    
var myArray = JSON.parse(document.getElementById("myArray").innerHTML);

//loop through myArray using JavaScript
var arrayLength = myArray.length;
for (var i = 0; i < arrayLength; i++) {
    alert(myArray[i]);
    //Do something
}
<script>

For #3, there are many ways. I may need to see your code that generates textarea to suggest how to populate it with text.

Update

I see you are using var xhttp = new XMLHttpRequest(); directly .. why?

I'd much recommend using jQuery AJAX facilities (easy learning curve and low initial investment) or something like AngularJS (high learning curve and initial investment) for AJAX requests.

It will be less code and less things to debug

For the json_decode() not working, try JSON.parse(this.responseText);

JSON.parse is JS function, while json_decode is a PHP function and you are trying to use it in a JS script.

I have not looked into the code further to see how to get your text into the textarea box just yet, but you can do it using AJAX and do something like these:

Fill a textbox with jQuery

Jquery to populate input or textarea

Dennis
  • 7,907
  • 11
  • 65
  • 115
0

I know its already passed almost 2 years, but just a simpler PHP only method can be used and no need JS or json if the source of data was in a form submitted through HTML only.

HTML/PHP Code set below.

Example HTML

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8" />
    <title>PHP HTML - Pass data around with POST</title>
    <link rel='stylesheet' type="text/css" href="css/style.css" />   
    </head>
    <body>

  <form method="post" name="frmData" action="pass_data_received.php">
    Name:<textarea name="name"></textarea>
    Surname:<textarea name="surname"></textarea>
    Date of birth:<textarea name="dob"></textarea>
    <br />
    <input type="submit" name="submit" value="Submit">
  </form>
  </body>
</html>

Example PHP

<?php

  // Process only if the form was submitted
  if(isset($_POST['submit'])){

    echo '<h3>Data was submitted as shown below.</h3>';
    // init variable data to an empty array
    $data = [];

    // set the data to the post array
    $data = $_POST;

    // get the count of posted by only the name field (any field can do as long as it is a mandatory/required input)
    $dataLength = count($data['name']);

    /* You can use a (foreach) loop or a (for) loop to iterate through the data array as below methods */

    // Method-1: for each loops through each entry in the data array as key->vlue pairs and echo with line break
    // Note: This will not give you index for further referencing
    foreach($data as $key=>$value){
        echo $key.':'.$value.'<br />';
    }

    // Method-2: for loop 
    // Note: This will give you index (i) for reference if required
    for( $i=0; $i > $dataLength; $i++ ){
      $data['name'] = $_POST['name'];
      $data['surname'] = $_POST['surname'];
      $data['dob'] = $_POST['dob'];
    }

    // Print_r the array for debug only
    echo '<pre>'; print_r($data); echo '</pre>';  
?>
    <h3>Data received and processed through POST and PHP only</h3>

<!-- Note:
     You can post the same data even further to any HTML or PHP again if needed 
     using the POST and ACTION
 -->

    <form method="post" name="frmData" action="pass_data_further.php">
      Data of index <?php echo $i; ?> <br />
      <hr />
      Name:<textarea name="name"><?php echo $data['name'] ?></textarea>
      Surname:<textarea name="surname"><?php echo $data['surname'] ?></textarea>
      Date of birth:<textarea name="dob"><?php echo $data['dob'] ?></textarea>
      <br />
      <input type="submit" name="submit" value="Submit">
    </form>
<?php
}
?>
samimi_it
  • 75
  • 1
  • 2
  • 11