How to pass php array to ajax function












0















So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.



public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();

if($stmt->rowCount()>0){
foreach($results as $row){

echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';

//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}


Here is my Ajax call to send the info to my php file



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Then here is the php file that handles the call.



if(isset($_POST['upVoteIncrement'])){

$upVoteIncrement = $_POST['upVoteIncrement'];

$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();


$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();

if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}


Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!










share|improve this question




















  • 1





    Please explain this line....."It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic" again. I didn't get that...

    – Pawan lakhera
    Dec 31 '18 at 6:58











  • So it will increment in the database but only for the last inserted ID in the database (if there are 100 topics, it will only increment the most recent one with ID of 100 and will not increment any other ID) and If I upvote on one of the other topics with say the ID of 47 it will still only upvote ID 100.

    – Stuckfornow
    Dec 31 '18 at 7:05











  • Check how you are populating the $row['topic_id'] value. Looks like your taking it out of a loop but we can't see the loop. Regardless the value appears to be static. Show us some more code for how $row['topic_id'] is being populated.

    – Joseph_J
    Dec 31 '18 at 7:08











  • I edited my question to include the foreach loop I'm using

    – Stuckfornow
    Dec 31 '18 at 7:16











  • not sure if I have to change it to json and dataType to json in order to send the array to the ajax portion. I'm not too familiar with how to go about doing that.

    – Stuckfornow
    Dec 31 '18 at 7:20
















0















So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.



public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();

if($stmt->rowCount()>0){
foreach($results as $row){

echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';

//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}


Here is my Ajax call to send the info to my php file



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Then here is the php file that handles the call.



if(isset($_POST['upVoteIncrement'])){

$upVoteIncrement = $_POST['upVoteIncrement'];

$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();


$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();

if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}


Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!










share|improve this question




















  • 1





    Please explain this line....."It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic" again. I didn't get that...

    – Pawan lakhera
    Dec 31 '18 at 6:58











  • So it will increment in the database but only for the last inserted ID in the database (if there are 100 topics, it will only increment the most recent one with ID of 100 and will not increment any other ID) and If I upvote on one of the other topics with say the ID of 47 it will still only upvote ID 100.

    – Stuckfornow
    Dec 31 '18 at 7:05











  • Check how you are populating the $row['topic_id'] value. Looks like your taking it out of a loop but we can't see the loop. Regardless the value appears to be static. Show us some more code for how $row['topic_id'] is being populated.

    – Joseph_J
    Dec 31 '18 at 7:08











  • I edited my question to include the foreach loop I'm using

    – Stuckfornow
    Dec 31 '18 at 7:16











  • not sure if I have to change it to json and dataType to json in order to send the array to the ajax portion. I'm not too familiar with how to go about doing that.

    – Stuckfornow
    Dec 31 '18 at 7:20














0












0








0








So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.



public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();

if($stmt->rowCount()>0){
foreach($results as $row){

echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';

//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}


Here is my Ajax call to send the info to my php file



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Then here is the php file that handles the call.



if(isset($_POST['upVoteIncrement'])){

$upVoteIncrement = $_POST['upVoteIncrement'];

$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();


$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();

if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}


Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!










share|improve this question
















So I would like to pass the php array values from this form id to my ajax form. Everything works fine except that it will only display the (1) id number.
Here is my form code: I am passing the $row[topic_id'] as a value to get the id for jquery.



public function forumview($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();

if($stmt->rowCount()>0){
foreach($results as $row){

echo '<tr>';
echo '<td style="color: #333;"><span class="pull-right">';

//Problem is here with the $row['topic_id'] portion
if(isset($_SESSION['user_session'])){
echo '<a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue('.$row['topic_id'].');">';
}else{
echo '<a href="#" id="loginForm" class="upVoteArrow" data-
toggle="modal" data-target="#loginModal"><i class="fa fa-arrow-up"></i>
</a>';
}
echo '<span id="voteCount">'.$this->cleanNumber($row['topic_likes']).'</span>';
}


Here is my Ajax call to send the info to my php file



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //not needed

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID,
},
dataType: "json",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Then here is the php file that handles the call.



if(isset($_POST['upVoteIncrement'])){

$upVoteIncrement = $_POST['upVoteIncrement'];

$stmt = $conn->prepare('UPDATE topics SET topic_likes = topic_likes+1 WHERE topic_id = :id LIMIT 1');
$stmt->bindParam(':id', $upVoteIncrement);
$stmt->execute();


$upVote = $conn->prepare('SELECT topic_likes FROM topics WHERE topic_id = :id LIMIT 1');
$upVote->bindParam(':id', $upVoteIncrement);
$upVote->execute();
$upVoteCount = $upVote->fetchAll();

if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit(); //not needed
}
}
echo json_encode($results);
}


Essentially I am just making a simple up vote system that the user clicks on and it updates the database incrementing by 1. It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic. Any advice is much appreciated, thanks in advance!







php jquery ajax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 31 '18 at 9:03







Stuckfornow

















asked Dec 31 '18 at 6:46









StuckfornowStuckfornow

405




405








  • 1





    Please explain this line....."It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic" again. I didn't get that...

    – Pawan lakhera
    Dec 31 '18 at 6:58











  • So it will increment in the database but only for the last inserted ID in the database (if there are 100 topics, it will only increment the most recent one with ID of 100 and will not increment any other ID) and If I upvote on one of the other topics with say the ID of 47 it will still only upvote ID 100.

    – Stuckfornow
    Dec 31 '18 at 7:05











  • Check how you are populating the $row['topic_id'] value. Looks like your taking it out of a loop but we can't see the loop. Regardless the value appears to be static. Show us some more code for how $row['topic_id'] is being populated.

    – Joseph_J
    Dec 31 '18 at 7:08











  • I edited my question to include the foreach loop I'm using

    – Stuckfornow
    Dec 31 '18 at 7:16











  • not sure if I have to change it to json and dataType to json in order to send the array to the ajax portion. I'm not too familiar with how to go about doing that.

    – Stuckfornow
    Dec 31 '18 at 7:20














  • 1





    Please explain this line....."It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic" again. I didn't get that...

    – Pawan lakhera
    Dec 31 '18 at 6:58











  • So it will increment in the database but only for the last inserted ID in the database (if there are 100 topics, it will only increment the most recent one with ID of 100 and will not increment any other ID) and If I upvote on one of the other topics with say the ID of 47 it will still only upvote ID 100.

    – Stuckfornow
    Dec 31 '18 at 7:05











  • Check how you are populating the $row['topic_id'] value. Looks like your taking it out of a loop but we can't see the loop. Regardless the value appears to be static. Show us some more code for how $row['topic_id'] is being populated.

    – Joseph_J
    Dec 31 '18 at 7:08











  • I edited my question to include the foreach loop I'm using

    – Stuckfornow
    Dec 31 '18 at 7:16











  • not sure if I have to change it to json and dataType to json in order to send the array to the ajax portion. I'm not too familiar with how to go about doing that.

    – Stuckfornow
    Dec 31 '18 at 7:20








1




1





Please explain this line....."It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic" again. I didn't get that...

– Pawan lakhera
Dec 31 '18 at 6:58





Please explain this line....."It increments the values and everything works except it will only increment it for the last posted item. So even if I upvote on a topic from earlier it will only add 1 vote to the last inserted topic" again. I didn't get that...

– Pawan lakhera
Dec 31 '18 at 6:58













So it will increment in the database but only for the last inserted ID in the database (if there are 100 topics, it will only increment the most recent one with ID of 100 and will not increment any other ID) and If I upvote on one of the other topics with say the ID of 47 it will still only upvote ID 100.

– Stuckfornow
Dec 31 '18 at 7:05





So it will increment in the database but only for the last inserted ID in the database (if there are 100 topics, it will only increment the most recent one with ID of 100 and will not increment any other ID) and If I upvote on one of the other topics with say the ID of 47 it will still only upvote ID 100.

– Stuckfornow
Dec 31 '18 at 7:05













Check how you are populating the $row['topic_id'] value. Looks like your taking it out of a loop but we can't see the loop. Regardless the value appears to be static. Show us some more code for how $row['topic_id'] is being populated.

– Joseph_J
Dec 31 '18 at 7:08





Check how you are populating the $row['topic_id'] value. Looks like your taking it out of a loop but we can't see the loop. Regardless the value appears to be static. Show us some more code for how $row['topic_id'] is being populated.

– Joseph_J
Dec 31 '18 at 7:08













I edited my question to include the foreach loop I'm using

– Stuckfornow
Dec 31 '18 at 7:16





I edited my question to include the foreach loop I'm using

– Stuckfornow
Dec 31 '18 at 7:16













not sure if I have to change it to json and dataType to json in order to send the array to the ajax portion. I'm not too familiar with how to go about doing that.

– Stuckfornow
Dec 31 '18 at 7:20





not sure if I have to change it to json and dataType to json in order to send the array to the ajax portion. I'm not too familiar with how to go about doing that.

– Stuckfornow
Dec 31 '18 at 7:20












2 Answers
2






active

oldest

votes


















2














If your using a loop to populate the row id, which it looks like you are here are your problems.



The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.



I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.



See if this helps:



PHP:



if(isset($_SESSION['user_session'])){

echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';

}


JS:



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Hope it helps!



I also want to point out that in the code below:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
echo $up;
exit();
}
}


You are exiting the script on the first iteration of the loop and you will only ever get one result back.



If you need to return an array of data it should look like this:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit();
}
}

echo json_encode($results);


You will then need to set your datatype to json instead of html.



The response in your ajax will now be an array. To see the array:



success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}





share|improve this answer





















  • 1





    Well explained Sir.....

    – Pawan lakhera
    Dec 31 '18 at 7:42











  • Thanks Joseph, those changes solved it.

    – Stuckfornow
    Dec 31 '18 at 7:47











  • Hey no problem! I'm glad it helped. Also, you really don't even need the hidden inputs anymore. You can use just the links, unless you need the inputs for something else. Anyways! Good luck with the rest of your project. ~Cheers!

    – Joseph_J
    Dec 31 '18 at 7:51



















1














The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.



function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();


You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:



 <input onclick="upVoteIncrementValue" />


Then your handler:



function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();


Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.






share|improve this answer


























  • Thanks for the help 2oppin. much appreciated.

    – Stuckfornow
    Dec 31 '18 at 7:56











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53984445%2fhow-to-pass-php-array-to-ajax-function%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














If your using a loop to populate the row id, which it looks like you are here are your problems.



The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.



I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.



See if this helps:



PHP:



if(isset($_SESSION['user_session'])){

echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';

}


JS:



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Hope it helps!



I also want to point out that in the code below:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
echo $up;
exit();
}
}


