Welcome to the nuBuilder Forums!

Register and log in to access exclusive forums and content available only to registered users.

Passing data from PHP to javascript

Questions related to customising nuBuilder Forte with JavaScript or PHP.
calida82
Posts: 58
Joined: Mon Sep 09, 2019 8:20 am

Passing data from PHP to javascript

Unread post by calida82 »

Hello,
I'm customizing a browse module that displays each customer's cars. I added a new <div> between nuBreadcrumbHolder and nuActionHolder
in this div I want to display paragraphs with the customer's data (name, address, telephone, etc.) I used nuRunPHPHidden

Code: Select all

$sql = "SELECT * FROM t_clienti WHERE t_clienti.cli_id =?";
$result = nuRunQuery($sql,array('#pk_cliente#'));
if (db_num_rows($result)==1){
    $r = db_fetch_object($result);
    nuDebug($r);
    
}

to retrieve the data I need but now I can't understand how to pass them from php to javascript....
nac
Posts: 115
Joined: Tue Dec 12, 2017 11:28 pm
Location: Aberdeen, UK
Has thanked: 9 times
Been thanked: 12 times

Re: Passing data from PHP to javascript

Unread post by nac »

Hello calida82,

You could try something like this (untested):

Code: Select all

$sql = "SELECT * FROM t_clienti WHERE t_clienti.cli_id =?";
$result = nuRunQuery($sql,array('#pk_cliente#'));
if (db_num_rows($result)==1){
  $r = db_fetch_array($result);
  $js = "
	var jData    = '".addslashes(json_encode($r))."';
	var rData  = JSON.parse(jData);
  ";
  nuJavascriptCallback($js);
}
The variable rData should contain the query result as a JSON object that you can then use in JavaScript (which could be placed in $js as well).


Neil
calida82
Posts: 58
Joined: Mon Sep 09, 2019 8:20 am

Re: Passing data from PHP to javascript

Unread post by calida82 »

Hi Neil thanks for your help,
I tried your suggestion but something isn't working. I'm definitely doing something wrong, I've never used nuJavascriptCallback and I'm not clear on how it works.
I try to view rData or even js in console.log() to see if data is being passed, but the console tells me that those variables are not defined. this is the custom code in the browse form.

Code: Select all

function creaDiv(){
    const intestazione = document.createElement("div");
    intestazione.setAttribute("id","nuIntestazioneHolder");
    intestazione.setAttribute("style","width: 100%; height: 50px; background-color:green;");
    
    const container = document.getElementById("nuActionHolder");
    container.parentNode.insertBefore(intestazione,container);
    
}


function addElements(){
    var paragrafo = document.createElement("p");
    
    nuRunPHPHidden('php_nominativo');
    console.log(rData);
    
    
}

creaDiv();
addElements();
php_nominativo

Code: Select all

$sql = "SELECT * FROM t_clienti WHERE t_clienti.cli_id =?";
$result = nuRunQuery($sql,array('#pk_cliente#'));
if (db_num_rows($result)==1){
    $r = db_fetch_object($result);
    nuDebug($r);
    $js = "	
    var jData  = '".addslashes(json_encode($r))."';
	var rData  = JSON.parse(jData);
	";
 nuJavascriptCallback($js);
}
nac
Posts: 115
Joined: Tue Dec 12, 2017 11:28 pm
Location: Aberdeen, UK
Has thanked: 9 times
Been thanked: 12 times

Re: Passing data from PHP to javascript

Unread post by nac »

Hi calida82,

The problem is that you are trying to display rData in the console immediately after calling the PHP function. The PHP code runs asynchronously on the server whilst the JavaScript continues immediately and so rData has not yet been defined when you try to use it. The PHP function nuJavascriptCallback($js) is called only when the PHP code has finished. Have a look at example below and try it yourself. I have added some code to display some of the data in rData as a popup message.

Code: Select all

$sql = "SELECT * FROM `zzzzsys_form` WHERE `zzzzsys_form_id` LIKE 'nu%' LIMIT 1";
$result = nuRunQuery($sql);
if (db_num_rows($result)==1){
    $r = db_fetch_array($result);
	$js = "
		 var jData    = '".addslashes(json_encode($r))."';
		 var rData  = JSON.parse(jData);
		 nuMessage('sfo_type         = ' + rData.sfo_type + '<BR>' +
		           'sfo_description  = ' + rData.sfo_description + '<BR>' +
		           'sfo_primary_key  = ' + rData.sfo_primary_key );
	";
	nuJavascriptCallback($js);
    
}
You could try adding the JavaScript you want to run after getting rData in the $js variable (where I have the nuMessage()). It will run correctly then.

I hope this helps.

Neil
calida82
Posts: 58
Joined: Mon Sep 09, 2019 8:20 am

Re: Passing data from PHP to javascript

Unread post by calida82 »

HI,
I tried your code and it works, but I can't get mine to work. If I understand correctly, inside $js I can write javascript code that will be executed when the function called with nuRunPHPHidden is finished.
I simply tried to insert code to add a paragraph to the nuActionHolder div present as standard in every module but when I run it gives me an error... this is the code

Code: Select all

