How do I print jquery results in a div?

Asked

Viewed 526 times

2

My codigo js is working perfectly however I wanted to printase the result inside a div in the index.html itself below my textarea and without redirecting to another page, because it is redirecting to the page ip.php and showing the results there.

<html>

<head>
<title> testar ips </title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  function enviar(){
    var bin = $("#bin_id").val();
    var linhaenviar = bin.split("\n");
    var index = 0;
    linhaenviar.forEach(function(value){

      setTimeout(

        function(){
          $.ajax({
            url: 'ip.php',
            type: 'POST',
            dataType: 'html',
            data: "bin=" + value,
            success: function(resultado){
              document.write(resultado + "<br>");
          }
        })

      }, 10 * index);

    index = index + 3;

    })
  }
  </script>

</head>

<body>

<center>
<textarea name="ip" id="ip_id" rows="10" cols="40">
</textarea>
<br>
<input type="button" value="testar ips" onclick="enviar();"></input>
</center>
</body>
</html>

2 answers

2

You can use jQuery’s HTML command on success of your AJAX request:

$('#id_da_minha_div').html(meu_html)

See more information here: http://api.jquery.com/html/

  • Who gave the -1, could explain, please, the reason here in the comment at least?

2


Simple, first create a span or div under your textarea with some id.

<span id="msg"> </span>

Within the function success you can use the function text() selecting the span:

success: function(){
   $("#msg").text("a mensagem que você quer");
}

A small example for ajax and php requests.

JS

  $("#cadastrar-produtos").on("submit", function(e){
    e.preventDefault();

    var dados = $(this).serialize();
    var url = "cadastrar-produto.php";

    $.ajax({
      url: url,
      type: "POST",
      data: dados,
      dataType: "json",
      success: function(json){
        if (json.status) {
          console.log("success");
          $("#cadastrar").each(function() {
            this.reset();
          });

          iziToast.success({
            title: 'Ok',
            message: json.message,
            icon: "zmdi zmdi-thumb-up"
          });

        } else {
          console.log("error");
          iziToast.error({
            title: 'Erro',
            message: json.message,
            icon: "zmdi zmdi-thumb-down"
          });

        }
      },
      error: function(json){
        iziToast.error({
          title: 'Erro',
          message: "Erro ao fazer requisição",
          icon: "zmdi zmdi-thumb-down"
        });
      }
    });

  });

I am using a lib called iziToast to display output alerts.

Php

require_once 'class/Produto.php';
require_once 'class/ProdutoDAO.php';
require_once 'conecta.php';

$nome = $_POST["nome"];
$preco = $_POST["preco"];
$quantidade = $_POST["quantidade"];
$validade = $_POST["validade"];
$descricao = $_POST["descricao"];

$produto = new Produto();
$dao = new ProdutoDAO($conexao);
$produto->setNome($nome);
$produto->setPreco($preco);
$produto->setQuantidade($quantidade);
$produto->setValidade($validade);
$produto->setDescricao($descricao);
try {
    if ($dao->inserir($produto)) {
        $json = array(
            "status" => "true",
            "message" => "Produto inserido com sucesso"
        );
    } else {
        $json = array(
            "status" => "false",
            "message" => "Erro ao inserir produto"
        );
    }
} catch (PDOException $e) {
    $json = array(
            "status" => "false",
            "message" => "Erro ao inserir produto: " . $e->getMessage()
        );
}

echo json_encode($json);

I found it very interesting to create an array, as if it were a json object, to save the status and a message. The status will save if everything happened correctly in my back end, and a message like " Successfully registered product ". In my Function Success I make a if(json.status) if true, it’s because it all worked out, and I send a custom iziToast for success messages, otherwise I send a custom iziToast for error messages.

  • Thanks more the messages to be printed are results of ip.php where there are requests in Curl and return echo, what I really wanted to do and take from php echo $result; and print in the index div as this is done ?

  • put the result variable (which is in the Function Success parameter) inside Function text(): text(result);

  • edited the answer by putting a small example of how to print results coming from the back end, in your case php

  • thanks helped me a lot :)

Browser other questions tagged

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