Php while loop with js variables - php

The plan:
Basically I have a set of clothing items stored in a table each containing "item_name" "item_id" and "item_shortcode" I want to have a link per clothing item, when the user clicks the link the item needs to be added to an array (the selected array)
I'm trying to create a javascript object based off the data I've gathered from the mySQL database, then pass that data to a function when a div is clicked to my method.
this is an example:
<?php
while($row = mysql_fetch_array($results)){
?>
<script>
var item = new Object();
item.itemName = <?php echo json_encode($row['item_name']); ?>;
</script>
<?php
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(item);\">";
//echo $row['item_name'];
echo "</div>";
}
}
?>
EDIT: this is just an example I'll be populating my object with lots of data, not just item_name
problem is the last object seems to be assigned to every div in while loop.
Anyone point out where I am going wrong?

Well, i honestly don't know if i really got you, but if i see it right, then you simply overwrite the item-object in every run of the while-loop.
After the last loop (after this comes the output) the variable "item" is set to the last result of the loop, so clicking on any div will return "item" - the last item of the loop.
As a solution, try to save the rows name in the div as a parameter, like
echo "<div id=\"".$row['item_name']."\" class=\"choice\" onclick=\"SetSelectedChoice(\'".$row['item_name']."\');\">";

You're redefining item on every iteration. Why not do something like this:
As per edit, you can create an item array and populate it in the loop:
<script type="text/javascript">
var objects = new Array();
</script>
<?php while($row = mysql_fetch_array($results)): ?>
<script type="text/javascript">
var item = new Object();
item.itemName = '<?php echo json_encode($row['item_name']); ?>';
objects.push(item);
</script>
<div id="<?php echo $row['item_id']; ?>" class="choice">
<?php echo $row['item_name']; ?>
</div>
<?php endwhile; ?>
then in js OUTSIDE of your loop:
$('.choice').on('click', function(){
SetSelectedChoice($(this).html());
});
function SetSelectedChoice(name)
{
for(var i = 0; i < objects.length; i ++)
{
if(objects[i].itemName == name)
{
//do something
}
}
}
NOTE: I wouldn't really recommend this kind of weird loop for comparing names. I just don't know what else you are doing with passing the name to this function. I would pass the item id or the index value and directly access an item in the array instead of a loop. Make sense?
Basically, stop using onclick. The whole world is leaning more on listeners. Secondly, no need to create an object at all. You don't seem to be using it and even if you did, you didn't put single quotes around the name like you should for strings. Thirdly, please break out of php to write html. It's just cleaner and easier. Morely, assign the item's id to the id parameter. It gets really ugly to have names and spaces in the ids of elements. And you don't really seem to need one since you don't use it in your example. None the less, I put it in there in case you wanted to access it like $(this).attr('id') in the on click listener.
But if I missed the point, perhaps you can clarify and I may update to better fit your needs

Related

Iterate through php array in jquery

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.

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));
});

Dynamically Generate divs with different ids with PHP

I want to generate a certain number of divs using PHP with different ids, I know how to generate them for a set number, but how do I generate on click, with different ids? Also, if
I wanted to delete a div (and its corresponding id) how would I do that?
This is the code I have for generating (6) divs
$element = "<div></div>";
$count = 6;
foreach( range(1,$count) as $item){
echo $element;
}
I need something like the click() in jquery/javscript (but in PHP) to trigger div creation instead and I don't even know where to start.
In JavaScript you can do
function createDiv(id, parent)
{
var elem = document.createElement('div');
elem.id = id;
document.getElementById(parent).appendChild(elem);
}
createDiv(10, id-of-parent-elem-to-append-to);
where 10 will be the ID of the new element and you will have to supply the ID of the element to which the new DIV should be appended, as the 2nd argument
echo "<div id='$item'></div>";
instead?
Ok, to create them with different ids you can do something like this:
$element = "<div id=";
$count = 6;
foreach($id=0;$id<$count;$id++) {
echo $element."div".$id."></div>";
}
In the same way as you appended the id you can append an onClick event that says something like this:
onclick="this.style='visibility:hidden;'";
or something along those lines.
Hope this helps.

How to get value of dynamic id in an html loop with javascript?

I am creating a drag and drop system using redips javascript.
This is my script using html and php to generate the data
<div id="base">
<table>
<tbody>
<?php
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus" value="'.$row['description'].'"></div></td></tr>';
}
?>
</tbody>
</table>
</div>
This is the fragment of my javascript file.
var redips_init;
redips_init = function () {
// reference to the REDIPS.drag
var rd = REDIPS.drag;
// initialization
rd.init();
rd.drop_option = 'shift';
rd.animation_shift = true;
rd.myhandler_dropped = function () {
alert($('#bus').val());
}
};
I am not good with php but what i usually do in jsp is create a local index variable and append it to each of the ID attribute in the loop.
So your code would look something like this
<?php
$index=0;
foreach($deviceID as $row)
{
echo '<tr><td><div class="drag">'.$row['description'].'<input type="hidden" id="bus'.$index++.'" value="'.$row['description'].'"></div></td></tr>';
}
?>
In javascript, your dragAndDrop event should return an index location by which u can get appropriate value.
Now you can use this dynamic ID in your JavaScript to do whatever you want to do.
REDIPS.drag contains save_content() method to scan all DIV elements in a table and to return the result as Query string or JSON object. Input parameters are table id and type of returned result (default is query string). If this is not good enough, you can search for save_content() source and make customization. Method is simple and it uses several loops to scan table content.
On the other hand, if you need to know ID of dropped DIV element that can be written inside myhandler_dropped event hander. Here is code snippet:
rd.myhandler_dropped = function () {
// define DIV id
var id = rd.obj.id;
// write DIV id to the console
console.log(id)
};
Hope this answer will be helpful.

An error with in the execution of an ajax

I have been a really big fan of stackoverflow(which led me to ask the question here and not anywhere else), anyway, without further ado...
While creating a shop system, I planned to implement an ajax which buys the item on the fly. Now This is how the loop for retrieving items looks like:
<?php
$shop_query = mysql_query("SELECT * FROM sector0_item WHERE 1");
$numrows = mysql_num_rows($shop_query);
While ($shop_fetch = mysql_fetch_array($shop_query)){
?>
<div id="shop_main">
<div class = 'item_img'>
<a><img src = "http://images.wikia.com/dofus/images/4/4e/Discovery_Potion.png" height = '100px'/></a>
</div>
<div class="item_buy">
<a><center>Price: <?php echo number_format($shop_fetch['item_price']);?></center><br /></a>
<a>Quantity: <input type = 'text' size = '9' id = 'itemquantity'/><br /></a>
<a><p>Point requirement: <?php echo number_format($shop_fetch['item_pt_req']);?></p></a>
<a><input type = 'button' id = 'buy' value = 'buy'/></a><span id = 'buy_status'></span>
</div>
<a><h3><?php echo $shop_fetch['item_name'];?></h3></a>
<a><p><?php echo $shop_fetch['item_desc'];?></p></a>
<a>Item Type: <font color = 'green'><?php echo $shop_fetch['item_class'];?></font></a>
</div>
<br />
<?php
}
?>
However, my ajax seems to act really weird. My implementation was to show a loading gif image.
Script:
<script type = 'text/javascript'>
$('#buy').click (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
</script>
The problem is, Only one button shows the circle when clicked. Does the position of the script cause this? Any help is appreciated.
You can only have one item with a given id. When you have multiple elements with the same id, it is indeterminate which one will be returned, but it will usually be the first item only.
If you want multiple buy buttons and want to assign them all the same jQuery event handler, then use a common class name instead of an id.
If you are loading content dynamically and you want event handlers to work for that content, then you need to use delegated event handling.
In jQuery, that is generally done with either .on() or .delegate(). The basic idea is that you pick a static parent object that is not dynamically loaded (perhaps the parent of show_main) and bind the event to that object and then pass the selector of the dynamic element like this (note, I've changed from an id to a class to identify the buy button):
$(staticParentSelector).on('click', '.buyButton', function() {
$(this).closest(".item_buy").find(".buy_status").html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
})
Two things:
It's hard to tell from the sample, but is there an iterator that creates a list of available items? If so, you shouldn't be using IDs which are meant to be unique. If there's really only one #buy then you're fine, though.
When content is updated with Ajax, you're going to lose bindings. Assuming the item related to the #buy button gets replaced with other items, you're better off with a delegated event:
// not in an inline script, but just once, ideally in your main JS file
$(document).ready(function() {
$('#wrapper').on('click', '#buy', (function(){
var quantity = $('#itemquantity').val();
$('#buy_status').html('<img src = "http://www.antibodyresource.com/theme/js/ajax-loader.gif" height = 20px;/>');
});
})
Where #wrapper is some ancestor higher up in the DOM tree that is never destroyed by the Ajax event.
id is unique value - on html page each id must have unique value. Use class instead.
You need to put your code inside $(document).ready(). So its:
$(document).ready( function() {
$('#buy').click( function(){
// do something here
});
});
Also, you may want to list to jfriend00's advice on IDs.

Categories