You are exiting the script on the first iteration of the loop and you will only ever get one result back.



If you need to return an array of data it should look like this:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit();
}
}

echo json_encode($results);


You will then need to set your datatype to json instead of html.



The response in your ajax will now be an array. To see the array:



success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}





share|improve this answer





















  • 1





    Well explained Sir.....

    – Pawan lakhera
    Dec 31 '18 at 7:42











  • Thanks Joseph, those changes solved it.

    – Stuckfornow
    Dec 31 '18 at 7:47











  • Hey no problem! I'm glad it helped. Also, you really don't even need the hidden inputs anymore. You can use just the links, unless you need the inputs for something else. Anyways! Good luck with the rest of your project. ~Cheers!

    – Joseph_J
    Dec 31 '18 at 7:51
















2














If your using a loop to populate the row id, which it looks like you are here are your problems.



The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.



I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.



See if this helps:



PHP:



if(isset($_SESSION['user_session'])){

echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';

}


JS:



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Hope it helps!



I also want to point out that in the code below:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
echo $up;
exit();
}
}


You are exiting the script on the first iteration of the loop and you will only ever get one result back.



If you need to return an array of data it should look like this:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit();
}
}

echo json_encode($results);


You will then need to set your datatype to json instead of html.



The response in your ajax will now be an array. To see the array:



