Fabio97 Fabio97 - 4 months ago 10
Ajax Question

return data json from ajax

First of all I'm sorry if my English isn't totally correct.
I'm learning to use json and I want to try with this simple code, where I insert name and surname and with Ajax I send them to a json struct for then show them in a table.
ajax.php

<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<input type="submit" id="invia" value="ISCRIVITI" />
</form>

<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>

<script type="text/javascript">
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
</script>


json.php

<?php
header("Content-Type: application/json", true);
$dati = array( 'nome'=>$_POST['nome'], 'cognome'=>$_POST['cognome'] );
echo json_encode($dati);
?>


Where are the mistakes? Because the outputs are shown for just a second and then they will disappear.
Thank you to everybody.

Answer

On submitting form, it will reload page. So you need to add return false; after your ajax call like,

$("#iscrizione").submit(function(){
    var nome = $("#nome").val();
    var cognome = $("#cognome").val();
    $.ajax({
        url: "json.php",
        type: "POST",
        data: {nome: nome, cognome: cognome},
        dataType: "json",
        success: function(msg){
            $("span#td_nome").html(msg.nome);
            $("span#td_cognome").html(msg.cognome);
        },
        error: function() {
            alert ("Chiamata Fallita");
        }
    });
    return false; // add return false here
});
Comments