Albertus Brand Venter Albertus Brand Venter - 3 months ago 11
jQuery Question

Giving an element multiple names/id's

I have come across a few posts emphasizing that an ID is only used once.

However I need to pass 2 php variables to my javascript. I intended to use the

document.getElementById
but since I can only have one ID, this will not work.

Are there any other ways to achieve this?

My code:

<a data-toggle="modal" data-id="prodModal" presID="<?php echo $selectPresForJs->valueof('pres_id'); ?>" prodID="<?php echo $prod->prod_id; ?>" data-target="#prodModal" class="image_modal" >
<img class="image-modal" style="width: 192px; height:192px;" src="<?php echo $prod->prod_icon; ?>">
<span ><h2 style='color:#2468A6'><b><?php echo $prod->prod_name ?></b></h2></span>
</a>


The two variables I need to pass are the
presID
and the
prodID
variables. found in the
<a>
element.

EDIT

After a suggestion I have rewrote my code as follows:

<a data-toggle="modal" data-id="prodModal" data-presId="<?php echo $selectPresForJs->valueof('pres_id'); ?>" data-prodId="<?php echo $prod->prod_id; ?>" data-target="#prodModal" class="image_modal" >
<img class="image-modal" style="width: 192px; height:192px;" src="<?php echo $prod->prod_icon; ?>">
<span ><h2 style='color:#2468A6'><b><?php echo $prod->prod_name ?></b></h2></span>
</a>


The javascript I am using looks as follows:

$(document).ready(function(){

$('#prodModal').click(function() {


var ajaxprodId = $('#prodModal').data('prodId');
var ajaxpresId = $('#prodModal').data('presId');
/*Console Prints the variables as undefined*/
console.log(ajaxprodId);
console.log(ajaxpresId);

$.ajax({

url: "path/to/file/Presentation.php",
type: "POST",
data: {prodId : ajaxprodId,presId:ajaxpresId}


,success: function(data){
console.log("Success was achieved");
document.getElementById("modal_content").innerHTML = "Works";
},
error: function(data){
console.error("The action was unsuccessfull");
alert(data);

}


});
});


});

Answer

You can use custom html attributes like data-presID and data-prodID

data-presID="<?php echo $selectPresForJs->valueof('pres_id'); ?>"

You can access these variables in javascript by targetting the a element.

var ele = document.getElementById("yourelementID");
var pressID = ele.attributes["data-presID"].value;