5

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>";
}
?>
Roucher
  • 151
  • 7
  • doesn't look like PHP's being parsed here. show your code and the extension used and if PHP's running/installed and how you're accessing that file. – Funk Forty Niner Nov 27 '15 at 13:10
  • 2 seconds and an 'expert' has already -1 it just cause im a newbie trying to learn. Wow, thanks! – Roucher Nov 27 '15 at 13:10
  • @Fred-ii- Im not trying to make you the code for me, just orientations like the one of the php being parsed. I will check that, thanks! – Roucher Nov 27 '15 at 13:12
  • AJAX is a fancy word for "retrieve part of the website and do something with it". So - your page renders, certain elements have JS defined actions that call URLs that correspond to PHP controllers that return HTML that JS does something with. – eithed Nov 27 '15 at 13:12
  • 1
    In your second page, you did not use json_encode - instead you likely just var_dumped the array - here: a tutorial: http://www.thecave.info/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/ – mplungjan Nov 27 '15 at 13:13
  • 3
    I'm having trouble wrapping my head around this. Question is: *why* is there "code" showing in there, rather than being parsed? My first comment wasn't answered. You'll need to show your PHP and we don't know how you're accessing these files, on a hosted site, on your own PC, if local as `http://localhost/file.php` or as `c:///file.php`? as `.htm`? no idea sorry. Wish I could help you more. – Funk Forty Niner Nov 27 '15 at 13:21
  • 1
    Also: [how-does-ajax-work](http://stackoverflow.com/questions/1510011/how-does-ajax-work) – Lucas Pottersky Nov 27 '15 at 13:25
  • You must return a json object to he ajax call, try to change "echo $page;' to "echo json_encode($page)". After submitting the form try also to see which response you get. – Franco Nov 27 '15 at 14:12

1 Answers1

1

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

KiRiCh
  • 38
  • 1
  • 8
  • Not exactly my case, but I get what you try to say – Roucher Nov 30 '15 at 08:40
  • Sorry I couldn't be more specific. I thought i point out how ajax is used, because you said you needed help with that. It is very powerful and useful. You have client code (js, jquery) and server code (php). Axaj is the bridge between client and server. – KiRiCh Dec 02 '15 at 16:03