I’m trying to dynamically generate JavaScript functions in PHP and execute them via AJAX on my web page. Here’s a simplified version of what I’m attempting:
In fetch_data.php:
<?php
$i = 1;
$ajax = '<script>';
foreach ($res2MultipleImages as $images) {
$imageId = h($images->id);
$ajax .= 'function add_to_cart_' . $i . '(' . $images->id . ') {
var product_id = ' . $imageId . ';
alert(product_id);
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: {
product_id: id,
quantity: 1
},
success: function(response) {
alert("ok");
},
error: function(xhr, status, error) {
alert("error.");
}
});
} ';
$i++;
}
$ajax .= '</script>';
echo json_encode([
'ajax' => $ajax,
]);
?>
index.php
success: function (result) {
const data = jQuery.parseJSON(result);
$('.filter_data').html(data.output);
$('#output_ajax').html(data.ajax);
}
<div id="output_ajax"></div>
output ajax '<script>function add_to_cart_1(36) {rn rn var product_id = 36;rn alert(product_id);rn rn $.ajax({rn type: "POST",rn url: "add_to_cart.php",rn data: {rn product_id: id, rn quantity: 1rn },rn success: function(response) {rn alert("ok");rn },rn error: function(xhr, status, error) {rn alert("error.");rn … var product_id = 61;rn alert(product_id);rn rn $.ajax({rn type: "POST",rn url: "add_to_cart.php",rn data: {rn product_id: id, rn quantity: 1rn },rn success: function(response) {rn alert("ok");rn },rn error: function(xhr, status, error) {rn alert("error.");rn }rn });rn rn } </script>'
Ten setup generuje dynamicznie funkcje JavaScript w fetch_data.php i próbuje je załadować i uruchomić za pomocą AJAX w index.php. Jednakże funkcje te nie wydają się działać poprawnie. Co mogę przeoczać w tej implementacji?