How to make a GET request to each line with jQuery

1

Hello,

I have the following code:

$('#checar').click(function() {
    $.ajax({
        type: 'GET',
        url: 'checar.php',
        data: { lista: $('#lista').val() },
        success: function(data) {
            $('#sucesso').html(data);
        }
    });
});

HTML page that the above code is running:

<!DOCTYPE html>
<html>
<head>
    <title>Checar Usuário</title>
</head>
<body>
    <div id="sucesso"></div><br><br>
    <textarea id="lista"></textarea>
    <button id="checar">Checar</button>
</body>
</html>

checar.php:

<?php
$usuario = $_GET['lista'];
$usuarios = 'usuario2|usuario4|usuario6|usuario8';
if(stristr($usuarios, $usuario) !== false) {
    return true;
} else {
    return false;
}

In textarea, the user will inform the list of people he wants to check if they exist in $usuarios , so it will contain more than 1 line.

I would like that when the user clicks on Checar , jQuery sends a GET request to each line, for example, it has 5 rows, each row containing usuario1|usuario2|usuario3|usuario4 , jQuery sends a GET request on those 5 rows, and groups all entire rows that PHP returned as false, and all rows that PHP returned as true.

Thank you in advance.

    
asked by anonymous 04.03.2017 / 08:49

1 answer

2

I think that this work, considering that it is to divide the found of the not found and send as a reply, should be left to the server side:

checar.php:

if(isset($_GET['nomes'])) {
    $arrNomes = explode("\n", $_GET['nomes']);
    $usuarios = 'usuario2|usuario4|usuario6|usuario8';
    $nomesValidos = explode('|', $usuarios);
    $found = array();
    $notFound = array();
    foreach($arrNomes as $nome) {
        if(in_array($nome, $nomesValidos)) { // existe
            $found[] = $nome;
        }
        else {
            $notFound[] = $nome;
        }
    }
    echo json_encode(array('found' => $found, 'not_found' => $notFound));
    die();
}

Ajax / HTML:

<textarea id="lista"></textarea>
<button id="checar">Checar</button>
<div id="sucesso"></div>
<div id="errors"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#checar').click(function() {
    $.ajax({
      type: 'GET',
      url: 'checar.php?nomes=' +encodeURIComponent($('#lista').val()), // manter os espaços
      success: function(data) {
          data = JSON.parse(data);
          $('#sucesso').html('<b>Encontrados: </b>' +data['found'].join(', '));
          $('#errors').html('<b>Não encontrados: </b>' +data['not_found'].join(', '));
      }
  });
});
</script>
    
04.03.2017 / 10:46