0

I'm working on a search page in PHP(buscador.php) and what I need is to show(always in the same page buscador.php) the employee info depending on the ID typed, for that I' coded a Jquery function using $.ajax in order to get the data via AJAX and JSON format(The database query is coded in process.php)

My problem is that when I define the ID and click submit button, it redirects me to process.php instead of show me the info in a special area inside buscador.php, the info process.php displays is:

{"users":{"status":"OK","0":{"ID":"001","Nombre":"algo","cargo":"algo cargo"},"1":{"ID":"PHP001","Nombre":"Pablo Ernesto Tobar Mayora","cargo":"Web Programmer"},"2":{"ID":"PHP002","Nombre":"Pabletoreto Blogger","cargo":"Blogger Manager"},"3":{"ID":"PHP003","Nombre":"prueba de stored procedure en MySQL","cargo":"Database Administrator"},"4":{"ID":"PHP004","Nombre":"Prueba de funciones en MySQL","cargo":"Database Tester"}}}

That's not the result I' looking for, but as you can see the query to the database is done and besides of that the info displays in JSON format but I couldn't manage to display that info in the buscador.php page, could you please tell me wht am I doing wrong please, my whole code is :

buscador.php

<html lang="es-ES">
<head>
<meta name="tipo_contenido"  content="text/html;" http-equiv="content-type" charset="utf-8">
<link type="text/css" rel="stylesheet" href="content/estilos.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="javascript/jquery.js" type="text/javascript"></script>

<title>BUSCADOR</title>
</head>
<form method="post" id="form_id" action="process.php">
<fieldset>
<legend> Buscador Asincrono</legend>
 <p>ID a buscar: <input type="text" name="ID_name" id="ID_id"/><div id="estado_id"></div></p>
 <p><input type="submit" id="submit_id" value="Buscar"/></p>
 <img src="imagenes/cargando.gif" id="LoadingImage"  style="display:none" align="center"/>
 <div id="ajax_id"><b>Person info will be listed here...</b></div>
 <div id="msg">
<table id="infoemp" border="1" style="display:none" align="center">
<thead>
<th>ID</th>
<th>Nombre</th>
<th>Cargo</th>
</thead>
<tbody></tbody>
</table>
</div>
</fieldset>
</form>
</html>

jquery.js

$(document).ready(function() {
  $("#form_id").submit(function(e){
    e.preventDefault(); 
     if(validaForm()){  
       requestInfo();
    } 
  });
});

function validaForm(){
        var id_val = $("input#ID_id").val().trim(); 
        //var id_val = id.val().trim();
        if((id_val=="") || id_val.replace(/s+/,'') == ''){
            alert("Favor ingrese el ID");
            $("input#ID_id").addClass("posicionamiento");
            $("#ajax_id").html("<div class='error'>Debe especificar el nombre</div>");
            return false;
        }else{  
        $("input#ID_id").removeClass("posicionamiento");
        $("#div_id").empty();
        }
        return true;
}   

   function requestInfo(){

    $("#submit_id").hide();
    $("#ajax_id").html("");
    $("#LoadingImage").show();
    $("#ajax_id").html("<div class='cargando'> realizando busqueda</div>");

    var url = $("#form_id").attr('action'); 
    var data = $("#form_id").serialize();   
    var type = $("#form_id").attr('method');
    alert(url);

    $.ajax({
    url:url,          
    data:data,       
    type:type,      
    cache: false,  
    contentType: "application/x-www-form-urlencoded", 
    dataType: 'json', 
    encode: true,
       }); 

.done(function(data) { 
if(data.status == "OK"){
$("#submit_id").show();
$("#ajax_id").html("");
$("#LoadingImage").fadeOut();   
$("#infoemp").show();

$.each(data.users, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.ID+"</td>"
+"<td>"+user.Name+"</td>"
+"<td>"+user.cargo+"</td>"
+"</tr>" ;
$(tblRow).appendTo("#infoemp tbody");
});
} else {  $("#ajax_id").html(data.status).addClass("cargando"); }
});

.fail(function( jqXHR, textStatus, errorThrown ) {
  if ( console && console.log ) {
       console.log( "La solicitud a fallado: " +  textStatus);
     }
    });

    }

process.php

<?php

$bd = "ejemplo";
$server ="localhost";
$user = "root";
$password = "";

if (isset($_POST['Submit']) && isset($_POST['ID_name'])) {
    $valor = filter_var($_POST['ID_name'], FILTER_SANITIZE_STRING);

    $var = array();

    if ($valor == null)
    $var["status"]="ERROR";
    exit(); 
    } else {

    $mysqli = mysqli_connect($server, $user, $password, $bd);
    if( ! $mysqli ) die( "Error de conexion ".mysqli_connect_error() );

$var["status"]="OK";
$sql = "SELECT * FROM empleado_php";

$result = mysqli_query($mysqli, $sql);

while($obj = mysqli_fetch_assoc($result)) {

$var[] = $obj;
}

$mysqli->close(); 
   }
echo '{"users":'.json_encode($var).'}';
header('Content-type: application/json; charset=utf-8');

?>
10
  • Why you're doing this echo '{"users":'.json_encode($var).'} ? Commented May 18, 2015 at 20:32
  • You're already preventing the default action. Are there any errors? Commented May 18, 2015 at 20:35
  • Hello, yes I' already prevent the default action, I don't understand why it redirects to process.php Commented May 18, 2015 at 20:37
  • I use the {"users":'.json_encode($var).'} in order to iterate the results with $.each Commented May 18, 2015 at 20:37
  • @PabloTobar 1) Are you getting any JS errors in the console? 2) Does alert(url) ever happen? Commented May 18, 2015 at 20:38

1 Answer 1

0

You have JS errors.

Remove the semicolon after }) in this snippet:

    encode: true,
       }); 

.done(function(data) { 
if(data.status == "OK"){

And do the same for this snippet, remove semicolon after })

} else {  $("#ajax_id").html(data.status).addClass("cargando"); }
});

.fail(function( jqXHR, textStatus, errorThrown ) {
 

This will fix this specific problem, if you run into PHP errors or more JS errors while looping please Google your problem first and post here if you're unable to find it. Also, try this question to learn how to find JS errors. Note: I just saw you figured out how to find JS errors before I posted the answer. Good job :)

Sign up to request clarification or add additional context in comments.

6 Comments

thanks @rick6 I' already remove the )}; but didn't fix the problem and I' already googled it but didn't find the answer but will continue searching
@PabloTobar Do it for both. That's the problem.
@PabloTobar And only remove the semicolon, not the entire parenthesis and bracket. You're going too fast. Slow down, and read my answer :)
yes, before .done and before .fail and got --> SyntaxError: invalid property id .done(function(data) { line 47 jquey.js in firebug
it works, thank you very much for your patience, I have only one more question, I cannot get the value data.status using this: $("#ajax_id").html(data.status); in process .php I defined $var["status"]="ERROR" or $var["status"]="OK"; but in buscador.php it only display: undefined, could you help me via this way or should I open another post...thanks anyway for your patience
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.