Search code examples
javascriptphpquotes

Pass PHP string variables to Javascript function via button click


I'm creating multiple buttons dynamically and I need to pass some PHP variables to a JavaScript function via the onclick method.

The code below works fine for the most part but if the variables contain double or single quotes, it fails to call the function.

I tried using htmlspecialcharacters with ENT_QUOTES which fixed the issue with the double quotes but the single quotes is still causing it to fail.

<button id="modalBtn" type="button" onclick="ShowProduct('<?php echo $title ?>', '<?php echo $description ?>', '<?php echo $img ?>');">View Details</button>

Any suggestions on how to fix this or is there a better way to do this?


Solution

  • I suggest you to create json object from your vars and pass it as argument, something like:

    <button 
        id="modalBtn" 
        type="button" 
        onclick="ShowProduct(<?php echo json_encode(array($title, $description, $img))?>);">
            View Details
    </button>
    

    Or (for more readable keys)

    <button 
        id="modalBtn" 
        type="button" 
        onclick="ShowProduct(<?php echo json_encode(array('title' => $title, 'descr' => $description, 'img' => $img))?>);">
            View Details
    </button>
    

    And your ShowProduct function you can define like:

    function ShowProduct(params) {
        console.log( params );
    
        // do other stuff
    }
    

    Update:

    if your vars are already in array you can:

    // pass this array:
    ShowProduct(<?php echo json_encode($your_array)?>)
    
    // fill new array with required keys only
    ShowProduct(<?php echo json_encode(array($your_array['title'], $your_array['description'], $your_array['img']))?>)