WhiteLine
WhiteLine

Reputation: 1991

Save text of textarea in db

the problem is as follows

example

save

hello hello hello

display

hello hello hello

and not hellohellohello

I tried like this, but I lose the formatting of the text

my html page

<textarea id="materiale1" style="margin-top: 0px;width: 715px;height:70px;max-width:715px;max-height:70px;" class="k-textbox"></textarea>

<a href="#" onclick="scrivi();return false;"><span class='k-button' style="margin-top: 0px;"><h3>SCRIVI</h3></span></a>

<textarea id="materiale2" style="margin-top: 80px;width: 715px;height:70px;max-width:715px;max-height:70px;" class="k-textbox"></textarea>

<a href="#" onclick="leggi();return false;"><span class='k-button' style="margin-top: 72px;"><h3>LEGGI</h3></span></a>

call the function for send the textarea text to a file php

function scrivi(){

$.ajax({ 
    type: "GET",
    url : "test_scrivi.php?testo="+$('#materiale1').val(),
    dataType:'json',
    cache: false,
    success: function(dati){ 

     }
     , error : function(errore){ 
     } 
    });
}

file php (test_scrivi.php) for save text of textarea

<?php


 try {

include('../../login/connect_db.php');

$db = new PDO("mysql:host=$my_hostname;dbname=$my_db_name", $my_username, $my_password);

$testo = nl2br($_GET['testo']);

$query = "UPDATE test SET testo='".$testo."' WHERE id = 1";

$result = $db->query($query);


} 
catch(PDOException $e)
{
        //echo $e->getMessage();
}


?>

call the function for read the textarea text

function leggi(){

    $.ajax({ 
            type: "GET",
            url : "test_leggi.php",
            dataType:'json',
            cache: false,
            success: function(dati_arrivati){ 

                $('#materiale2').val(dati_arrivati)

            }
            , error : function(errore){ 
              } 
        });


}

file php (test_leggi.php) for read the text of textarea

<?php


try {

    include('../../login/connect_db.php');

    $db = new PDO("mysql:host=$my_hostname;dbname=$my_db_name", $my_username, $my_password);

    $query = "SELECT * FROM test WHERE id = 1";

    $result = $db->query($query);

    header("Content-type: application/json");

    $testo = "";

    foreach($result as $row)
        {

            $testo = nl2br($row['testo']);


        } 

    echo json_encode($testo);

    $db = null;

} 
catch(PDOException $e)
{
        //echo $e->getMessage();
}


?>

Upvotes: 0

Views: 1656

Answers (1)

Barmar
Barmar

Reputation: 780861

Change your AJAX call to:

$.ajax({ 
    type: "GET",
    url : "test_scrivi.php",
    data: { testo: $('#materiale1').val() },
    dataType:'json',
    cache: false,
    success: function(dati){ 

     },
    error : function(errore){ 
     } 
});

You weren't properly URL-encoding the value. When you use a data object, jQuery does this correctly.

Upvotes: 1

Related Questions