populate dropdown onload by passing php array to javascript function - javascript

im trying to pass a php array to javascript function onload that will display the js array in a drop down list but now im already doing it for sometime i guess i need to pop it again
first i pass it from one php file to another using this code
header("location: Rules.php?varFields=".serialize($varFields));
secondly i transfer to another variable as it had been passed to the said php file
<?php
$varArray = unserialize($_GET['varFields']);
?>
third part is im tyring to pass it into a jS functon that will then display it to a drop down list
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
and here is the external javascript code
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.stringify(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in varDisplay)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
for the first two part i already tested it and it is working but for the last parts i cant make it work

I think this part looks suspicious
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
maybe
<body id="body" onclick="cmbRuleField(<?php echo json_encode($varArray);?>)">
is more like it.
One more tip, you can see the output on the rendered page to determine what the written out code looks like. So if you see something like:
<body id="body" onclick="cmbRuleField('['a', 'b']')">
you know there is a problem. You want a native Javascript array to be passed like this
<body id="body" onclick="cmbRuleField(['a', 'b'])">
EDIT
After talking on chat it became clear the top portion of OP's code needed a tweak as well.
header("location: Rules.php?varFields=".http_build_query($varFields));

The problem has to do with quotes not being terminated here:
...
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
...
The JSON created using json_encode will have a lot of double quotes. Try this:
<script>
var array = <?php echo json_encode($varArray);?>;
</script>
<body id="body" onclick="cmbRuleField(array);">

There is a much easier way. Encode the $varArray as direct HTML options before sending to the browser. For instance:
<select id="ruleField">
<?php for ($i = 0; $i < count($varArray); $i++) { ?>
<option value="<?php= $varArray[$i].val ?>"><?php= $varArray[$i].name ?></option>
<?php } ?>
</select>

Might be because you are calling JSON.stringify on something that is already a string?
Also what is myCars?
..
for (var i in myCars)
..
Possibly rename it to varArray.
or rename varDisplay to varArray.
and lastly try calling JSON.parse instead:
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.parse(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in myCars)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
If that didn't work post the html output here so peeps can create a fiddle :)

Related

HTML form select to drive PHP/SQLSRV results

I'm working on a very basic web page to facilitate data entry. I have it working with PHP talking to SQL Server to both enter and display data. At the simplest level, they'll select a store from a dropdown and enter some data, then hit submit.
I'm trying to dynamically display the last 7 days worth of data when their store is chosen from the form select input. How do I get the Select value to drive the SQL query? I found how to use onchange to fire a javascript function, which I can alert the value. Do I really need to then use jquery or AJAX to link that back to the PHP select query or is there a simpler way to approach this?
I'm trying to learn this all from scratch and am quite admittedly out of my element. Here are some snippets of what I've got:
...
<script>
function OnSelectChange(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
</script>
...
<td align="right">Store</td><td width="125"><select style="width:100%" name="store" onchange="OnSelectChange(this)">
...
<?php
$tsql = "select * from test where DateStamp >= getdate()-7";
$stmt = sqlsrv_query($conn, $tsql);
//generate table view of data
echo "<table>";
echo "<tr><td>Store ID</td><td>Date</td><td>Data</td></tr>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$StoreID = $row['StoreID'];
$DateStamp = $row['DateStamp'];
$Donations = $row['Data'];
echo "<tr><td>".$StoreID."</td><td>".$DateStamp."</td><td>".$Data."</td></tr>";
}
echo "</table>";
?>
I've found a lot of helpful information to get me this far, but am stuck now.
Thank you in advance.
Got it! For anyone else looking, here are relevant snippets of code:
<style>
.hideable {
visibility: collapse;
}
</style>
...
<script language="JavaScript">
function OnSelectChange(cl)
{
var els = document.getElementsByClassName('hideable');
for(var i=0; i<els.length; ++i){
var s = els[i].style;
s.visibility = 'collapse';
};
var els = document.getElementsByClassName(cl);
for(var i=0; i<els.length; ++i){
var s = els[i].style;
s.visibility = 'visible';
};
}
</script>
...
<select style="width:100%" name="store" onchange="OnSelectChange(this.value)">
...
echo "<tr class='hideable ".$StoreID."'><td>".$StoreID."</td><td>".$DateStamp."</td><td>".$Data."</td></tr>";
Leveraging dual classes upon the table (tr) creation and the collapse CSS style property was key.

