Solved

Storing a return value from a java script in  php

Posted on 2014-12-03
23
363 Views
Last Modified: 2014-12-11
Hi Experts, I am fairly new to PHP calling jscript.

I have a php page where I will list down a set of script names in a combo box . The script names are read from database and the display part works fine. I wanted to display the arguments corresponding to the script again by reading from the database when a user selects one of the option from the combo box.

The approach I am doing here is by setting a submit button near the combo box to allow the user to select an option from the combo box and when the user clicks the submit botton ( labelled as Lookup) to call a function GetScriptData() and  return the selected script name in the combo box . This return value of script name I need to capture in a varaiable say $script_name and use it for further processing. ie) I have to again call the database using the variable $script_name to get the args corresponding to the script name.

I want to get this on the same php page. I have tried few options , but could not succeed. Any help would be much appreciated.

the script is as below.

<html>
<head>
<script language="javascript" type="text/javascript">
function GetScriptData($scriptName) {
document.write($scriptName);
</head>

<body>

<form name="frmParams" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<?php
# Select the list of scripts for the corresponding business unit.
$script_list_query = "SELECT DISTINCT script_name FROM script_execution WHERE business_unit = '$business_unit';";
$script_list       = pg_query($connection, $script_list_query) or die ("Error in query: $check_query.". pg_last_error($connection));
# Store the number of scripts.
$no_of_scripts = pg_num_rows($script_list);
echo "<table border=\"0\" align=\"left\" cellpadding=\"5\" cellspacing=\"0\">\n";
   echo "<tr>\n";
       echo "<td align=\"left\">\n";
#echo $script_name;
for ($i=0; $i < $no_of_scripts ; $i++)

{
   $script_row = pg_fetch_row($script_list, $i);
   echo "<option value=\"".$script_row[0]."\">".$script_row[0]."</option>\n";
}
echo "</select>\n";
echo "<input type='submit' value='Lookup' onclick =\"GetScriptData(document.getElementById('script').value);\" />";
?>

Open in new window

0
Comment
Question by:naveenraj
  • 7
  • 7
  • 2
  • +4
23 Comments
 
LVL 11

Expert Comment

by:jausions
ID: 40481031
First, please repost the question's code without encoding the < > and other special HTML characters.

Second, I can't see if you have the start tag <select> anywhere.

Third, if you use an <input type="submit" > element, you probably need to make the onclick event return false, although it's not clear what you are trying to achieve with the document.write() call.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40481039
1 - did you notice your code is not really readable, look like you copy/paste from dreamweaver
2 - you need to use Ajax, using jQuery it's a bit simple but, please, start by posting your right code well formated
0
 

Author Comment

by:naveenraj
ID: 40481122
I cant post any comment to this ?!
Moderator please help
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40481150
? ? ?
greetings  naveenraj, , You seem to have the wrong Idea about the way PHP (a server side code base), and Javascript (a browser side code base) can "Interact" and be used Together.

Please keep in mind that PHP code and Javascript code are on TWO different computers, and can have NO working interaction, except to send text output to each other, so you CAN NOT use PHP code variables in Javacript code, , , , OR use Javascript variables in PHP code. You also can not ever use the PHP database directly in your Javascript code, so as you ask - "I have to again call the database using the variable $script_name" , , can not be done just with Javascript code, because the PHP and database are on a separate computer.

It is my view that you have two options to do this.

The first option is to place ALL of the "args corresponding to the script name" for ALL of the different script names into a Javascript array or object for storage, and then when the user makes a Selection change, you use javascript function to read the "args" from the Javascript array or object, and display them to the user.

The other option is to use a Javascript browser to server communication method called AJAX, using this AJAX exchange of text between the browser and PHP server, will allow you to send the Script Name to PHP and then get PHP to use the Database, and send back the "args" as a CSV list in the text output from PHP to the browser Javascript.

I would think that you will need to know something about programing in Javascript code to do either one. Unfortunately, there are MANY different ways to do either option, maybe we can help you more if you can give more info about How to need to display the database return of "args corresponding to the script name" to the user? ?
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40481159
it is always best for EE to display code work in the "Code" that you see at the top of the Comment input, to have your code look like this -
<html>
<head>
<script language="javascript" type="text/javascript">
function GetScriptData($scriptName) {
document.write($scriptName);
</head>

<body>

<form name="frmParams" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<?php
# Select the list of scripts for the corresponding business unit.
$script_list_query = "SELECT DISTINCT script_name FROM script_execution WHERE business_unit = '$business_unit';";
$script_list       = pg_query($connection, $script_list_query) or die ("Error in query: $check_query.". pg_last_error($connection));
# Store the number of scripts.
$no_of_scripts = pg_num_rows($script_list);
echo "<table border=\"0\" align=\"left\" cellpadding=\"5\" cellspacing=\"0\">\n";
   echo "<tr>\n";
       echo "<td align=\"left\">\n";
#echo $script_name;
for ($i=0; $i < $no_of_scripts ; $i++)

{
	   $script_row = pg_fetch_row($script_list, $i);
   echo "<option value=\"".$script_row[0]."\">".$script_row[0]."</option>\n";
}
echo "</select>\n";
echo "<input type='submit' value='Lookup' onclick =\"GetScriptData(document.getElementById('script').value);\" />";

Open in new window

0
 
LVL 65

Expert Comment

by:RobSampson
ID: 40481875
>> so you CAN NOT use PHP code variables in Javacript code

Is that really true?  I don't pretend to know much about PHP or JQuery at all, since I haven't been coding with them for long, but I have been able to do something like this:
<?php
	$strMyPHPString = 'This is my PHP string transferred to JQuery';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <title>My New Page</title>
    </head>
    <body>
		This is my page
		<br>
		<div id='mydiv'></div>
		<br>
		<script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
		<script>
			$(document).ready(function() {
				var strMyJQueryString = "<?php echo $strMyPHPString; ?>";
				$("div#mydiv").html (strMyJQueryString);
			});
		</script>
    </body>
</html>

Open in new window


So that allows me to take server side values and use them in JQuery.  It's primitive I know, and rather static, but it does the job for me, and doesn't mean that passing values (or more accurately, pulling values) is impossible.

The other option you have is to write a value to a hidden text element, and have JQuery read that as well.

Regards,

Rob.
0
 
LVL 11

Expert Comment

by:jausions
ID: 40481931
If the original poster would explain what the code should be doing, that would help a lot. The word "script" is confusing as we don't know if that refers to a PHP script on the server or a JavaScript file script.

My suggestions:
Don't use $ with Javascript variables. That will confuse you when working on PHP pages.
Make sure all the HTML elements are properly declared (i.e. <select> start tag, correct "name" and "id" attributes, and so on...).
Make the "onclick" event return "false" if you don't want the page to reload.
If you want data to be sent to the PHP script on the server (i.e. from the selected option on the HTML page in the web browser) to be processed then want that PHP script to return data to the same HTML page, I suggest you use AJAX. The data the PHP script returns should be encoded in JSON for easy processing by jQuery (for instance.)
Think if a round-trip to look up the information is really necessary. Why not include the data you need in the drop <select> element directly so the JavaScript on the HTML page would have all it needs to do its thing.
0
 

Author Comment

by:naveenraj
ID: 40482308
<html>

<head>

<script language="javascript" type="text/javascript">

function GetScriptData($scriptName) {

document.write($scriptName);

}

</script>

 

</head>

 

<body>

<form name="frmParams" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">

 

# Select the list of scripts for the corresponding business unit.

$script_list_query = "SELECT DISTINCT script_name FROM script_execution WHERE business_unit = '$business_unit';";

$script_list       = pg_query($connection, $script_list_query) or die ("Error in query: $check_query.". pg_last_error($connection));

 

# Store the number of scripts.

$no_of_scripts = pg_num_rows($script_list);

 

echo "<select id=script name =\"script\"  align=\"left\">\n";

 

#echo $script_name;

for ($i=0; $i < $no_of_scripts ; $i++)

 

{

   $script_row = pg_fetch_row($script_list, $i);

   echo "<option value=\"".$script_row[0]."\">".$script_row[0]."</option>\n";

}

echo "</select>\n";

echo "<input type='submit' value='Lookup' onclick =\"GetScriptData(document.getElementById('script').value);\" />";

?>

</form>

 

</body>

</html>

Open in new window



Basically I need to store the value of the combo box in a variable and use it in another sql statement when I submit the button.

EDIT: Code tags added - RobSampson
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 40482482
NEVER use document.write after load. the page will be wiped.

If you need to use the variable on the server, do what has been suggested and Ajax to the PHP

For example
<!DOCTYPE html>
<html>
<title>Select something</title>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
  $("#frmParams").on("submit",function(e) {
   e.preventDefault(); // stop submission
   var scriptName = $("#script").val();
   if (scriptName) {
     $.get("newselect.php?parm="+scriptName,function(data) {
        $("#someContainer").html(data);
     });
   });  
});
</script>
</head>
<body>
<form id="frmParams" name="frmParams" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" 
enctype="multipart/form-data"
onsubmit="return GetScriptData(this)">
<select id=script name ="script"  align="left">
<? 
# Select the list of scripts for the corresponding business unit.
$script_list_query = "SELECT DISTINCT script_name FROM script_execution WHERE business_unit = '$business_unit';";
$script_list       = pg_query($connection, $script_list_query) or die ("Error in query: $check_query.". pg_last_error($connection));
# Store the number of scripts.
$no_of_scripts = pg_num_rows($script_list);
for ($i=0; $i < $no_of_scripts ; $i++) {
   $script_row = pg_fetch_row($script_list, $i);
   echo "<option value=\"".$script_row[0]."\">".$script_row[0]."</option>\n";
}
?>
</select>
<input type="submit" value="Lookup">;
</form>
<div id="someContainer"></div>
</body>
</html>

Open in new window

0
 

Author Comment

by:naveenraj
ID: 40482810
ALL I have decided to go with AJAX .

I have put in couple of scripts after referring to w3schools , google etc.

First script is to display a combo box a list of script names .

 <!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
  if (str=="") {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","getscript.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
<!--form name="frmParams" method="post" action="scriptCompletion.php" enctype="multipart/form-data"-->

<select name="scripts" onchange="showUser(this.value)">
<option value="">Select a script:</option>
<option value="db_config_chk.pl">db_config_chk.pl</option>
<option value="FI_TKOCheetahBMM_params.sh">FI_TKOCheetahBMM_params.sh</option>
<option value="USE_TKOCheetahBMM_matrix.sh">USE_TKOCheetahBMM_matrix.sh</option>
<option value="add_phobos_basket_params.pl">add_phobos_basket_params.pl</option>
</select>
<input type="submit" value ="Execute" onclick="executeScript(this.value)">
</form>
<br>
<div id="txtHint"><b>Script info will be listed here.</b></div>
</body>
</html>


Second script which is getscript.php

<?php
$q = $_GET['q'];

$dbhost = "xxx";
$dbname = "yyy";
$dbuser = "zzz";
$dbpass = "";
$connection = pg_connect ("host=$dbhost dbname=$dbname user=$dbuser password=$dbpass");
if (!$connection) {
   echo "Could not open connection to database server";
   die("Could not open connection to database server");
}

$sql="SELECT script_name, args FROM script_execution WHERE script_name = '".$q."'";
$script_list = pg_query($connection, $sql) or die ("Error in query: $sql.". pg_last_error($connection));
$no_of_scripts = pg_num_rows($script_list);

echo "<table border='1'>
<tr>
<th>Script Name</th>
<th>Args</th>
</tr>";

for ($i=0; $i < $no_of_scripts ; $i++)

{
   $script_row = pg_fetch_row($script_list, $i);
  echo "<tr>";
  # echo "<option value=\"".$script_row[0]."\">".$script_row[0]."</option>\n";
  echo "<td>" . $script_row[0] . "</td>";
  echo "<td> <input type=\"radio\" name=\"args\" value=\"args\"> $script_row[1] </td>";
}

echo "</table>";

?>


Using the above script I can show a page where there is a combo box listing the list of scripts. On selecting any script I will see the corresponding args and it is listed as radio button. Now my requirement is when I choose one of the option in the radio button ( ie - args of the script), I should be able to call a funtion by passing both the script name and the args. Using the script_name and args I will furhter query the database to get other parameters for the script and execute the script. This is my requirement.

I tired calling function executeScript by passing the values , but not sure how to capture the values of script name and the args in a variable and pass to the function. Please direct me how I can go ahead doing this.

thanks
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 40482958
Do NOT use the submit buttons click handler. Always use the form's submit handler.

In this particular case you cannot do what you want since the radios returned by the ajax are not wired

If you use jQuery it is MUCH simpler to do since you can delegate the clicks to the parent container.

Why do you have radios AND a select? Are you not just simply looking for a cascading select ?

To wire the returned radios you can do this in jQuery's load event ($(function() { ... }):

$("#txtHint").on("click",[name="args"],executeScript);
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40483343
OK I have looked at your code from the comment  ID: 40482810, like Michel Plungjan above, I am very puzzled by how you have set-up your Ajax returned <table> with the radios ? ? you have this as your select -
    "SELECT script_name, args FROM script_execution WHERE script_name = '".$q."'";
with the WHERE using the same  "script_name" as you have in the column returns , , SO that means ALL of the info displayed to the user (if the db SELECT returns more than ONE row) are the SAME "script name" for every radio button, the Difference between the radios, seems to be in the arguments (your args column), which the user does not see?, Then again if ONLY one row is ever returned for any "script Name", then the radios are a waist of time, as there would just be the One radio, with the SAME script name, as already chosen, by the user for the AJAX from the select? ? ?

I can do a functional javascript  AJAX without Jquery or any other framework, however your attempt at doing browser AJAX is to simplistic for any practical functioning Browser robustness,
especially this line -
     if (xmlhttp.readyState==4 && xmlhttp.status==200) {

you really need to separate the IF test for xmlhttp.status into another IF block, you really need to have ERROR CONTROL for the xmlhttp.status return,
   and You also HAVE to place in some kind of  variable to Block and prevent the user from clicking your AJAX function button Many times in a row (frustration), IF your server ajax response is SLOW, and they do not swiftly see a response from the button click, they WILL push it many times.

Sorry I do not understand what to mean to do with your radios, but as I said, you have a good start it seems, but I can not see what to recommend without some info about your different args for the same script name?
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
ID: 40483882
naveenraj,

We all can write ajax with pure JavaScript but unless you're doing this as a learning exercise, I'd suggest using a JavaScript framework like jQuery for the following reasons:

-- cross browser compatibility
-- code is easier to follow e.g. when debugging
-- simplifies your code so the logic of what your doing is clearer
-- easier for other programmers to pick up when using a standardised framework api

Remember that jQuery is just pure JavaScript bundled up in an easy to use api.

Rob
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40488015
* naveenraj
it has been a few days since you last response, and because Rob Jurd, suggested that you may be doing this as a way to learn the javascript for AJAX, I have fished out parts of some code from some other projects, and will show you this here to maybe help you learn. But be warned, that the browser - server - browser AJAX connection and exchange can get very complicated, especially for DEVELOPMENT testing and error control in a many factors-elements mobil web pages.

I almost never use the JSON CSV text response for ajax with data segments, I use a kind of multilevel CSV, using "/0", "/t", "/n", and "/r" delimiters.
first the browse file as an HTML page -
<!doctype html>
<html lang="en"><head><title>Ajax From Select</title>
<style>
body {background:#e3f7ff; height:100%;}
h2 {color:#c40; text-align:center;}
.fm {color:#00b;}
.fm input{margin-left:16px;}
.userRadio {display:inline-block; border:1px solid #aaa; padding:6px; margin:10px;}
#txtHint {width:733px; border:2px solid #fab338; padding:8px; margin:10px;}
.show {width:513px;padding:8px; margin:10px; background:#bbb; border:2px solid #55b;}
</style>
<script>/* <![CDATA[ */
var ajaxObj = false, busy = true, devel = false, radioDiv = false, radioOPP="no";
// start with busy = true to STOP all ajax functions, until ajax is confirmed

// for easier coding use id2dom instead of document.getElementById
function id2dom(elmt1){return document.getElementById(elmt1);}
if(document.all)id2dom=function(elmt1){return document.all[elmt1];}
function setInnr(elmt1,out1){var Dobj=id2dom(elmt1); Dobj.innerHTML=out1; Dobj=null;}

function iniAJAX(){var xmlh=false;
/*@cc_on
@if (@_jscript_version>=5)try{xmlh=new ActiveXObject('Msxml2.XMLHTTP.4.0');} catch(e){
	try{xmlh=new ActiveXObject("Msxml2.XMLHTTP");} catch(e){
	try{xmlh=new ActiveXObject("Microsoft.XMLHTTP");} catch(E){xmlh=false;}}}
	@else xmlh=false;
@end @*/
if(!xmlh&&typeof XMLHttpRequest !='undefined'){try{xmlh=new XMLHttpRequest();} 
catch(e){xmlh=false;}}
return xmlh;
}

function getData(sn) {
// this is the AJAX send function for the select input change
// NEVER allow more than one type of AJAX request until the last request returns and busy is false
  if(busy) return;
// IMPORTANT, you should use encodeURIComponent() if there is any punctuation in URL string
  ajaxObj.open("GET","ee-select.php?sn="+encodeURIComponent(sn),true);
  if(ajaxObj.timeout) ajaxObj.timeout=2800;// set a timeout for slow server
  ajaxObj.onreadystatechange = ajxChange;
  busy = true;// stop any other request
  ajaxObj.send(); //start ajax contact send
}

function showRadio( ) {
// this is the button click to send the Radio by ajax
  if(busy) return;
  var ckValue = "", rd = document.getElementsByName('rds');
// test the radios in rd for a checked as true
  for (i = 0; i < rd.length; ++i) 
    if (rd[i].checked) {ckValue = rd[i].value; break;}
// this is an ajax POST send, which is different than a GET
  ajaxObj.open('POST', "ee-select.php", true);// same php page
  if(ajaxObj.timeout) ajaxObj.timeout=2600;
// in a POST, you must build the URL send string without the first ? 
  var send2 = 'job='+radioOPP+'&aug='+encodeURIComponent(ckValue);
  ajaxObj.onreadystatechange= ajxChange;
  ajaxObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajaxObj.setRequestHeader ("Content-length", send2.length);
  ajaxObj.setRequestHeader ("Connection", "close");
  busy = true;
  ajaxObj.send(send2);
}

function ajxChange() { // ALL Ajax return trafic is handled by only this function
  if(ajaxObj.readyState==4){ busy=false; // a false busy will allow ajax function to work
    if(ajaxObj.status==200){
      if(ajaxObj.responseText.length < 5){alert("ERROR - Server response text less than FIVE");return;}//length error
// FOR DEVELOPMENT ONLY, all responseText is shown in the showText div without < tag
      devel.innerHTML = ajaxObj.responseText.replace(/</g, "&lt;").replace(/>/g, "&gt;");//replace < and >
	  
// ALL correct response have "*" as FIRST character, error if NOT because there is a PHP warning or fatal
      if(ajaxObj.responseText.charAt(0) != "*"){alert("ERROR - Server responce had server language Errors");return;}
// the server response is split into the oArray for the null "\0" delimiter, 
      var oArray = ajaxObj.responseText.split("\0");
      if(oArray.length<2){alert("ERROR Array.length Less THAN 2.");return;}
// you can have Many different responses from a single ajax call by using switch( )
      switch (oArray[0]){
//the First array element defines the "Kind" of responce from server
// three are used here "*radios", "*show" and "*error"
        case "*radios":
          id2dom("but1").disabled = false;
          id2dom("but1").innerHTML = "Submit The Radio Above";
          radioDiv.innerHTML = oArray[2];
// radioOPP is the kind of radio operation to send in the showRadio( ) function
          radioOPP = oArray[1];
		  setInnr("showText", "No Show YET");// reset the Show div
		  break;
        case "*show":
          setInnr("showText", oArray[1]);// show the lists from php in showText
          break;
// IMPORTANT, you need to have error control for server misses or user input to ajax errors
        case "*error": alert('ERROR - server processing: '+oArray[1]); break;
        default: alert('ERROR - Not able to use operation code# '+oArray[0]);
        }
      } else alert("ERROR - Server Unable to Return. error status code: "+ajaxObj.status);
// I did NOT do status errors, you should at least have a 404 status error
	}
} // end ajxChange function



ajaxObj = iniAJAX(); // create Ajax Object
if(!ajaxObj) alert("ERROR, your BROWSER is NOT able to use this SITE due to Javascript incompatablity");
  else busy = false; // set busy to false so functions will work
/* ]]> */</script>
</head><body>
<h2>Ajax Using Select</h2>
<form name="form1" class="fm">
Please choose a Script from the drop down below -<br />
<select name="scripts" id="sel1" onchange="if(this.value) getData(this.value)">
<option value="">Select a script:</option>
<option value="db_config_chk.pl">db_config_chk.pl</option>
<option value="FI_TKOCheetahBMM_params.sh">FI_TKOCheetahBMM_params.sh</option>
<option value="USE_TKOCheetahBMM_matrix.sh">USE_TKOCheetahBMM_matrix.sh</option>
<option value="add_phobos_basket_params.pl">add_phobos_basket_params.pl</option>
</select>
<br /><div class="userRadio">
<div id="radioDiv">
<input type="radio" name="rd1" value="n" disabled /> No Script,
</div>
</div>
</form>
<button id="but1" onclick="showRadio( )" disabled>Disabled until You Select</button>
<div id="showText" class="show">
No Show YET
</div>
<hr>
Development AJAX responce Info is below -
<div id="DelvOut" style="padding:8px; border:2px solid #cde;">No Ajax yet</div>
<br /><br />
<script>/* <![CDATA[ */
// get a continuous delevopment object in devel and radioDiv
devel = id2dom("DelvOut");
radioDiv = id2dom("radioDiv");
/* ]]> */</script>
</body></html>

Open in new window


next as the php page as  ee-select.php in the ajax request , all of the RADIO names and Values are just made up by me , since I do not know what to have in yours. Also I do NOT do any database access in this, because that is not part of the problem here. -
<?php
/* CONVENTIONS for the AJAX sent back
the only string OUTPUT will go in the $out  variable
All out strings will begin with an asteric '*', to Test in browser to see if there is PHP errors or warnings

The string of output will be Comma Separated Values using the "\0" (null) charater for the separator

Error output will begin with the "*error" identifier

output will always be in Plain Text Content

the PHP switch( ) is used to produce Different returns for different ajax Inputs
*/
ini_set('display_errors', 1);
error_reporting(E_ALL); // for DEVELOPMENT show all errors
header('Cache-Control: no-cache');
// Change the server Type output to text/plain, as this is NOT a web page output
header('Content-Type: text/plain');
$out = 'Access Error 643, ERROR - Page Unavailable for Server Access, errorcode: 643 Non Responce: nr55 ';
// the above output for error, so if this page is accessed by search engine or other NON ajax access without the "GET" request

// test for, and Use the radios POST
if (isset($_POST['job']) && isset($_POST['aug'])) {
  $out = '*show'."\0";
// the $aug is an array from the comma delimited $_POST['aug'] produced by the explode( )
  $aug = explode(',', $_POST['aug']);
  $lst = '';
// make a numbered List tag for each $aug element
  for ($i = 0; $i < count($aug); ++$i) $lst .= '<li>'.$aug[$i].'</li>';
  switch($_POST['job']){ //there are three case for corrct input
    case 'scr0': $out .= '<h2 style="text-align:center;">Job as '.$_POST['job'].
      ', for SCRIPTS</h2>Submitted AUGS are listed Below<ol>'.$lst.'</ol>'; break;
    case 'val1': $out .= '<div style="text-align:right; color:#08b; font-size:30px;">Job as '.$_POST['job'].
      ', for Values</div>Submitted AUGS are listed Below<ol>'.$lst.'</ol>'; break;
    case 'dir2': $out .= '<div style="text-align:left; color:#d0d; font-size:12px;">Job as '.$_POST['job'].
      ', for Directory</div>Submitted AUGS are listed Below<ol>'.$lst.'</ol>'; break;
// ALWAYS have a default:  case for ERROR, use unique errorcode ID for error reporting
    default: $out .= "error\0".'Server Request could not be processed, errorcode: sh6271';
  }
  header('Content-Length: '.strlen($out));
  exit($out);
}

// this is a Simple Ajax GET for the Select request to server below
if (!isset($_GET['sn'])) exit($out);
$sn = (strlen($_GET['sn']) < 6)? '': $_GET['sn'];// test for Minimum ['sn'] length
if($sn) {
  $out = '*';
  switch($sn){ // I only do the first three select values, the fourth will error out
    case 'db_config_chk.pl': $out .= 'radios'."\0".'scr0'."\0".
'<input type="radio" name="rds" value="ab,cd" checked /> script 0
<input type="radio" name="rds" value="ef,gh,ij" /> script 1
<input type="radio" name="rds" value="kl,mn" /> script 2
<input type="radio" name="rds" value="op,qr,st,uv" /> script 3'; break;
    case 'FI_TKOCheetahBMM_params.sh': $out .= 'radios'."\0".'val1'."\0".
'<input type="radio" name="rds" value="z1" checked /> Do Z values
<input type="radio" name="rds" value="y1,y2" /> Do Y values
<input type="radio" name="rds" value="x1,x2,x3" /> Do X Values
<input type="radio" name="rds" value="w1,w2,w3,w4" /> Do W values
<input type="radio" name="rds" value="v1,v2,v3,v4,v5" /> Do V values'; break;
    case 'USE_TKOCheetahBMM_matrix.sh': $out .= 'radios'."\0".'dir2'."\0".
'<input type="radio" name="rds" value="Nor" checked /> North
<input type="radio" name="rds" value="est,wst" /> East
<input type="radio" name="rds" value="nor,up,back ward" /> South'; break;
    default: $out .= "error\0".'Server Request could not be processed, errorcode: db1726';
    }

  }
// not necessary but helpful in Ajax to include content length
header('Content-Length: '.strlen($out));
echo $out;
?>

Open in new window


as I said, it took me years of buildin and testing to get a good understading of the Ajax processes and some of the many "Options" to be used for effective mobil web page user experience.
I hope you can find some help with these codes
0
 

Author Comment

by:naveenraj
ID: 40489036
Hi Slick812, I am finding AJAX more complicated at the moment. I think I need to spend some more time to learn and understand . Thanks for your time and the code examples. I could use AJAX but what I noticed is extending it to my project seems to be tough if I am not familiar enough with it . So I am going to stick with simple javascript function to be called from a php page.

As many of the experts were asking as why i need a radio button is to show the args whatever the user wants to use. There might be a single or more than 1 arg and user can chose one of it and exeute it.

I am still working on the best way to do it.

So my request is in the first php page to list down the various scripts available and user on selecting one from the drop down list i have to show in the same form by calling onChange event ( which I am unable to do at the moment) because once I capture the script in a variable I need to call the db again from php to find all the args . So I am trying to load a new form and show the arguments as a list of radio button options. The problem I am facing now is to unable to store both the variables script and its argument in the new form to use it to call the database. still working on it, will post more info when i have. thanks
0
 

Author Comment

by:naveenraj
ID: 40489102
Hi Slick812, you mentioned in your earlier comments
"The first option is to place ALL of the "args corresponding to the script name" for ALL of the different script names into a Javascript array or object for storage, and then when the user makes a Selection change, you use javascript function to read the "args" from the Javascript array or object, and display them to the user."

Can you provide an example code snippet. I am finding it tough / so far unsuccessful to call a java script on the same form on the change event when a script is selected from the drop down box and showing all the args corresponding to the script with radio button/cehck box on the same page so the user can select one of the optional args.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40489409
OK, to NOT use ajax, and just get ALL of the necessary "data" or strings that are needed for ALL of the options in your select choice, then Transfer these "data" and or strings to the Javascript as Containers (array or object), that you can use the select choice to just get the array element and display as a group of radio buttons, with the values for that radio group.

I will do some code later maybe, first I will give u the code thinking, that I use to do this.
You will have a DB SELECT to get the several "args" for a script file name,
    IMPORTANT, at this point YOU must decide if you will be better to add the "HTML" formatting in the PHP server code, OR,  add the "HTML" formatting (<input type="radio">)  in the javascript browser code. Often the code procedures will be nearly identical (except code syntax). . So for me, if the added "HTML" is lengthy and not a complexity of IF tests for changes in the class or style, I will use the javascript, and just pass down the radio "name" and "args" strings to the javascript array. But mostly I try and do ALL "HTML" formatting on the server side in PHP, because I can deal with the raw DB row data directly and just add the html for <input type="radio"> to one string or an array of strings, something like this -
$jsOutArray = array(array( ));
$group = 0;
$jsOutArray[$group] = '';
// query SELECT DB
// do fetch row get row as $row, and loop to get All args
// add the HTML to the $row->args and  $row->displayName for radio display (and table <td> or other text)
$jsOutArray[$group] .= $row->displayName.' <input type="radio" name="rds" value="'.$row->args.'" /> - ';
// code produces 3 Rows so there are 3 radios in group 0, increase $group by one - ++$group
// for next SELECT add radios to second group

// when ALL script names are done (you have 4 in your example like db_config_chk.pl) 
//each script will have a separate group of radios
// now try and place ALL of the PHP array strings in to javascript arrays

echo "<script>\n";
$jsCode = '[';    // start JS group array with a [
for ($g = 0: $g < count($jsOutArray): ++$g) {
    $jsCode += jsOutArray[$g]."\\n"; // double escape here ! !
  // IMPORTANT, WARNING, You must use DOUBLE escapes in php to get a valid single escape in js
  // you will need to practice and evaluate code output for special characters like \n \t \r for php-2-js variable
  if ($g < count($jsOutArray)-2) $jsCode = ','; // add comma for new array element
  }
$jsCode = ']'; // end group array
echo 'var groupArray = ',$jsCode,'
</script>';

Open in new window


now when you write the <select> it will be easier if you use the array numbers as Option values instead of the script names -
<select name="scripts" id="sel1" onchange="if(this.value) doRadios(this.value)">
<option value="">Select a script:</option>
<option value="0">db_config_chk.pl</option>
<option value="1">FI_TKOCheetahBMM_params.sh</option>
<option value="2">USE_TKOCheetahBMM_matrix.sh</option>
<option value="3">add_phobos_basket_params.pl</option>
</select>

// the doRadios( ) function might be something like -
<script>
function doRadios( val )  {
  val = parseInt(val);
  document.getElementById("radioDiv").innerHTML =  groupArray[val];
}
</script>

Open in new window


this is untested code work to show the thinkin I use to get PHP data-strings to JS variables

you could also just push the raw un-formatted strings for displaName and args into a two JS arrays (one for names and one or args) and then add the HTML (<input type="radio") with a javascript build
0
 
LVL 33

Expert Comment

by:Slick812
ID: 40489536
I just realized That I did NOT place the quotes in the JS code array to signify a String for the JS array elements so -

for ($g = 0: $g < count($jsOutArray): ++$g) {
    $jsCode .= "'".jsOutArray[$g]."'";// these single quotes assume that there ARE NO single quotes in string
  if ($g < count($jsOutArray)-2) $jsCode .= ",\n"; // add comma for new array element
// do NOT double escape this new line
  }

I also FORGOT which code language syntax I was using at the time, as I always place + in PHP and . in JS by mistake for String joiners.
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 40489792
There are certain problems with getting the PHP code strings from php arrays or variables, and getting them into correct syntax for javascript to write the JS variables from PHP, this has mostly to do with using Line breaks to get the page source code so you can read it, and then having escape characters in PHP and placing escape characters into your string for javascript, Also getting correct placement for the quotes that distinguish strings in JS and then having PHP to escape any quotes inside the string.. . In the following code I do NOT do any complicated string escaping, since the radios do not have any single quotes in the html.
<!doctype html>
<html lang="en"><head><title>Ajax From Select</title>
<style>
body {background:#e3f7ff; height:100%;}
h2 {color:#c40; text-align:center;}
.fm {color:#00b;}
.fm input{margin-left:16px;}
.userRadio {display:inline-block; border:1px solid #aaa; padding:6px; margin:10px;}
#txtHint {width:733px; border:2px solid #fab338; padding:8px; margin:10px;}
.show {width:513px;padding:8px; margin:10px; background:#bbb; border:2px solid #55b;}
</style>
<script>/* <![CDATA[ */
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL); // for DEVELOPMENT show all errors
	
function rows2js($rows, &$jsc) {
$chec = 'checked';
foreach($rows as $row) {
  $jsc .= '\'<input type="radio" name="rds" value="'.$row->args.'" '.$chec.'/> '.$row->dName."'+\n";
  $chec = '';
  }
$jsc = substr($jsc, 0, -2);
}

// I will NOT do a DATA BASE SELECT, just pace values into a $row object
	
// do DB SELECT and loop rows  while($row = $result->fetch_object()) {
$results= array((object) array('args'=>'ab,cd','dName'=>'script 0'),
  (object) array('args'=>'ef,gh,ij','dName'=>'script 1'),
  (object) array('args'=>'kl,mn','dName'=>'script 2'));
$jsCode = '[';
rows2js($results, $jsCode);
$jsCode .= ",\n";

// another SELECT from DB here
$results= array((object) array('args'=>'z1','dName'=>'Do Z values'),
  (object) array('args'=>'y1,y2','dName'=>'Do Y values'),
  (object) array('args'=>'x1,x2,x3','dName'=>'Do X values'),
  (object) array('args'=>'w1,w2,w3,w4','dName'=>'Do W values'));
rows2js($results, $jsCode);
$jsCode .= ",\n";

// another SELECT from DB here
$results= array((object) array('args'=>'so,what','dName'=>'S + W'),
  (object) array('args'=>'joke,laugh','dName'=>'Ha + Ha'),
  (object) array('args'=>'clean,dirt,mess','dName'=>'Hi + Dry'),
  (object) array('args'=>'cop,rob,cap','dName'=>'Jail + Fine'));
rows2js($results, $jsCode);
$jsCode .= ",\n";

// another SELECT from DB here
$results= array((object) array('args'=>'kool,up','dName'=>'North'),
  (object) array('args'=>'fast,slow,no','dName'=>'East'),
  (object) array('args'=>'left,right','dName'=>'South'));
rows2js($results, $jsCode);
$jsCode .= ']'; // end array with ]


echo 'var grpArray = ',$jsCode; // write PHP to the page source as javascript
?>
	
function doRadios(val) {
val = parseInt(val);
document.getElementById("radioDiv").innerHTML = grpArray[val];
}

/* ]]> */</script>
</head><body>
<h2>Ajax Using Select</h2>
<form name="form1" class="fm">
Please choose a Script from the drop down below -<br />
<select name="scripts" id="sel1" onchange="if(this.value) doRadios(this.value)">
<option value="">Select a script:</option>
<option value="0">db_config_chk.pl</option>
<option value="1">FI_TKOCheetahBMM_params.sh</option>
<option value="2">USE_TKOCheetahBMM_matrix.sh</option>
<option value="3">add_phobos_basket_params.pl</option>
</select>
<br /><div class="userRadio">
<div id="radioDiv">
<input type="radio" name="rd1" value="n" disabled /> No Script,
</div>
</div>
</form>

</body></html>

Open in new window

this works in firefox for me. . as I said dealing with every different situation for the escape characters from PHP to JS took me some time to learn. I try to not use any methods that have escape characters in the transform code work.
0
 

Author Closing Comment

by:naveenraj
ID: 40493632
Works perfect and this is what I am looking for except I don't get the  object array. Is this the only way the object array could be declared.  Please can you explain the declaration of the variable $results and the array of objects inside it.
0
 

Author Comment

by:naveenraj
ID: 40494043
Hi Slick812, I got it all about the group array after doing my own research. All good. thanks, no more explanation needed.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Get to know the ins and outs of building a web-based ERP system for your enterprise. Development timeline, technology, and costs outlined.
This video teaches users how to migrate an existing Wordpress website to a new domain.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now