Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

439
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda