Receive and read array coming by Ajax

Asked

Viewed 1,890 times

-1

I have a requisition ajax thus

$.ajax({
    type: "POST",
    data: "valor="+val,
    url: "ajax/mostra_imagens.php",
    success: function(e){
        console.log(e);
    }
});

On the page mostra_imagens.php he creates a array which in turn is received in the variable e but how do I do for the variable e be a array and not a string?

mostra_imagens.php

<?php
require "../../ligacao.php";
$array = array();
$query=mysqli_query($db, "SELECT * FROM publicidades_sponsors where id_publicidade = '".$_POST['valor']."'");
while($mostra=mysqli_fetch_assoc($query)){
    $array[] = $mostra['nome'];
}
print_r($array);
?>

What the console.log(e) return

Array
(
    [0] => DIDAXIS1.png
    [1] => DIDAXIS2.png
    [2] => DIDAXIS3.png
    [3] => DIDAXIS4.png
)

It returns different data depending on what is selected in select

  • what comes out in console.log(e)? Press F12 and see in the console tab

  • can ask the question an example of is returned?

  • Puts your string being returned to the question.

  • @Ricardopunctual Edited the Question

  • @Mayconf.Castro I edited the question

  • @Marconi I edited the question

Show 1 more comment

5 answers

1

You have some options.

You can use the option dataType jQuery, so it tries to guess the server response type depending on the MIME sent in it, if you do not control it or prefer not to change, you can put this value as json to and jQuery will turn the answer into a javascript object (if possible).

$.ajax({
    // ... outras opcoes
    dataType: 'json'
});

You can do it too, no success conversion, without having to use the dataType above.

$.ajax({
    success: function(e) {
        console.log(JSON.parse(e));
    }
});

EDIT

With the new details placed in the question, the above is not valid. But it remains a viable option when the API returns correct JSON, but jQuery does not interpret it as such.

  • If you execute the JSON.parse array (in the example given in the question) of the error

  • I just saw the update the question. I didn’t have the output of the ajax call yesterday, and I thought it was valid json. Being as it is, yes, JSON.parse will not work.

0


Well, I kind of got what I wanted to do.

while($mostra=mysqli_fetch_assoc($query)){
    $array[] = $mostra['nome'];
}
foreach($array as $value){
    echo $value.",";
}

With this code it creates a string separated by commas that I can use next.

success: function(e){
    var slice = e.slice(0,-1);
    expl = slice.split(",");
        for(t=0;t<=balance;t++){
            if(n_pub-1<=t){
                r=0;
            }
            console.log("???"+expl[r]);
            $(".images"+p+" .images_pub").html("<img src='pubs/"+valor+"/"+expl[r]+"' style='width:100%' /><div class='altera' style='margin-top:-20px;top:0;left:2px;position:absolute;color:white;'><small><small><small><b>"+pub+"</b></small></small></small></div>");
            p++;
            r++;
        }
}

With this I get what I needed. Using the slice(0, -1) withdraw the last comma to not give conflict and create another position in the array created with the split(",").

0

In show_images.php, you can do so instead of print_r() of your example,

<?php
    require "../../ligacao.php";

    $array = array();
    $query = mysqli_query($db, "SELECT * FROM publicidades_sponsors where id_publicidade = '{$_POST['valor']}'");
    while ($mostra = mysqli_fetch_assoc($query)) {
        $array[] = $mostra['nome'];
    }

    // Troca o print_r() pela linha de baixo.
    echo json_encode($array);
?>

0

I don’t know exactly how your array is coming, but for you to scan an array you can use the jQuery.each()

var array = [3, 2, 3, 4];
$.each(array, function(index, val) { 
  console.log("Indice: " + index + " Valor: " + val)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

I was very much in doubt of how to return an array of a php using Jquery, I searched several ways and it was always quite complicated. Then performing some tests I found that it was much easier than I thought. So I decided to share.

I am using my select of my crud, but in case of fetch the mysql information, you put the way q wish.

<button type='button' id='1' class='btn btn-primary' onClick='ModalEditar(this.id)'>Alterar</button>

Here is the Jquery I will use to display in modal.

function ModalEditar(id){
$.post('require/jp/jpvisitantes.php',
{
    modalEditar:true,
    id:id,
},
function(res){
    var arr = $.parseJSON(res);
    $('#ModalVisitantes').modal('show'); //exibir no modal primeiro, senão, não exibe os dados
    $("#nome").val(arr[0]);
    $("#cpf").val(arr[1]);
    $("#rg").val(arr[2]);
});

PHP file:

extract($_POST); //recebe todas as informações enviada via post e cria as variaveis automaticamente.

if(isset($modalEditar)){
    $visitante=$crud->select('visitantes', 'WHERE id = '.$id);
    foreach($visitante as $dt){
        $dado[0] = $dt['nome'];
        $dado[1] = $dt['cpf'];
        $dado[2] = $dt['rg'];
    }
    echo json_encode($dado); //retorna a variavel dado
}

Modal that will receive the information:

<div class="modal fade" id="ModalVisitantes" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
            <div>Nome:
              <input type="text" class="form-control" id="nome" maxlength="90" required>
              <input type="hidden" id="id"/>
            </div>
            <div style="width:50%; float:left; min-width:150px;">CPF:
              <input type="text" class="form-control" id="cpf" maxlength="14" required="required">
            </div>
            <div style="width:50%; float:left; min-width:150px;">RG:
              <input type="text" class="form-control" id="rg" maxlength="90">
            </div>
          <br />
      </div>
      <div class="modal-footer">
      </div>
    </div>
  </div>
</div>

Browser other questions tagged

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