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');

?>
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Pablo Tobar
  • 614
  • 2
  • 13
  • 37
  • Why you're doing this `echo '{"users":'.json_encode($var).'}` ? – Akar May 18 '15 at 20:32
  • You're already preventing the default action. Are there any errors? – Jay Blanchard May 18 '15 at 20:35
  • Hello, yes I' already prevent the default action, I don't understand why it redirects to process.php – Pablo Tobar May 18 '15 at 20:37
  • I use the {"users":'.json_encode($var).'} in order to iterate the results with $.each – Pablo Tobar May 18 '15 at 20:37
  • @PabloTobar 1) Are you getting any JS errors in the console? 2) Does alert(url) ever happen? – rick6 May 18 '15 at 20:38
  • @rick6 Hi, Not any error, a question: do you think my way of using arrays is the error – Pablo Tobar May 18 '15 at 20:41
  • [Quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/), use `console.log()` instead. – Jay Blanchard May 18 '15 at 20:42
  • @PabloTobar I don't think so. You're positive there's no JS errors? Something is stopping JS from executing the AJAX, and instead "reverting" to the default action of the form, which is to (as you say) "redirect" to process.php. – rick6 May 18 '15 at 20:44
  • @rick6 exactly, and when I comment the reuqetsInfo function in jquery.js it prevents the form info to submit, but I' checked once and once again but couldn't find the error – Pablo Tobar May 18 '15 at 20:53
  • @rick6 So So sorry, I would like to add: SyntaxError: expected expression, got '.' .done(function(data) { the error ocurrs in jquery.js line 47 this comment appears in firebug console – Pablo Tobar May 18 '15 at 21:08

1 Answers1

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 :)

Community
  • 1
  • 1
rick6
  • 467
  • 3
  • 8
  • 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 – Pablo Tobar May 18 '15 at 21:29
  • @PabloTobar Do it for both. That's the problem. – rick6 May 18 '15 at 21:31
  • @PabloTobar And only remove the semicolon, not the entire parenthesis and bracket. You're going too fast. Slow down, and read my answer :) – rick6 May 18 '15 at 21:32
  • yes, before .done and before .fail and got --> SyntaxError: invalid property id .done(function(data) { line 47 jquey.js in firebug – Pablo Tobar May 18 '15 at 21:38
  • 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 – Pablo Tobar May 18 '15 at 21:53
  • @PabloTobar That is a separate problem.. Stack Overflow is for specific programming questions, which I gave the correct answer to this specific question.. please mark this answer as accepted :) – rick6 May 18 '15 at 21:56