success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}





share|improve this answer





















  • 1





    Well explained Sir.....

    – Pawan lakhera
    Dec 31 '18 at 7:42











  • Thanks Joseph, those changes solved it.

    – Stuckfornow
    Dec 31 '18 at 7:47











  • Hey no problem! I'm glad it helped. Also, you really don't even need the hidden inputs anymore. You can use just the links, unless you need the inputs for something else. Anyways! Good luck with the rest of your project. ~Cheers!

    – Joseph_J
    Dec 31 '18 at 7:51














2












2








2







If your using a loop to populate the row id, which it looks like you are here are your problems.



The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.



I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.



See if this helps:



PHP:



if(isset($_SESSION['user_session'])){

echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';

}


JS:



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Hope it helps!



I also want to point out that in the code below:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
echo $up;
exit();
}
}


You are exiting the script on the first iteration of the loop and you will only ever get one result back.



If you need to return an array of data it should look like this:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit();
}
}

echo json_encode($results);


You will then need to set your datatype to json instead of html.



The response in your ajax will now be an array. To see the array:



success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}





share|improve this answer















If your using a loop to populate the row id, which it looks like you are here are your problems.



The loop is creating a hidden input element on every iteration of the loop and you are not changing the id of the element. So you will have a bunch of elements all with the same id. That will cause you problems a few different ways.



I changed your PHP code so that each element will have it's own id. I also changed the your javascript function so that the id value is passed to the function itself.



See if this helps:



PHP:



if(isset($_SESSION['user_session'])){

echo '<input type="hidden" id="' . $row['topic_id'] . '" name="upVoteIncrement"
value="' . $row['topic_id'] . '"><a href="#" class="upVoteArrow"
onclick="upVoteIncrementValue(' . $row['topic_id'] . ');">';

}


JS:



function upVoteIncrementValue(postID){
event.preventDefault();
//var upVoteIncrement = $("#upVoteIncrement").val(); //Don't need this anymore.

$.ajax({
type: "POST",
url: "voting.php",
data: {
"upVoteIncrement": postID, //Use the passed value id value in the function.
},
dataType: "html",
cache: false,
success: function(response){
if(response){
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}
});


Hope it helps!



I also want to point out that in the code below:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
echo $up;
exit();
}
}