Convert PHP objects array to javascript array

I retrieve image paths with the function get_all();. This get_all function retrieves images as an object. This object has the attributes name, source_path and date. I want my javascript to add images to a div. I have the following:
The instantiate.php includes files like Jquery and another JS file.
<?php
require_once("../../include/instantiate.php");
$photos = Photos::get_all();
$JSPhotos;
foreach($photos as $photo) { $JSPhotos + $photo->source_path; }
?>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($JSPhotos); ?>;
for(var i = 0; i <= 10; i++)
{
create_image("../"+photos[i]);
}
});
This does not work. Anyone got a solution?
Solution in Jeroen's Post!
New Problem;
In the create_image function I set the class and src of the image element. When you click such an image I want an alert box to show up. I have checked if the class is set correctly, and I concluded that all images did have the classname "imgid". So, any idea why this dont work?
Script in the javascript part:
$(".imgid").click(function() {
alert("hey");
});
You are not assigning anything to your variable.
You probably want:
$JSPhotos = array();
foreach($photos as $photo) {
$JSPhotos[] = $photo->source_path;
}
Or something similar.

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

Why is the javascript variable undefined? (2nd time around...)

I am reposting this question with revised code that use more of jQuery.
Here is the HTML code that defines the objects:
<LEGEND><b>Select Study Sample</b></LEGEND>
<p>
<P CLASS=select_header>Study - Box - Well - Lab ID<br>
<SELECT multiple size=20 NAME="stylabid" ID="stylabid" onchange=show_stylabid() onclick=clear_fetch() STYLE="width: 115px">
<?php
$i=0;
while ($i < $numstylabids) {
$styarr = pg_fetch_row($stylabidresult);
echo "<option value=$styarr[0]>$styarr[1]\n";
$i++;
}
?>
</select>
and
<LEGEND><b>Select Project Sample</b></LEGEND>
<p>
<P CLASS=select_header>Project - Box - Well - Lab ID<br>
<SELECT multiple size=20 NAME="pjtlabid" ID="pjtlabid" onchange=show_pjtlabid() onclick=clear_fetch() STYLE="width: 115px">
<?php
$j=0;
while ($j < $numpjtlabids) {
$pjtarr = pg_fetch_row($pjtlabidresult);
echo "<option value=$pjtarr[0]>$pjtarr[1]\n";
$j++;
}
?>
</select>
Now, here is the javascript; I am simply trying to get the values of the selected object, which can be either a Study or a Project. I use this later to retrieve data from the database:
function fetchgenotype() {
var ms, mndx, ss, sndex = 0;
ms = $("#marker")[0].selectedIndex;
if (Study_selected) {
ss = $("#stylabid")[0].selectedIndex;
sndx = $("#stylabid").val(ss);
} else
ss = $("#pjtlabid")[0].selectedIndex;
sndx = $("#pjtlabid").val(ss);
}
// for debugging...
alert('ss='+ss+', sndx='+sndx);
This code dies on the line sndx = ... Would really appreciate any help!
TIA
Currently i don't know what $("#marker") an Study_selected are.
Assuming there is anything OK so far, change the function into:
if (Study_selected) {
sndx = $("#stylabid").val();
} else
sndx = $("#pjtlabid").val();
}
val() returns the value of a form-element when used without an argument, otherwise it will set the value and return an jQuery-object.
There is no need to retrieve the selectedIndex, you may access the value of the select-element directly(it will be the value of the currently selected option)
I think you have a syntax error
sndx should be sndex .. or the other way around
var ms, mndx, ss, sndex = 0; // <--
$("#pjtlabid").val(ss) // <-- setter method
.val(value) is also a setter method so sndx is undefined because it never was defined with any value
It's a typo:
var ms, mndx, ss, sndex = 0;
should be
var ms, mndx, ss, sndx = 0;

Is it possible to use a for loop in <select> in html? and how?

I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/

Categories