Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax newbie learning (PHP JQuery)

I am new to AJAX, I'm trying to read a whole page and change an element inside it without refreshing.

I have a page that looks like this:

enter image description here

I am using PHP & JQuery. Whenever I click on any tr, it gets the id and puts the data assigned in the db to that id, on the form. So I can update the user's data.

Obviously when the form is empty it is a standard insert in the database.

When you click the last td of each tr (Eliminar), it deletes that user from the database.

My files:

  • A controller that builds the page (crud.php).
  • A database that contains every database-related method (database.php)
  • CSS files and a template with the basic html, js.

I want to make all this refresh pages with Ajax, but I get something like:

enter image description here

All my page has been inserted in the form instead of replacing my page with the new one, or replacing only the form with a new one.

Any tip/guide that can help me with the learning? I've searched all related AJAX content in this site. Also JQuery site...

I don't really get how AJAX works and how to relate it with the JS and PHP

Relevant code:

//Capturador de eventos
$(document).ready(function(){
//Clickar en cualquier lado del tr (menos el ultimo td) para actualizar ese registro
$("#tablaDatos tr td:not(:last-child").click(function() {
    if (confirm("¿Seguro que desea modificar el registro?")){
        $("#idSelected").val($(this).closest('tr').attr('id'));
        var data = $('#idSelected').serialize(); 
        $.post(
                'crud.php',
                {data: data},
                function(response){
                    $('#result').html(response);
                }
        );
        return false;
    }else
        return false;
});

//Clickar en el borrar del listado para eliminar ese registro
$("#tablaDatos input").click(function(){
    if (confirm("¿Seguro que deseas borrarlo del registro?")){
        $("#idSelected").val($(this).closest('tr').attr('id'));
        $("#eliminar").val("Eliminar");
        var data = $('#idSelected').serialize(); 
        $.post(
                'crud.php',
                {data: data},
                function(response){
                    $('#result').html(response);
                }
        );
        return false;
    }else
        return false;
}); 
// Clickar en Alta/Modificar para enviar los datos al crud a través de post
$('#submit').click(function() {
    var data = $('#envioDatos').serialize();   
    $.post(
            'crud.php',
            {data: data},
            function(response){
                $('#envioDatos').html(response);
                $("#envioDatos input, textarea").val('');
            });
    return false;
    });
});

<?php
// INCLUDES
include 'lib/pintarHTML.php';
include 'lib/database.php';

// VARS
$tableName = 'ALEJANDRO';
$clientes = array ();
$page = null;
$body = null;
$elemSel = null;
$obj_pintar = new pintarHTML ();
$ID = null;
$result = null;
$type = null;

// CONECTION DB
$obj = new database ();

// POST READ
if (isset ( $_POST )) {
    mpr($_POST);

    if ($_POST['alta'] == "Alta" && empty ( $_POST['id'] )) {
        // Llamo a insertar
        $result = $obj->insert ( $_POST );
    } else
    if ($_POST['modificacion'] == "Modificacion" && ! empty ( $_POST['id'] )) {
        // Llamo a modificar
        $result = $obj->update ( $_POST );
    } else
    if ($_POST['eliminar'] == "Eliminar" && ! empty ( $_POST['idSelected'] )) {
        // Llamo a eliminar
        $result = $obj->delete ( $_POST );
    } else
    if ($_POST['idSelected'] && empty ( $_POST ['eliminar'] )) {
        // Elemento Seleccionado
        $ID = $_POST['idSelected'];
    }
}

// Client list
$clientes = $obj->select ( $tableName );


// Title
$body .= $obj_pintar->pintarTitulo ( 'LISTADO DE CLIENTES' );


// Check ID
if (isset ( $ID )) {
// Formulario relleno con los datos del usuario para modificarlos
    $elemSel = $obj->select ( $tableName, '*', 'id=' . $ID, null );
    $body .= $obj_pintar->pintarFormulario ( $elemSel );
} else {
    // Formulario vacío para alta de usuario
    $body .= $obj_pintar->pintarFormulario ( $elemSel );
}


// Page echo
if (!empty($result)) {
    $body .= $obj_pintar->pintarMessage($result);
}


$body .= $obj_pintar->pintarTable ( $clientes );

$page = $obj_pintar->composeHTML ( $body );

echo $page;

// Debug
function mpr($value, $text = null) {
    echo "<pre>" . $text;
    print_r ( $value );
    echo "</pre>";
}
?>
like image 246
Roucher Avatar asked Nov 10 '22 00:11

Roucher


1 Answers

In general Ajax is used for performing some manipulation on data asynchronously. You click something on your page, data gets sent somewhere else to be manipulated and the result of that manipulation is returned as a response. You can then act based on that response.

In your case, say you want to delete some client. You can perform an ajax call to your clientDataEdit.php and tell it to delete a student with a specific ID for example.

$.post( "clientDataEdit.php", { function: "Delete", id: "#someID" } );

Then in your php you check what function is being called (delete in this case) and perform the necessary manipulation

if(isset($_POST['function'])){  
 if(($_POST['function'])=="Delete"){ 
    //perform the manipulation and respond
    echo "OK";
  }
}

Then back on the client page you catch the response and act on it:

$.post( "clientDataEdit.php", { function: "Delete", id: "#someID" })
  .done(function( data ) {
    alert( "Execution status: " + data );
  });

This should give you an alert "Execution status: OK". If it was all ok. You should replace that alert with the necessary local manipulations (for example hide the form, forward to another page, load another form, whatever really).

like image 100
KiRiCh Avatar answered Nov 14 '22 21:11

KiRiCh