Iterate through php array in jquery - php

So I have a php array that I am JSON encoding and handing to some JQuery. Basically I am using the information from the array to dynamically change the content of one drop down based on the value of another drop down. I am running into some problems with the JQuery though as JQuery is pretty new to me.
First off my PHP:
<?php
$sql = mysql_query("SELECT * FROM menu") or die(mysql_error());
$menuItems = array();
$x = 0;
while($row = mysql_fetch_object($sql))
{
$menuItems[$x]['ID'] = $row->ID;
$menuItems[$x]['parent'] = $row->parent;
$menuItems[$x]['name'] = $row->Name;
$menuItems[$x]['header'] = $row->header;
$menuItems[$x]['Sort'] = $row->sort;
$x++;
}
?>
This code returns an array of ~30 menu items.
Then my JQuery:
<script>
var menuItems = <?php echo json_encode($menuItems); ?>;
$('#dropdown1').change(function (){
if($('#dropdown1').val() == 0){
$('dropdown2').children().remove().end()
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
$('#dropdown2').options[menuItems[x]['sort']] = new Option(menuItems[x]['name'], menuItems[x]['sort']);
}
}
}
});
</script>
What I want this to do is when dropdown1 is changed, dropdown2's options are removed and then repopulated with specific things from the array.
Currently this code does delete the options for dropdown2 when dropdown1 is changed but re-population just isn't working. From what I can tell in testing, the for loop to iterate through the array is only entered once, despite their being about 30 items in it and I assume that is were my main problem is.
What am I doing wrong here?

change it to
for(var x = 0; x < menuItems.length; x++){
if(menuItems[x]['header'] == 1){
var option = $('<option />', {
text : menuItems[x]['name'],
value: menuItems[x]['sort']
});
$('#dropdown2 option[value="'+[menuItems[x]['sort']]+'"]').replaceWith(option);
}
}
$('#dropdown2').options[] is not valid, as jQuery doesn't have those methods, that's for plain JS DOM nodes.

So from the comments there seemed to be some confusion on what I meant, and I apologize. It was one of the instances where the explanation made sense to me, but I just must not have conveyed everything well enough.
To clear up a little bit of the confusion. The array that was passed from the PHP code to the javascript contained everything I could ever need for the second drop-down.
As many pointed out the .options[] was the culprit for why the code wasn't executing. This was simply from another example I had found, and with my limited knowledge I assumed it was correct, and it wasn't.
I instead used the the .append() function and things seem to be working normally now.

Related

HTML, PHP, JavaScript -- How to make a button for each individual record in a database? Seems simple but doesn't work

I have an SQL database (I know for sure it includes remote access, if that's necessary to access a database through php). It definitely has at least one record in it, and I need to get each record and create a corresponding button that links to a php file, taking the first field for that record as a/n argument, variable, parameter, or whatever you call the whatever.php?variable=value.
For some reason, this code just gives me a blank page. Why?
<?php
$connection=mysqli_connect("myhost","myusername","mypassword","mydatabase");
$result=mysqli_query($connection, "SELECT * FROM myTable");
$resultArray=array();
while ($row = mysqli_fetch_array($result)) {
array_push($resultArray, $row['ID']);
}
$resultArrayImplode = implode(",", $resultArray);
?>
<script>
var resultArray = <?php echo $resultArrayImplode; ?>
arrayEntries = new Array();
arrayEntries = resultArray.split(",");
function CreateButtons(element, index, array) {
var button = document.createElement("input");
button.type = "button";
button.value = element;
button.onclick = function() {
document.location.href = "ButtonClicked.php?id=" + element;
}
document.body.appendChild(button);
}
arrayEntries.forEach(CreateButtons);
</script>
Thanks!
Your javascript assignment to resultArray is probably not syntactically correct due to quote characters, etc. Luckily, PHP's JSON functions automagically create good javascript for you.
Try this for the javascript output:
var arrayEntries = <?php echo json_encode($resultArray)?>;
Your problem is $resultArrayImplode; is a string, so
var resultArray = <?php echo $resultArrayImplode; ?>
renders as:
var resultArray = 1,2,3,4,5
Which is a syntax error.
What you can do is use JSON. JSON syntax is JavaScript syntax, so all you need to do is:
var arrayEntries = <?php echo json_encode($resultArray); ?>;
This should render as something like:
var arrayEntries = [1,2,3,4,5];
Which is perfect JavaScript syntax. Then the rest of your code should work.
I just don't see why do you need to use javascript for this, cant you just do the following :
<?PHP
foreach($resultArray as $result)
{
?>
Im a button click me</div>
<?PHP
}
?>
in my opinion, i see no real need for you to use javascript for this.

Javascript countdown not working for php loop

Hello i me and a friend have a maffia game. I have a countdown timer code but it only works when i use one timer. But i need to use it in a loop to get more timers in a table. I searched on google but nothing really helped. I saw that i had to use different id's but that didn't work for me. I have little knowledge of javascript.
This are my codes:
While loop:
while($info = mysql_fetch_object($dbres))
{
$j = 0;
$bieding = mysql_fetch_object(mysql_query("SELECT `bedrag` FROM `biedingen` WHERE `veilingid`='{$info->id}' ORDER BY `bedrag` DESC LIMIT 1"));
$tijd = ($info->tijd + $info->duur * 60 * 60 - $time);
echo '<tr>
<td>'.veilingnaam($info->id,1,1).'</td>
<td>'.usernaam($info->veiler,1,1).'</td>
<td>€'.getal($bieding->bedrag).'</td>
<td><div id="teller'.$j.'"></div></td>
</tr>';
}
Javascript part:
<script type="text/javascript">
var seconds = <?= ($tijd+1) ?>;
var countdown = document.all? document.all["teller<?= $j?>"] : document.getElementById? document.getElementById("teller<?= $j?>") : "";
var woord = "seconden";
function display()
{
seconds=seconds-1;
if(seconds==1){ woord="seconde"; }
if(seconds==0){ woord="seconden"; }
if(seconds<0)
{
self.location.replace(self.location);
}
else
{
if (countdown)
{
countdown.innerHTML=seconds+" "+woord;
setTimeout('display()',1000);
}
}
}
display();
</script>
Your while loop goes through table rows in a DB, but your JavaScript code is not part of that loop. That means you generate a HTML table for each row, but then you create <script>...</script> which includes $tijd/$j only for the last row (assuming that your while executes before the script is added to the page.
Possible workarounds:
Add a jQuery's selector, something like $("div.teller").each(function(){...}); and in that function create a timer and/or any other JavaScript code you need associated with that div.Note that this requires your div to get a CSS class "teller".
Create all JavaScript code that is needed for each DB's table row inside the PHP's while loop, but this would probably get really messy.
Also, I advise you to take a look at JavaScript's setInterval(), since it is more appropriate than setTimeout() for what you want to do.
Another thing to consider: all your timers would have a one second tick. It seems to me that it is better to have a single timer and just keep numbers of seconds (whatever that might be) in a JavaScript array (this one is easily created in PHP's while loop).
Edit: Here is one way to do this:
$data = array();
while($info = mysql_fetch_object($dbres))
{
... /* your current code */
$data[] = "{ id: 'teller$j', seconds: $tijd }";
}
$data = "[ ".implode(", ", $data)." ]";
Now, create your JavaScript code outside of the loop:
<script type="text/javascript">
var data = <?php echo $data; ?>; // It is not advisable to use <?= ... ?>
// Get references to divs via saved ids (seconds are already saved
for (i = 0; i < data.length; i++)
data.div = document.getElementById(data.id); // No need for document.all; IE supports getElementById since version 5.5
...
</script>
Now, adapt display() to work with the elements of your data array.

Calling individual Divs by id from PHP generated list using jQuery

I am generating divs in PHP, from an array, thus:
echo "<div id='parentdiv'>";
for($counter = 0; $counter < count($list); $counter++){
echo "<div>".$list['important_info']."</div>";
}
echo "</div>";//parentdiv
I want to add some click functionality to each div independently, i.e. the action performed on clicking depends on the div, and more importantly the index of the array, $list;
I want to give each div an id based on it's index in the PHP array.
So I could do
echo "<div id='"."divindex_".$counter."'>".$list['important_info']."</div>";
where "divindex_" is just used to prevent the id form beginning with a numeric value.
Then, I think in jQuery I can write click functions for each div.
However the problem is the $list size is variable, so I don't know how many divs there are.
So what I'm thinking is something like,
$("#parentdiv div").click(function(){
var id = split($(this).attr('id').split("_")[1];//get the php index from the id
//do something with the id, e.g. ajax or whatever
  });
Is there a better way to do this? If you think what I'm doing is strange and not a very good idea, then I understand. But I don't know how to do this any other way. Any help appreciated.
Simply use:
$("#parentdiv div").click(function(){
var id = $(this).index(); //index of div, 0 based
var val = $(this).text(); //content of div, if you need it
});
No need to add unique IDs :) .
Demo:
http://jsfiddle.net/q9TaJ/
Docs:
http://api.jquery.com/index/
First, make sure to properly escape your outputs:
echo '<div id="parentdiv">';
for ($counter = 0; $counter < count($list); $counter++){
echo sprintf('<div data-id="%d">%s</div>',
$counter,
htmlspecialchars($list['important_info'])
);
}
echo '</div>';//parentdiv
I'm also using a special attribute called data-id which you can easily access in jQuery with this code:
$('#parentdiv > div').on('click', function() {
var id = $(this).data('id');
});
you can pass your variables as html attributes. Then bind the click event to a single class.
<div class="divs" data-id="myid"></div>
in jquery
$('.divs').click(function(){
console.log($(this).data('id));
});

Auto refreshing unlimited divs

I am currently able to refresh a div on my website using jquery with php. This works well to a point. The issue is that the data being refreshed currently is an entire table. The code being used in the header is as follows:
<!-- DIV REFRESH START -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$('#datatable').fadeOut('slow').load('data/table.php').fadeIn("slow");
}, 10000);
</script>
<!-- DIV REFRESH END -->
As you can see, it is refreshing a specific div with a specific page. I'm very novice with jquery and java based coding in general as I'm sure will be evident in this question.
Is it possible to do the following:
The table is actually created in a php function due to the the fact that the number of rows changes all the time. Is it possible to have it refresh the function specifically rather than a page that is just calling the function?
The table currently refreshes completely. This is just to update one figure on each row. It would be much cleaner to have it only refresh each figure on the row but due to the flexible nature of the table and the fact that it is part of a function would this be possible? If so, how would it be possible? I know I could have each div on each row to have a unique div name which I could then take into account in the script section at the top of the page but would that not require having every possible div name added with the same code repeated?
Though I know it is possible to have the item refresh based on when something in the database changes rather than by a time delay but what would be the best way given the requirements listed above?
I could be way off and it's a simple answer to each question but I appreciate any and all input.
Thanks!
p.s. if it helps, the function I'm currently using to create the table is the following (I know it can be made to function much cleaner but it is a bit of a learning project):
function portalTable($venueId, $eventId)
{
echo "<table class='basic-table'><tr class='th'><th>Portal Name</th><th>Scanned</th></tr>";
$grandTotals = array();
$portalSql = mysql_query("SELECT * FROM portal WHERE id_venue = $venueId");
while ($portalRow = mysql_fetch_array($portalSql))
{
$portalId = $portalRow['id_portal'];
$portalName = $portalRow['name_portal'];
if($portalId&1) {$gray = "dg";} else {$gray = "lg";}
$sql = mysql_query("SELECT * FROM scan WHERE id_event = $eventId AND id_portal = $portalId");
while ($row = mysql_fetch_array($sql))
{
$scanTotal = $row['total_scan'];
echo "<tr class='$gray'><td>$portalName</td><td>$scanTotal</td></tr>";
$grandTotals[] = $scanTotal;
}
}
$totals = array_sum($grandTotals);
echo "<tr class='basic-table-total'><td>Total</td><td>$totals</td></tr>";
// total failed scans
$sql = mysql_query("SELECT total_errors FROM errors WHERE id_event = $eventId");
while ($row = mysql_fetch_array($sql))
{
$totalErrors = $row['total_errors'];
echo "<tr class='basic-table-total'><th>Total Rejected Scans</th><th>$totalErrors</th></tr>";
}
echo "</table>";
}
$('div.myDiv').each(function(i, obj) {
$(obj).load('myURL.php');
});
That what you're looking for?
As for the large amount of data being sent? Don't send raw HTML!
Instead, use parseJSON in jQuery and json_encode in your PHP script to send a (much) smaller amount of data to the user, which can then be used by the client to make the table.
Handling the decoded JSON data is relatively simple in JavaScript. Once it has been decoded, it is now an accessible object. You can use an iterator (jQuery does this well).
$.each(myJSON, function(i, val) {
$('body').append(val + "<br />");
});

Use php to populate javascript array

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

Categories