Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

440
Visualizações
PHP AJAX Notifications if MySQL query returns no rows

Situation

I've got a working script that sends an ajax request to get_code.php. This script is run from the main page - index.php. The get_code.php script queries my MySQL DB for a row and then sends back the data to index.php.

Current code

jQuery in index.php

<script type="text/javascript">
$("#CMTCode").click(function(){
    var cde = $("#cmtcodeinput").val();
        $.ajax({
            method:'POST',
            url:'get_code.php',
            data: {va_code:cde},
            dataType: 'json',
            success: function(output_string){
                    $('#rtable').append(output_string);
                    $("#cmtcodeinput").val('');
                    var prc = $(".price:last");
                    prc.focus();
            }
        });
});    
</script>

PHP script get_code.php

<?php
include('dbc.php');
$code = $_POST['va_code'];
$cq = mysql_query("SELECT * FROM variants where va_code='$code'")or die(mysql_error());
  if(!$cq){
mysql_close();
echo json_encode('There was an error running the query: ' . mysql_error());
  }elseif(!mysql_num_rows($cq)){
mysql_close();
echo json_encode('No results returned');
  }else{
$output_string = '';
$output_string .= '<tr>';
while($row = mysql_fetch_assoc($cq))
{        
     $output_string .= '<td>'.$row['cmtcost'].'</td>';
//etc. etc. lots more output here
}
     $output_string .= '</tr>';
}
mysql_close();
echo json_encode($output_string);
?>

Problem

However, if no results are found for the query, nothing is returned on the page to notify the user. Ideally I'd like to open a modal, or display a div in which I can use the data the user input. I just can't work out for the life of me how to check if $cq returns no results, and if so then to display something on index.php like a notification saying 'Your code was not found'.

Appreciative of any help

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You could return a result flag. This is a good logic and easy to understand.

If no row was found :

die(json_encode(['result' => false, 'error' => 'No code was found']));

If some code found :

die(json_encode(['result' => true, 'output' => $output_string]));

And in js :

...
success: function(data){
    if (!data.result) {
        alert(data.error);
    } else {
        $('#rtable').append(data.output);
        $("#cmtcodeinput").val('');
        var prc = $(".price:last");
        prc.focus();
    }
}
...

Hope it helps.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda