1

I am wanting to run a jquery.append function on some divs. Basically, I am calling information to the database, and the database knows which DIV id the content belongs to, so I want the DIV id in the .append function to be different for each value.

I guess I want to know how I can run a loop on the Jquery portion. Everything else I am doing is working great!

4
  • 2
    Could you clarify your question with an example? Commented Oct 11, 2011 at 20:23
  • 1
    It may be easier do do the loop in PHP and output a JQuery.append line for each record. Commented Oct 11, 2011 at 20:23
  • 2
    check out jQuery.each(), probably all you need... and hey, what's wrong with an oldskool for loop? Commented Oct 11, 2011 at 20:24
  • haha, nothing wrong with the oldskool, but everything is cool with new school lol. And I was thinking an .each would work, but I'm still learning how to use Jquery, and wasn't sure how to work it with PHP Commented Oct 12, 2011 at 1:23

1 Answer 1

2

Lets say your each id is stored into an array in PHP, i.e.

<?php
$all_ids = Array(
  '1' => 'ID 1 value',
  '2' => 'ID 2 value',
  '3' => 'ID 3 value'
);
?>

You can use json_encode to translate the array to a javascript object.

<script>
var iterateMe = <?=json_encode($all_ids)?>;
$.each(iterateMe,function(index, value) {
  // This is where you would run each append
  alert(index + ": " + value);
});
</script>

Then, iterate as normal!

Sign up to request clarification or add additional context in comments.

4 Comments

this looks good, now I just need to learn arrays in PHP. lol. I am learning and that's all that matters. Appreciate the help!
I am very confused, I am wanting to do a PHP loops through an unknown amount of values from the database. I can use an array, but idk how to loop it for the jquery. Basically I want the #divid on the .append function to change with each pass of the loop.
Well let's break this down. Hopefully you're (1) Using $myArray = mysql_fetch_array() to get an array from the database. You should use <pre><?=var_dump($myArray)?></pre> to understand how that array works. Then (2) You should be converting that to JavaScript Object Notation via PHP's json_encode($myArray) method as seen above. If you've never worked with JSON before, don't fret. Check out this 3 minute tutorial: secretgeek.net/json_3mins.asp and compare it with your PHP array. Lastly, (3) to help better grasp the "changing #divid", try console.log(whatever var you stored json in).
If that doesn't help at all, you'll need to send code, because all the concepts you've talked about have been spread thin by now. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.