ijason03
ijason03

Reputation: 581

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?

Upvotes: 1

Views: 897

Answers (2)

Kapil Yadav
Kapil Yadav

Reputation: 706

I would suggest the best way of passing variables to javascript from button click or any other event.

Add the passing argument as data-attributes in button.

Example:

<button id="b1" type="button" data-id="123" data-name="xyz" data-size="m" onClick="doSomething()">

And in php script or in ajax request you can get the attributes like:

var id   =  $("#b1").attr("data-id");
var name =  $("#b1").attr("data-name");

And use those in ajax call for php script.

Hope this is what you were looking for.

Upvotes: 0

u_mulder
u_mulder

Reputation: 54841

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']))?>)

Upvotes: 1

Related Questions