简体   繁体   中英

pass php variable through name in javascript appended to html

In this one line of code in my js function, I am trying to pass the id from the databse table through the name attribute.

However it is breaking my javascript and not correctly passing.

$("#a"+$selected.val()).append('<input type="hidden" name="'<?php echo json_encode($data['id']); ?>'" value="'+$selected.text()+'">');

Full function to get a better view of issue:

$(function() {
$("#event").hide();
$("#events").hide();
$("#myselect select").change(function() {
var $selected = $('#myselect select option:selected');
if (!$selected.hasClass('added')) {
  $('<li />', {
    'data-value': $selected.val(),
    id:'a'+$selected.val(),
    text: $selected.text()
  }).appendTo('#events');
  $selected.addClass('added');
  $("#a"+$selected.val()).append('<input type="hidden" name="'<?php echo json_encode($data['id']); ?>'" value="'+$selected.text()+'">');
}

$("#event").show();
$("#events").show();


});
});

Updated:

console.log('<?php echo $data['id']; ?>');

outputs:

Resource interpreted as Image but transferred with MIME type text/html: "http://localhost:8809/locations". jquery.js:3492(anonymous function) jquery.js:3492fire jquery.js:3048self.fireWith jquery.js:3160jQuery.extend.ready jquery.js:433completed

I think, you dont want to json_encode it as the variable $data['id'] will not be an array and just a string or number. Also you are using both single and double quotes to wrap the value where just one will do the task. So do

name="<?php echo $data['id']; ?>"

instead of

name="'<?php echo json_encode($data['id']); ?>'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM