1 | initial version |
There are several ways to accomplish this task, but one possible method is:
<form>
<label for="select-image">Select an image:</label>
<select id="select-image" name="image">
<option value="">-- Choose an option --</option>
<option value="1">Image 1</option>
<option value="2">Image 2</option>
<option value="3">Image 3</option>
</select>
<img id="display-image" src="" alt="Selected image">
</form>
$(document).ready(function() {
$('#select-image').change(function() {
var selectedImage = $(this).val();
if (selectedImage != '') {
$.ajax({
url: 'get_image_path.php',
type: 'POST',
data: { image: selectedImage },
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('#display-image').attr('src', response.path);
} else {
alert('Error: ' + response.message);
}
},
error: function(xhr, status, error) {
alert('AJAX Error: ' + error);
}
});
} else {
$('#display-image').attr('src', '');
}
});
});
<?php
if (isset($_POST['image'])) {
$imageId = intval($_POST['image']);
$imagePaths = array(
1 => 'images/image1.jpg',
2 => 'images/image2.jpg',
3 => 'images/image3.jpg',
);
if (array_key_exists($imageId, $imagePaths)) {
$response = array(
'status' => 'success',
'path' => $imagePaths[$imageId],
);
} else {
$response = array(
'status' => 'error',
'message' => 'Invalid image ID',
);
}
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
?>
Note that this is a simplified example and doesn't include error handling, security measures, or other features that may be necessary in a real-world application.