You are exiting the script on the first iteration of the loop and you will only ever get one result back.



If you need to return an array of data it should look like this:



if($upVote->rowCount() > 0){
foreach($upVoteCount as $row){

$up = $row['topic_likes'];
$results = $up;
//exit();
}
}

echo json_encode($results);


You will then need to set your datatype to json instead of html.



The response in your ajax will now be an array. To see the array:



success: function(response){
if(response){
console.log(response); //Look in your console to see your data.
var response = $.trim(response);
if(response){
$('#voteCount').html(response);
}
else {
return false;
}
}
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 31 '18 at 7:37

























answered Dec 31 '18 at 7:20









Joseph_JJoseph_J

3,2822620




3,2822620








  • 1





    Well explained Sir.....

    – Pawan lakhera
    Dec 31 '18 at 7:42











  • Thanks Joseph, those changes solved it.

    – Stuckfornow
    Dec 31 '18 at 7:47











  • Hey no problem! I'm glad it helped. Also, you really don't even need the hidden inputs anymore. You can use just the links, unless you need the inputs for something else. Anyways! Good luck with the rest of your project. ~Cheers!

    – Joseph_J
    Dec 31 '18 at 7:51














  • 1





    Well explained Sir.....

    – Pawan lakhera
    Dec 31 '18 at 7:42











  • Thanks Joseph, those changes solved it.

    – Stuckfornow
    Dec 31 '18 at 7:47











  • Hey no problem! I'm glad it helped. Also, you really don't even need the hidden inputs anymore. You can use just the links, unless you need the inputs for something else. Anyways! Good luck with the rest of your project. ~Cheers!

    – Joseph_J
    Dec 31 '18 at 7:51








1




1





Well explained Sir.....

– Pawan lakhera
Dec 31 '18 at 7:42





Well explained Sir.....

– Pawan lakhera
Dec 31 '18 at 7:42













Thanks Joseph, those changes solved it.

– Stuckfornow
Dec 31 '18 at 7:47





Thanks Joseph, those changes solved it.

– Stuckfornow
Dec 31 '18 at 7:47













Hey no problem! I'm glad it helped. Also, you really don't even need the hidden inputs anymore. You can use just the links, unless you need the inputs for something else. Anyways! Good luck with the rest of your project. ~Cheers!

– Joseph_J
Dec 31 '18 at 7:51





Hey no problem! I'm glad it helped. Also, you really don't even need the hidden inputs anymore. You can use just the links, unless you need the inputs for something else. Anyways! Good luck with the rest of your project. ~Cheers!

– Joseph_J
Dec 31 '18 at 7:51













1














The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.



function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();


You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:



 <input onclick="upVoteIncrementValue" />


Then your handler:



function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();


Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.






share|improve this answer


























  • Thanks for the help 2oppin. much appreciated.

    – Stuckfornow
    Dec 31 '18 at 7:56
















1














The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.



function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();


You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:



 <input onclick="upVoteIncrementValue" />


Then your handler:



function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();


Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.






share|improve this answer


























  • Thanks for the help 2oppin. much appreciated.

    – Stuckfornow
    Dec 31 '18 at 7:56














1












1








1







The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.



function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();


You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:



 <input onclick="upVoteIncrementValue" />


Then your handler:



function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();


Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.






share|improve this answer















The problem is that in the event handler you addressing element by id, and it's not always the same that you click on.



function upVoteIncrementValue(){
event.preventDefault();
// Always will be last inserted element
var upVoteIncrement = $("#upVoteIncrement").val();


You can use event to get valid element. It's default argument that passed to handler, but remember to define it without braces:



 <input onclick="upVoteIncrementValue" />


Then your handler:



function upVoteIncrementValue(event){
event.preventDefault();
var upVoteIncrement = $(event.target).val();


Also if you have several elements with the same ID it's invalid HTML, at least it will hit warning at https://validator.w3.org/ .
So you should set id arg for your element only in case if it's unique, and having this mindset will help you to not hit similar issue again.







share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 31 '18 at 7:30

























answered Dec 31 '18 at 7:23









2oppin2oppin

1,4561125




1,4561125













  • Thanks for the help 2oppin. much appreciated.

    – Stuckfornow
    Dec 31 '18 at 7:56



















  • Thanks for the help 2oppin. much appreciated.

    – Stuckfornow
    Dec 31 '18 at 7:56

















Thanks for the help 2oppin. much appreciated.

– Stuckfornow
Dec 31 '18 at 7:56





Thanks for the help 2oppin. much appreciated.

– Stuckfornow
Dec 31 '18 at 7:56


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53984445%2fhow-to-pass-php-array-to-ajax-function%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas