Search code examples
javascriptjqueryimagesrc

Issue changing image src with javascript


I am trying to change an Image SRC based on a variable in javascript.

I have the following modal:

<div class="modal-body">
    <img src="https://www.w3schools.com/js/landscape.jpg" alt="image" width="400" name="image_modal" id="image_modal">
    <div class="form-group">
        <label>Image Name</label>
        <input type="text" name="image_name" id="image_name" class="form-control" />
    </div>
    <div class="form-group">
        <label>Image Description</label>
        <input type="text" name="image_description" id="image_description" class="form-control" />
    </div>
    <div class="form-group">
        <label>Path</label>
        <input type="text" name="path" id="path" class="form-control" />
    </div>  
</div>
<div class="modal-footer">
    <input type="hidden" name="image_id" id="image_id" value="" />
    <input type="submit" name="submit" class="btn btn-info" value="Edit" />
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>

I then try to change the initial dummy SRC in JS:

...
$.ajax({
   url:"edit.php",
   method:"post",
   data:{image_id:image_id},
   dataType:"json",
   success:function(data)
   {
    $('#imageModal').modal('show');
    $('#image_id').val(image_id);
    $('#image_name').val(data.image_name);
    $('#path').val(data.path);
    $('#image_description').val(data.image_description);
    document.getElementById("image_modal").src = val(data.path);
   }
});

I am checking if the src URL is correct by showing it in the modal (data.path) and it is correctly outputted.

But when trying to change src with document.getElementById("image_modal").src = val(data.path);no image is shown, like if the variable was not correctly interpreted.


Solution

  • Your problem is here: val(data.path);

    Unless you've defined it, val() is undefined. You should be able to just use data.path, assuming it's the string you're after.

    Use this instead

    document.getElementById("image_modal").src = data.path;