Call mysql data of specific tablerow into hype

the data is written

<td>TOM</td><td>WARUM??</td><td>55</td>

but i don´t know how i can write this individual to the innerHTML of each element.
do i have to call it by creating an array?

var array = hypeDocument.getElementsByTagName("td");
for (var i=0; i < array.length; i++) {
txt1=data
};

just looking at this briefly I would keep it as an array in PHP and then json_encode it and bring it into Hype and parse it. That way the data will be an array in Hype that you can use to fill the elements.

thank you. i was looking for json_encode in stackoverflow, but i don´t check the logic of the php-code there
as i´m no php-coderer. using my script above is working. the only missing link is to put ervery cell.innerHTML from
the MYSQL-table to each element.innerHTML within hype.

Code from the other thread:

var loadTextFromID=function(id){
   var content=document.getElementById(id).innerHTML;
   var hypeElements=document.getElementsByClassName(id);
   for(i=0;i<hypeElements.length;i++){
      hypeElements[i].innerHTML=content;
   }
}
loadTextFromID('post1_headline');
loadTextFromID('post1_body');

As I mentioned this function writes the data found in a ID to all elements that have the same Classname.
So for example the content from the DIV with ID post1_headline is written into the all elements that have the class post1_headline .

As @DBear mentioned keeping the data in some format that is easy to convert into a data structur would be beneficial and make thing easier. Once you got that use something like this… (untested) tweak from the previous function:

var writeContentToClass=function(content, cl){
   var hypeElements=document.getElementsByClassName(cl);
   for(i=0;i<hypeElements.length;i++){
      hypeElements[i].innerHTML=content;
   }
}
//in your success clause and assuming you got a JSON return with data.user, data.pwd etc.
writeContentToClass( data.user, 'dataUser' );
writeContentToClass( data.pwd, 'dataPwd' );

You might ask why I am writing to class an here are the two reasons:

  1. Most important: Hype has a unique approach when it comes to responsive layouts. As with scenes themselves it keeps them in own HTML braches. Meaning when you have to repeat elements per scene/layout ID’s have to be unique and it would be annoying to have to choose a different ID per scene or layout for the same content.
  2. Addressing the content nodes per Class allows them to be in plentiful locations and they are all updated at once without the need to target any element specifically.

I saw that you are passing around password in your server response. If this isn’t secured by some two-way handshake I wouldn’t expose that access point to your userdata in a open ajax endpoint. A user able to read code could take advantage of that.

That (untest) suggested function isn’t currently limited to Hype as it does the replacing below document affecting the whole HTML-Page. That is nothing to worry about if your only running a single Hype Instance on the page… but if you want/need to limit the scope of the replacement to the current HypeDocument you would need some like:

var hypeDiv = document.getElementById(hypeDocument.documentId());
var hypeElements=hypeDiv.getElementsByClassName(cl);

instead of

var hypeElements=document.getElementsByClassName(cl);

Made a Extension from this (renamed it, though):

@MaxZieb how’s about actually answering strmiska’s question rather than hijack this thread with an extension you wrote that doesn’t actually solve this conundrum. Or use the code that strmiska has supplied within your example so that he can see the logic. :slight_smile:

He needs to get table data from a database using a PHP call into his Hype document. Not populate his elements with the innerHTML of other elements. Maybe he could use that after the fact but that fact is still “How do I get xyz from a database into my Hype project”

@strmiska Instead of creating table cells with the data inside your PHP why not just leave the data as an array. That way it would be easier to use it when it gets to Hype. Once I’m back on my computer I’ll have a better look.

1 Like

Really… what is it with this bashing here :hammer:. The code is to the point of his request and your JSON suggestion … I am trying to help him and others in the future.

And the extension was written after the fact in trying to generalize the effort.
If you go into the extention there is even an example (repost here):
setInnerHtmlByClass.hype.zip (62,6 KB)

OK gonna put this one to bed (i hope) and by the way it was a little friendly bashing Max as I’m sure strmiska didn’t really follow what you were trying to do and to be honest it wasn’t in keeping with the Title of the thread.

<?php
include ('DB3.php');

$con = mysqli_connect($host,$user,$pass,$databaseName);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

// Change character set to utf8
mysqli_set_charset($con,"utf8");

mysqli_select_db($con,$tableName);
$sql="SELECT * FROM $tableName WHERE id = 17";
 $result = mysqli_query($con,$sql);
 $output = mysql_fetch_array($result);
// This should leave you with an array like ["key" => "value"]
// You can then encode this to a javascript friendly format
echo json_encode($output);
// should echo like this ["key": "value"]

mysqli_close($con);
?>

Then in your Hype function you can do something like

var txt1 = hypeDocument.getElementById("nr").innerHTML;
var txt2 = hypeDocument.getElementById("header").innerHTML;
var txt3 = hypeDocument.getElementById("sub").innerHTML;
	
	$.ajax({
	   url: "${resourcesFolderName}/test.php", // or wherever your php file is
	   type: "POST",
	   success: function(data){                    
	        var arr = JSON.parse(data);
                txt1 = arr["username"];
                txt2 = arr["password"];
                txt3 = arr['zeit'];
	    }
	});

After this you could implement Max’s Extension and update more than one element

Given you use the extention and your field to fill got the class userName assigned

Then tweak it to assign values to class like this:

       $.ajax({
	   url: "${resourcesFolderName}/test.php",
	   type: "GET",
	   success: function(data){                    
	        var arr = JSON.parse(data);
                hypeDocument.setInnerHtmlByClass ('userName', arr["username"]);
                //... other fields here if needed
	    }
	});

@DBear that's collaboration :thumbsup:. In general the world needs more of this and not liberal (capitalistic) survival of the fittest :smile:

Yes collaboration I'm all for but confusion I am not. :wink: I'm not being capitalistic at all in fact the opposite. I share my information plenty. I could have kept it to myself. :wink:

2 Likes

I agree… the capitalistic was geared towards the general world not you. I see your profile is more then active so :sunny: on that behalf. About confusion… just doing the work for people that come to the forum can’t be the solution either so I try to explain and educate with an tendency to demand much. But then again this is not the Tumult Helpdesk an we are co-users with individual styles and personalities… I for one like to generalize problems so that the solution offers help for people with a similar (but not identical) problem in the future.

Cheers

thank you very much, but unfortunately i got the same problem.
alert(data) shows the correct text, but doesn´t set the text into the innerHTML of the elements.
here´s my test-doc.
mysql.zip (104,7 KB)

@MaxZieb thanks to all. you are a real great coder and your tutorials are very helpful.
as i´m not saddle in javascript like you i can follow you only step by step very slowly :footprints:.
but i´m still learning - thanks for your help, too!

I’ll leave it to Max then. Over to you Max. I mustn’t tell them how to do it :wink:

I didn’t say you mustn’t … just that I have a different mentality. If it practical is another discussion. I can offer help but only in a couple of hours, though. On the phone and the road. As usual.

Btw: at this point it’s implemention only. The solution and combined effort still rock :blush:

@MaxZieb vielleicht besser in deutsch :wink: das problem ist, dass ich daten von der datenbank mittlerweile laden kann, hineinschreiben kann, … funktioniert alles. das einzige problem ist dieses auslesen einzelner zellen.
hast du da mehr erfahrung damit?

Autsch! Ich verstehe auch deutsch. Ich schreibe nicht sehr gut. Also werde ich auf Englisch schreiben.

The code I have written is sound. It should echo out an array which you can then parse. I’m not sure why it’s not doing it for you.

Here is a demo for you. (This is my own server and a newly created database)

Here are 2 other ways you could do it.

Associative array:

$result = mysqli_query($conn, $sql);
$output = mysqli_fetch_assoc($result);
 
echo json_encode($output);

Demo here

Or

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo json_encode($row);
    }
}

Both should output an associative array that looks like {“id”: “1”, “firstname”: “John”, etc …}

and you can access the array in Hype by parsing it and using the convention array["key"];

Here is the full code I’ve used

PHP file:

<?php
$servername = "localhost";
$username = "************";
$password = "***********";
$dbname = "cl17-dbear";
$tablename = "MyGuests";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

//select info from table
$sql = "SELECT * FROM $tablename WHERE id=2";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo json_encode($row);
}

mysqli_close($conn);
?>

Hype function:

var result = hypeDocument.getElementById('result')
var output = hypeDocument.getElementById('output')
	
    $.ajax({
        url: "conn.php",
	type: "POST",
	success: function(data){                    
		console.log(data);
		var arr = JSON.parse(data);
		result.innerHTML = arr["firstname"] + ", " + arr["lastname"];
		output.innerHTML = JSON.stringify(arr);
        }
});

Demo

Oh and one thing to add. If you want to update more than 1 element with the same info just use a symbol / persistent symbol.

And that will be all the help I’m giving as clearly I haven’t got the experience as per the quote by strmiska above. Also I’m away for 3 weeks so I won’t have time to help.

Cheers

4 Likes

@DBear - thank you very much - DANKESCHÖN!!
it´s working now as expected.
the problem was the php - you wrote first to create an array:

$output = mysql_fetch_array($result);

then you changed it to

$output = mysqli_fetch_assoc($result);

… and this is working.
this was the missing link and again thanks for your help.

1 Like