Display result of a Javascript function in a modal

Asked

Viewed 478 times

0

Good morning!

I have a function that scans a JSON file for information compatible with the search that will be performed. Work normally. But what I want is, to display the result of this search in a modal.

I can display normally in an Alert(), but I can’t in a modal, created by bootstrap.

Could you help me? (I don’t know if I was clear enough)

var estadoClicked = "";

function disparar() {
    var el = document.getElementById('local');
    el.addEventListener('click', function(e) {
        estadoClicked = e.target.id;
        executando();
    });
}

var locais = "";
var texto1 = "";
var texto2 = "";
var texto3 = "";
var texto4 = "";
var texto5 = "";
var texto6 = "";
var texto_final = "";
var dados_cidades = "";

function executando() {
    var obj, dbParam, xmlhttp, myObj, x, txt = "";

    obj = {
        "table": "customers",
        "limit": 20
    };
    dbParam = JSON.stringify(obj);
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            txt += "<table border='1'>"
            for (x in myObj) {
                if (myObj[x].estadoSigla == estadoClicked) {
                    if (myObj[x].existe == 'true') {
                        locais += "<strong>" + myObj[x].estado + "</strong>" + "<br/>" + myObj[x].cidade + "<br/>";
                    }
                }
            }
            txt += "</table>"

            //dados_cidades RECEBE O CONTEUDO REALIZADO APARTIR DA PESQUISA NO ARQUIVO JSON:
            var dados_cidades = document.getElementById("demo").innerHTML = locais;

            //GERANDO O TEXTO QUE SERÁ EXIBIDO POSTERIORMENTE:
            var texto1 = "<h2>Olá!</h2>";
            var texto2 = "<h4>Obrigado por consultar a Next.</h4>";
            var texto3 = "<h4>Atualmente, já existem unidades neste Estado.</h4>";
            var texto4 = "<h4>Mas fique <strong>tranquilo!</strong></h4>";
            var texto5 = "<h4>Na next, seu espaço está RESERVADO!</h4>";
            var texto6 = "<h4>Envie-nos seu email e entraremos em contato:</h4>";
            var texto_final = texto1 + texto2 + texto3 + "<h2>" + dados_cidades + "</h2><br/>" + texto4 + texto5 + texto6;

            //EXIBINDO O RESULTADO APARTIR DE UM ALERTA:
            //bootbox.alert(texto_final);
        }
    };
    xmlhttp.open("POST", "json_estados.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("x=" + dbParam);
}
  • Send the HTML as well

1 answer

1


I used that example modal.. But use whatever you think best, come on, first put an id inside the element you will insert in case I added the id "here". Explaining... innerHTML is used to add text and html inside an HTML element so I just took the id and added its mounted structure, more about innerHTML here, From an id to the modal and use the show function, It is worth remembering that jquery has to be imported and bootstrap too

https://www.w3schools.com/jsref/prop_html_innerhtml.asp

<div class="modal" id="mymodal" tabindex="-1" role="dialog"><!--Coloquei um ID-->
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div id="aqui" class="modal-body"><!-- AQUI O ID -->
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary">Save changes</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

In your js make an innerHTML

<script type="text/javascript">
  var locais = "";
  var texto1 = "";
  var texto2 = "";
  var texto3 = "";
  var texto4 = "";
  var texto5 = "";
  var texto6 = "";
  var texto_final = "";
  var dados_cidades = "";

  function executando(){
    var obj, dbParam, xmlhttp, myObj, x, txt = "";

    obj = { "table":"customers", "limit":20 };
    dbParam = JSON.stringify(obj);
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<table border='1'>"
        for (x in myObj) {
          if(myObj[x].estadoSigla==estadoClicked){  
            if(myObj[x].existe=='true'){
              locais +="<strong>" + myObj[x].estado + "</strong>" + "<br/>" + myObj[x].cidade + "<br/>";
            }
          } 
        }
        txt += "</table>"        

        //dados_cidades RECEBE O CONTEUDO REALIZADO APARTIR DA PESQUISA NO ARQUIVO JSON:
        var dados_cidades = document.getElementById("demo").innerHTML = locais;

        //GERANDO O TEXTO QUE SERÁ EXIBIDO POSTERIORMENTE:
        var texto1 = "<h2>Olá!</h2>";
        var texto2 = "<h4>Obrigado por consultar a Next.</h4>";
        var texto3 = "<h4>Atualmente, já existem unidades neste Estado.</h4>";
        var texto4 = "<h4>Mas fique <strong>tranquilo!</strong></h4>";
        var texto5 = "<h4>Na next, seu espaço está RESERVADO!</h4>";
        var texto6 = "<h4>Envie-nos seu email e entraremos em contato:</h4>";
        var texto_final = texto1 + texto2 + texto3 + "<h2>" + dados_cidades + "</h2><br/>" + texto4 + texto5 + texto6;

        //EXIBINDO O RESULTADO APARTIR DE UM ALERTA:
        //bootbox.alert(texto_final);

        //AQUI O innerHTML NO DETERMINADO ID
        document.getElementById('aqui').innerHTML = texto_final;
        $('#mymodal').modal('show');
      }
    };
    xmlhttp.open("POST", "json_estados.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("x=" + dbParam);
  }
</script>
  • I understood your idea perfectly. But unfortunately, it didn’t work. When I click on the element, the function is triggered, scans the JSON, does the calculations and then need to display this result in a modal. In the case of the code you explained to me (very well by the way), the modal does not open itself, even if it contains the correct id.

  • Okay I’ll edit a moment

  • Ready Edited @Lucasneves

  • It worked perfectly! Incredibly to be honest. Thank you very much! It only has one detail...the internal content of the modal, repeats...if I click the same element twice. Example, the modal displays: hello! If I click the element again, it appears: hello! hello! hello! Case?

  • My friend, it worked here. I played a window.Reload() in the close of the modal and I refresh the page with each element query. It seems a problem, but given the element I’m using, it fell perfectly. Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.