I am trying to show an image using JavaScript after a user fills out an input field. I have gotten it to show the URL when using a input type="text" but when I try change it to an img tag it returns [object Object]. Is this possible to do?
input.php
<div class='col1;'> <img style='width:20%' src="" alt="" id="img" ></div>
<script type="text/javascript">
$(document).ready(function() {
function myrequest2(e) {
var mn = $('.auto2').val();
var pn = $('.auto').val();
$.ajax({
method: "GET",
url: "autofill2.php",
dataType: 'json',
data: {
inputmn: mn,
inputpn: pn
},
success: function( responseObject ) {
var x = $('#img').val( responseObject.image);
document.getElementById("img").src = x;
document.getElementById("img").alt = x;
},
failure: function() {
alert('fail');
}
});
}
$('#mn').change(function(e) {
e.preventDefault();
myrequest2();
});
});
</script>
autofill2.php
<?php
$conn = mysqli_connect($host, $username, $password, $db);
$inputmn = $_GET['inputmn'];
$inputpn = $_GET['inputpn'];
$return = mysqli_query($conn, "SELECT image FROM parts WHERE ModelNum = '$inputmn' and PartNum = '$inputpn' LIMIT 1");
$rows = mysqli_fetch_array($return);
$formattedData = json_encode($rows);
print $formattedData;
?>
Also, I know that I need prepared statements. Just getting this to work first
You're incorrectly calling upon the responseObject
parameter for your use case. The x
variable is a jQuery
selector. This selector does not contain image data. Since you set the image src
to the selector (which is invalid), it fell back to the alt
text. Since you also had your alt
text set to the jQuery
selector, the toString()
function for it was run, and thus you saw [Object object]
, as a jQuery
selector doesn't have an overridden toString()
. To solve this: Change x
to responseObject.image
and change alt
to a description of the image.
success: function( responseObject ) {
var x = responseObject.image // assuming .image is img data
document.getElementById("img").src = x;
document.getElementById("img").alt = "Nice image";
},
One small note, you're mixing-and-matching with jQuery
. If you want to continously use jQuery
you can change document.getElementById("img") = x
to $("#img").attr("src", x);