How do I send a variable in a URL through AJAX?
I'm sending the variable like this:
xmlhttp.open("GET","insert-karma.php?pid=<? echo $pid; ?>",true);
The AJAX part doesn't seem to be the problem, if I check the Sript the PHP is echoing the integer correctly. (It displays the url as: insert-karma.php?pid=5
). However the PHP isn't getting the variable. (I tried echoing and it does't show anthing)
This is the PHP file:
// Connect to db;
$pid = $_POST['pid'];
$sql="UPDATE Poems SET Karma = Karma + 1 WHERE Pid = '$pid'";
// Disconnect form database;
What am I doing wrong? How do I manage to send $pid
to the PHP update-kar开发者_如何学Cma.php?
try $pid = $_GET['pid']
or
$pid = $_REQUEST['pid'];
You are sending the variable using GET, so in your php you have to use the $_GET variable
$pid = $_GET["pid"];
Also avoid using your variable directly in your sql query. you will be vulnerable to sql injection.
if using mysql:
$pid = mysql_real_escape_string($_GET["pid"]);
or in case you are passing an integer:
$pid = (int)$_GET["pid"];
first you should not use PHP in you ajax requests it's just make things more complicated and PHP is for server side scripting in the first place secound , you should use xmlhttp.open("POST","insert-karma....) if u plain to use POST Third the only important difference (not the only but the important) between POST and Get is :
GET requests can be cached
GET requests can remain in the browser history
GET requests can be bookmarked
GET requests can be distributed & shared
GET requests can be hacked lool
so u cant use Get For unsecured and dangerous action like LOGIN OR ...
POST Can handel too long Data
Post is more secured Cuz it's not gonna be cached or saved in history or bookmarked
u can clearly notice that POST's dont display in the browsers address bar but Get do 'www.anything.com/index.php?bla=bhe'
i hope that i am helping here !! :)
Just a suggestion here since you have already got the answer. Try to use some javascript library to aid you while you are writing your JS code. I would suggest jquery
And also please read what is the difference in GET, POST requests and when it should be used.
精彩评论