How to send "&" as request parameter in ajax
I pass form data to php using jquery code then the php code save the data to the mysql database. If the title is "how to save & to mysql database using php"
, then the title will stored in database as "how to save"
. How can i fix this?
Here is my JS code
var dataString = 'title='+ title + '&url=' + url + '&description=' + description + '&published=' + published+ '&catid=' + catid;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$(".button").hide();
$('#messages').html("<div id='message'></div>");
$('#message').html("<h2>weblink Form Submitted!</h2>")
.hide()
.fadeIn(1500, function() {
$('#message');
});
}
});
and php code
<?php
$con = mysql_connect("localhost","db","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dalanrep_dalanreportcom", $con);
$title = mb_convert_encoding(trim($_POST['ti开发者_开发百科tle']),'HTML-ENTITIES', 'UTF-8');
$url = mb_convert_encoding(trim($_POST['url']),'HTML-ENTITIES', 'UTF-8');
$description = mb_convert_encoding(trim($_POST['description']),'HTML-ENTITIES', 'UTF-8');
$published = mb_convert_encoding(trim($_POST['published']),'HTML-ENTITIES', 'UTF-8');
$catid = mb_convert_encoding(trim($_POST['catid']),'HTML-ENTITIES', 'UTF-8');
$title =mysql_escape_string($title );
$url = mysql_escape_string($url );
$description = mysql_escape_string($description );
$sql="INSERT INTO table (title, url, description,catid)
VALUES ('$title','$url','$description','$catid')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The &
is a special character in URL's. It is the separator character for multiple parameters. You need to either URL-encode the parameter value yourself by encodeURIComponent()
var dataString = 'title' + encodeURIComponent(title) + '&url=' + encodeURIComponent(url) ... ;
or to supply the parameters as a JS object {}
so that jQuery will handle it itself.
var data = {
"title": title,
"url": url,
...
};
You need to encode the ampersand if it's data and not a segment delimiter.
<?php
$var = "some title with an & in it";
$title = htmlentities($var);
...
?>
精彩评论