Retrieve variable data jQuery

0

I have the following button:

<button type="button" class="btn btn-default" data-toggle="modal" data-target="#abrir-imagem" data-pasta="interno_fotos" data-imagem="139379939.jpg">Abrir Imagem</button>

I need to recover it through Ajax. And I did this:

    $('#abrir-imagem').on('show.bs.modal', function(e) {
        var pasta = $(this).data("pasta") 
        var imagem = $(this).data('imagem');
        $("#imagem").html("<img src='"+BASE_URL+"assets/uploads/"+pasta+"/"+imagem+"'>");
    });

It opens the modal correctly but the image does not appear. He says that the two variables are undefined. What is the correct way to look for them?

    
asked by anonymous 23.10.2017 / 17:26

2 answers

1

It is not working because your call is 'meaningless', you are informing $(this) to get a attr of another element.

In this section:

$('#abrir-imagem').on('show.bs.modal', function(e) {

You're saying "when the open-image id modal starts firing," that is, you will not find data-attrs buton with $(this) when button is $(this) .

Simply add a% identifier to classname , and search for button through it, as in the following example:

$('#abrir-imagem').on('show.bs.modal', function(e) {
        var pasta = $('.open-modal-btn').data("pasta") 
        var imagem = $('.open-modal-btn').data('imagem');
        //$("#imagem").html("<img src='"+BASE_URL+"assets/uploads/"+pasta+"/"+imagem+"'>");
        console.log('Pasta:' + pasta + '| Imagem: ' +imagem )
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="open-modal-btn btn btn-default" data-toggle="modal" data-target="#abrir-imagem" data-pasta="interno_fotos" data-imagem="139379939.jpg">Abrir Imagem</button>

<!-- Modal -->
<div id="abrir-imagem" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>
    
23.10.2017 / 17:56
1

Change the JavaScript code for this:

$('#abrir-imagem').on('show.bs.modal', function() {
  var pasta = $(this).attr('data-pasta');
  var imagem = $(this)attr('data-imagem');

  $("#imagem").html("<img src='"+BASE_URL+"assets/uploads/"+pasta+"/"+imagem+"'>");
});
    
23.10.2017 / 17:30