How to send data from browser to server and reply back
On my webpage I have a textarea where the user inputs all kind of characters.
When he saves it I want to send the data using AJAX to the server for storing in the database. After this, the server will send back the data to the browser to be displayed.Which is the right way to do this?
Right now I make an AJAX call:function update()
{
$.ajax({
type: "POST",
url: "ajax/update.php",
data: "ID=" + ID + "&value=" + encodeURIComponent($('#newText').val()),
success: function(html) {
$('#l' + CurrentID).html(decodeURIComponent(html));
}
});
}
and my php file looks like this:
<?php
$ID = $_POST["ID"];
$value = nl2br(urldecode($_POST["value"]));
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = htmlentities($value);
$value = str_replace("<br />", "", $value);
$value = str_replace("<br/>", "", $value);
$value开发者_如何学Go = str_replace("<br>", "", $value);
mysql_query("update MyTable set value = '$value' where id = $ID");
echo html_entity_decode(urlencode($value));
?>
I am not sure I am doing the things right. For sure I can see now the problem with spaces being replaced by + sign. But I am thinking that there is something I am not doing it by the book.
You could improve your AJAX call like this:
$.ajax({
type: "POST",
url: "ajax/update.php",
data: { ID: ID, value: $('#newText').val() },
success: function(html) {
$('#l' + CurrentID).html(html);
}
});
Notice how the data is sent using an object. You no longer need to worry about properly url encoding. jQuery takes care of it.
Also your PHP seems to be vulnerable to SQL injection. You should use prepared statements to avoid this.
精彩评论