$sql = "SELECT * FROM t_clienti WHERE t_clienti.cli_id =?";
$result = nuRunQuery($sql,array('#pk_cliente#'));
if (db_num_rows($result)==1){
    $r = db_fetch_object($result);
    nuDebug($r);
   $js = "
		 var jData    = '".addslashes(json_encode($r))."';
		 var rData  = JSON.parse(jData);
		 var paragrafo = document.createElement("p");
         var testo = document.createTextNode("Test");
         paragrafo.appendChild(testo);
         document.getElementById("nuActionHolder").appendChild(paragrafo);
		 
    ";
 nuJavascriptCallback($js);
}
I tried adding ' before and after each " but nothing changed...
One thing is still unclear to me, once the function called with nuRunPHPHidden is finished, will the rData variable be available to be used in custom javascript code of the form without any particular declaration? if so can I add a dummy delay after calling nuRunPHPHIdden and then continue with the javascript code? always from custom javascript code of the form?
nac
Posts: 115
Joined: Tue Dec 12, 2017 11:28 pm
Location: Aberdeen, UK
Has thanked: 9 times
Been thanked: 12 times

Re: Passing data from PHP to javascript

Unread post by nac »

Hello calida82,

Do make sure that you look for errors in the console; I had to change const to var to make this work. Anyway, here is a quick response which does work but you will need to add a bit more to get what you want. I have used my orginal SQL statement and the most basic way of putting some text (from the SQL result) in the DIV. Note that you need to use db_fetch_array as well.

JavaScript for the form

Code: Select all

var intestazione = document.createElement("div");
intestazione.setAttribute("id", "nuIntestazioneHolder");
intestazione.setAttribute("style", "width: 100%; height: 50px; background-color:green;");
var container = document.getElementById("nuActionHolder");
container.parentNode.insertBefore(intestazione, container);
nuRunPHPHidden('php_nominativo');
This creates the DIV and then calls the code that pulls data from the server to add the content.

PHP procedure : php_nominativo

Code: Select all

$sql = "SELECT * FROM `zzzzsys_form` WHERE `zzzzsys_form_id` LIKE 'nu%' LIMIT 1";
$result = nuRunQuery($sql);
if (db_num_rows($result) == 1) {
    $r = db_fetch_array($result);
    $js = "
		 var jData    = '".addslashes(json_encode($r))."';
		 var rData  = JSON.parse(jData);
		 var rInfo ='Three values from a record in the table zzzzsys_form .... sfo_type = ' + rData.sfo_type + ' : sfo_description  = ' + rData.sfo_description + ' : sfo_primary_key = ' + rData.sfo_primary_key ;
		 $('#nuIntestazioneHolder').text(rInfo);
	";
    nuJavascriptCallback($js);
}
You can call nuRunPHPHidden('php_nominativo'); as often as required, perhaps after changing the value of #pk_cliente# and the code will replace the contents of the DIV.

As I said, this is very basic but it demonstrates the functionality. Try using the code fragments here, check that they work and then make the modifications to the SQL etc so that you get what you want.

Let me know how you get on.

Neil
calida82
Posts: 58
Joined: Mon Sep 09, 2019 8:20 am

Re: Passing data from PHP to javascript

Unread post by calida82 »

Hi, thanks, I tried your code by adapting it to my table, it works but I would like to do something more. I would like to add some paragraphs to format the data in a more readable and nice way. not using the classic instructions to add elements to the dom I can't understand how to set the attributes for the elements I add.
nac
Posts: 115
Joined: Tue Dec 12, 2017 11:28 pm
Location: Aberdeen, UK
Has thanked: 9 times
Been thanked: 12 times

Re: Passing data from PHP to javascript

Unread post by nac »

Hi again,

I am glad to hear that it worked. My reply was focussed on your question "Passing data from PHP to JavaScript" using the tools available in nuBuilder, which you have now been able to do, rather than how to then present and format the data once transferred. That is a much bigger topic and it really depends on how you want the data formatted etc. (which I do not know, of course).

You may have noticed that I used jQuery to put the plain text in the div. It is worth looking at how to use jQuery to "add some paragraphs to format the data in a more readable and nice". There are many resources to help you create/modify web pages using jQuery. Examples include TutorialRepublic and W3Schools and there is always StackOverflow, of course.

Neil
nac
Posts: 115
Joined: Tue Dec 12, 2017 11:28 pm
Location: Aberdeen, UK
Has thanked: 9 times
Been thanked: 12 times

Re: Passing data from PHP to javascript

Unread post by nac »

A quick follow-up..

Using jQuery, you could replace the JS for the form custom code with these three lines.

Code: Select all

$("<div id = 'nuIntestazioneHolder'>This text will be replaced after running PHP procedure 'php_nominativo' .</div>").insertBefore("#nuActionHolder");
$("#nuIntestazioneHolder").css({ 'width': '100%', 'height': '50px', 'background-color': 'green', 'color': 'white', 'font-size': '120%',  'text-indent' : '50px' });
nuRunPHPHidden('php_nominativo');
Line 2 has your formatting plus a bit extra that I added as an example.

Neil
calida82
Posts: 58
Joined: Mon Sep 09, 2019 8:20 am

Re: Passing data from PHP to javascript

Unread post by calida82 »

Hi, thanks again, no I don't know jquery, I'm now approaching web languages... I took a look at the first link you gave me and I saw that you can do practically everything and even with little code. the thing that annoys me a little is that in this way the two languages ​​are merged and if you want to make some changes in the future it will perhaps be more complicated than acting on each language individually. I haven't tried to write anything yet, if I can I'll try tonight. To avoid making mistakes between ' and " to write javascript code inside the $js variable I thought of adding all the tags I need with the right formatting in the custom code of the module by inserting only the tags or giving them a value " " and then via php with jquery as you showed me replace the spaces with the values ​​of the query. so I have the possibility of writing more code each in its own editor which often helps to avoid errors....
Post Reply