How to place a GET order on each line with jQuery

Asked

Viewed 212 times

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>

check.php:

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

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

I wish that when the user clicked on Checar, jQuery sent a GET request to each line, for example, it has 5 lines, each line containing usuario1|usuario2|usuario3|usuario4, jQuery sent a GET request on these 5 lines, and grouped all entire lines that PHP returned as false, and all lines that PHP returned as true.

Thanks in advance.

1 answer

2


I think that this work, given that it is to divide the found from the found and send as an answer, should stay on the server side:

check.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>

Browser other questions tagged

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