Reputation: 25
I have a problem with transmitting php data in ajax function. What I want is to send a html form, in which i have php value from a mysqli_fetch_array. The value is the number of the post, which is my primary key. Being new to javascript, I don't really know how to do this. Here is my onclick function code :
<script>
function foo () {
$.ajax({
url:"vote.php?no_post=<?php $post ['no_post'] ?>", //what I'd like to do
type: "POST", //request type
success:function(result)
{
alert(result);
}
});
}
</script>
In the php page, I have this fetch array, here we focus on button named "up" :
if(!isset($_POST['more']))
{
while($post = mysqli_fetch_array($res))
{
echo
'<p>'.
'<center>'.
'<img src="image/'.$post['image_post'].'">'.
'</center>'.
'<br/>'.
'<label>'.$post['desc_post'].'</label>'.
'<p>'.
'<a id="darkBlue" href="account.php?no_post='.$post['no_post'].'">'.'@'.$post['login'].'</a>'.
'<p>'.
'<label>'.$post['time'].'</label>'.
'<p>'.
'<label>'.$post['vote_post'].' points'.'</label>'.
'<footer>';
if (isset($_SESSION['login']))
{
echo '<button class="btn btn-success" name="up" id="up" onclick="foo()">+</button>'.
' '.
'<button class="btn btn-danger" name="down" id="down">-</button>'.
' '.
'<a href="commentaire.php?no_post='.$post['no_post'].'" class="btn btn-warning">Comment</a>'.
'<hr>';
}
EDIT***
And finally my php page where the sql request is executed :
<?php
if (isset($_POST['up'])) // 2 buttons on the first html FORM
{
$req="UPDATE post SET vote_post=vote_post+1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my url
$res=mysqli_query($con,$req);
}
else if (isset($_POST['down']))
{
$req2="UPDATE post SET vote_post=vote_post-1
WHERE no_post=".$_GET['no_post'].""; //picking up the value from my URL
$res2=mysqli_query($con,$req2);
}
else
echo 'Error';
?>
Thanks for you help.
Upvotes: 0
Views: 111
Reputation: 6223
You have missed echo
in below line.
url:"vote.php?no_post=<?php echo $post['no_post'] ?>", //what I'd like to do
EDIT
As you have used POST
method, it should be passed in data
like:
$.ajax({
url:"vote.php",
type: "POST", //request type,
data: {
postCount : <?php echo $post['no_post']; ?>
}
success:function(result)
{
alert(result);
}
});
Upvotes: 1
Reputation: 1785
You can try something like that :
<script>
function foo () {
$.ajax({
url:"vote.php",
type: "POST", //request type
data: {no_post: <?php echo '$post['no_post']'?>}
success:function(result)
{
alert(result);
}
});
}
</script>
It's better to use data : [...]
instead of using parameters in url
Upvotes: 0