Mike Spider
Mike Spider

Reputation: 227

PHP array being passed to javascript function not doing anything

I have a php array that is being passed to a js function using "json_encode($array)", the problem is that when I click the button to trigger the function, nothing happens besides the page refreshing.

I think the problem might be the enclosing quotes, though I already tried changing from double to single and vice verse, no joy.

HTML:

 <button class="button1" 
  onclick="validateEncomenda('<?php echo json_encode($chosen_restaurant_addr);?>');
           return false;">Encomendar</button>

js:

function validateEncomenda(myarray){
   alert('Hello JS');
  }

if I echo the "json_encode($chosen_restaurant_addr)" I'm getting the right values in this format:

["ipsum lorem blah blah","Curabitur aliquam feugiat tellus"]

Any help or hint will be greatly appreciated.

Upvotes: 0

Views: 68

Answers (3)

Mike Brant
Mike Brant

Reputation: 71384

A better way to handle this would be to separate the onclick handling out from the HTML source. You could create a script like this:

var chosenResturant = <?php echo json_encode($chosen_restaurant_addr);?>;
document.getElementById('button1').onclick = function() {
    // no need to parse JSON here as we created an array literal above
    alert(chosenRestaurant.length);
    return false;
};

Note here that I am assuming that you add an id button1 to the element as the means for determining which elements gets the event handler. If you truly want to attach this behavior to all elements with the class name of button1, you would simply substitute getElementsByClassName('button1') instead of getElementById('button1')

Upvotes: 2

blue112
blue112

Reputation: 56432

You should escape the quotes in the PHP output. Since HTML quote can't be escaped, rewrite it like this :

onclick='validateEncomenda("<?php echo addslashes(json_encode($chosen_restaurant_addr)); ?>"); return false;'>

Upvotes: 1

jewelnguyen8
jewelnguyen8

Reputation: 249

I think that you should add new attribute for the button: type="button"

Upvotes: 0

Related Questions