0

I'm trying to send multiple php variables to javascript function and I don't know how to achieve that. Any suggestions?

HTML code:

 <button class="btn btn-icon" type="button" data-toggle="modal" data-target="#modal-edit-category" data-toggle="tooltip" 
 onClick=(setSelectedCategoryId2({{$category->id}},{{ $category->name }})) >
    <span class="btn-inner--icon"><i class="fa fa-edit"></i></span>
 </button>

Javascript function:

function setSelectedCategoryId2(id,name){
   alert(id, name)
}
3
  • @mplungjan $category->id $category->name inside html code Commented Nov 10, 2020 at 17:44
  • What error does this currently produce? Commented Nov 10, 2020 at 17:45
  • @Msencenb Uncaught ReferenceError: Product is not defined at HTMLButtonElement.onclick Product is the category name that i'm sending as a parameter Commented Nov 10, 2020 at 17:46

2 Answers 2

1

You mean this? Data-attributes are recommended over inline event handlers

document.querySelector("[data-toggle=modal]").addEventListener("click",function() {
  console.log(this.dataset.cat,this.dataset.name)
})
<button class="btn btn-icon" type="button" data-toggle="modal" data-target="#modal-edit-category" data-toggle="tooltip" 
data-cat="<?= $category->id ?>" data-name="<?= $category->name ?>">
    <span class="btn-inner--icon"><i class="fa fa-edit"></i></span>
 </button>
Sign up to request clarification or add additional context in comments.

1 Comment

I think as a matter of best practice, we should see some encoding here.
0

Your HTML code needs to be placed in a PHP file, then

onClick=(setSelectedCategoryId2({{$category->id}},{{ $category->name }}))

becomes

onClick="setSelectedCategoryId2('<?php echo $category->id; ?>','<?php echo $category->name; ?>')"

Avoid using ' in your php vars and that's done :)

1 Comment

This will break if the php variable's text contains a single or double quote.

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.