Home > OS >  How do I display an image after you've made your selection with a php Array?
How do I display an image after you've made your selection with a php Array?

Time:02-23

My question is, what would be the best way to go about this?

<?
if (in_array("1434", $category)) {
  if($item > 0) {
    $wc_product = wc_get_product($item);
    echo '<img src="' . get_the_post_thumbnail_url($item, 'medium') . '">'; 
  }
}
?>

[1]:

CodePudding user response:

The general method that you would use is

  • someone clicks on the product which calls a javascript function
  • your javascript makes an ajax call to your PHP script on the back end
  • your php script gets the data and echoes it back as a JSON encoded string
  • your javascript gets this new data, parses into JSON and makes the image appear

Using php, you build your initial html page. Lets say you have an image element to show the selected image, like:

<img id='mainImg' src='/placeholder-image.jpg' />

Use something like the product id as the argument for the function that is called from the button

<button onclick='getProductData(1234)'>View Product</button>

Your JS function would look something like this

function getProductData(id) {
   let url = '/myBackendPHPendpoint.php?pid='   id
   $.ajax({url: url,
        success: function(json){
          json = JSON.decode(json)
          $('#mainImg').attr('src', json.image)
        }
    })
}

Your PHP page myBackendPHPendpoint.php would look something like

<?php
  $id = $_GET['pid'];
  // database query to get the product data
  // get the result as an object or array in php  
  echo json_encode($result);
?>
  • Related