0

I'm fairly new to jQuery and OOP in PHP, but what I have is a PHP Object that has an array

$array[0] = "a"
$array[1] = "b"
$array[2] = "c"
$array[3] = "d"

and a select box in my HTML

<select class="box">
<option value="1">First Letter</option>
<option value="2">Second Letter</option>
<option value="3">Third Letter</option>
<option value="4">Fourth Letter</option>
</select>

<div></div>

How do I dynamically change whatever is in the div tags as someone changes the value of the select box using jQuery?

Is there a way to do something like

$('.box').change(){ var value = $object->array[index-1]}?

Assuming I had already have the value for index.

EDIT I know I'll have to use Ajax, but I'm not sure how to call a method in an instance of an object already made.

1
  • javascript and php run in two different contexts, client and server... Commented Oct 3, 2011 at 1:12

3 Answers 3

1

You can't access PHP through javascript. There are several possible solutions:

  1. Load all of the possible data combinations at once onto the page stored somewhere in the DOM. As the user cycles through the options, change them appropriately.
  2. Load only the initial elements onto the page without javascript, then use Ajax to load all other possible combinations.
  3. Load each combination with ajax on the fly.

You can either have javascript make an Ajax request to the same page and filter the request, or you can create a proxy that will serve only the requests you need when hit with ajax.

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

Comments

1

Remember that you are trying to combine PHP with Javascript.

Your code will primarily be written in javascript, but you'll only inject bits of PHP code into the javascript code.

As in this instance, use the standard jquery onchange event method 'change()' for the selectbox, set the javascript variable value to $object->array[0] from PHP.

$('select').change(function() {
  var value = <?php echo $object->array[$index] ?>
  $('div').html(value)
});

Comments

0

You can use the php function json_encode to turn your php data into a javascript object. e.g

<script type="text/javascript">
    var mydata = <?= json_encode($myarray) ?>;
    console.log(mydata); 
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.