I am having issue after a successful AJAX post, where the updated div disappears after a few moments
Below are the jquery/PHP/POST data in succession.
Button On Click Function:
function Delete_ID(clickBtnValue,clickBtnID,clickBtnName) {
var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
$.ajax({
type: 'POST',
url: '../Programs/Programs.php',
data: my_data,
success: function (data) {
$('#ProgramsTable').load("../Programs/ProgramChange.php");
$('#update-div').html(data);
}
});
}
PHP DIV display:
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
POST in Programs.php:
if (!empty($_POST)) {
if ($_POST['passvalue'] == "Delete"){
DB_Delete_Program_list($_POST['passid']);
echo $_POST['passname'] . " has been deleted";
}
if ($_POST['passvalue'] == "Edit"){
echo ' <div class="form_div"><form class="Edit_form" method="post">';
echo ' <div style="margin-top:5px"><input type="text" style="height:20px;" id="'.$_POST['passid'].'" value="'.$_POST['passname'].'" size="40" maxlength="253"></div>';
echo ' <div style="margin-top:10px"></div>';
echo ' <div ><input class="form_submit" type="Submit" name="Edit_button"></div>';
echo ' </form></div>';
}
return true;
}
When I press delete, it will display for example "Program 1 has been deleted" and then disappear
When I press edit, the new form table and display and then disappear
Here is a screen record of my issue
What do I need to change, to make it so my div data "table" refreshes with the latest SQL data while also keeping the success text message?
DSICLAIMER
Yes I am aware that the EDIT POST option is not how it's supposed to be, as I am just testing the success message return.
Yes there is SQL mitigation in place
I believe what's happening is when you click your button, you're submitting the form while also triggering your Delete_ID function. So, what happens is the JS function executes and displays your div, but the page also reloads, so you only see it for a moment. What you need to do is to call preventDefault() on the event that is generated by the onclick event.
As a tangent, to make passing the data to your Delete_ID function easier, I'd recommend using data attributes rather than passing the data as properties to the function itself.
This is how I'd redo your code.
For your form buttons, remove the onclick attribute, and use the data- attributes for relevant properties. I also added delete-button and edit-button classes to each button to distinguish them.
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button data-name-hash="{$list_programs[$ii]["Name_Hash"]}" data-program-name="{$list_programs[$ii]["Program_Name"]}" class="button delete-button">Delete</button>
<button data-name-hash="{$list_programs[$ii]["Name_Hash"]}" data-program-name="{$list_programs[$ii]["Program_Name"]}" class="button edit-button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
Then in your javascript, assign the on-click function to buttons with the matching class. This allows you to access the click event in that function.
$('.delete-button').click(Delete_ID);
Now, update the function definition to use the click event and pull the data from data attributes:
function Delete_ID(event) {
event.preventDefault(); // Stop the form from submitting so the page doesn't reload
const clickedBtn = event.target; // This is a reference to the <button> itself.
const clickBtnValue = 'Delete'; // You could pass this via data attributes too; I assume you'll probably have a separate Edit_ID function though.
// Pull the values from the `data-` attributes on the clicked button
// Note that JS converts the kebab-case attribute names (eg: data-name-hash) to camelCase with "data" removed (eg: nameHash).
const clickBtnID = clickedBtn.dataset.nameHash;
const clickBtnName = clickedBtn.dataset.programName;
var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
$.ajax({
type: 'POST',
url: '../Programs/Programs.php',
data: my_data,
success: function (data) {
$('#ProgramsTable').load("../Programs/ProgramChange.php");
$('#update-div').html(data);
}
});
}
Here's a very basic JSFiddle example of using preventDefault with data attributes.
you need to prevent your form to be submitted when you press Delete/Edit button, you can do it by remove form tag
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Edit</button>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
or return false on button click event
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" class="button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
Related
I am building a basic commenting system for a website: Comments can be made and users can reply on every comment. I am using ajax for submitting and retrieving/displaying the comments and replies. I have successfully coded the comments part, but need assistance on the replies part.
Every comment stored in the database has a unique id (comment_id) associated with it. And I use that id to associate replies to each respective comment.
The form for the comments, which is in index.php:
<div id="showComments"></div> <!--div where comments are inserted by AJAX-->
<div style="text-align:center;">
<form action="" method="post" id="commentForm">
<textarea name="comment" id="comment" rows="1"></textarea><BR>
<button type="submit" name="new_comment" onClick="submitComment()">Comment</button>
</form>
<div id="message"></div> <!--div where a status (comment submitted successfully or failed) is inserted by AJAX-->
</div>
The JavaScript for submitting the comment and displaying the comments, also in index.php.
<script>
$(document).ready(function() {
showComments();
});
function submitComment(){
var commentText = document.getElementById('comment').value;
var commentString = 'comment=' + commentText;
event.preventDefault();
$.ajax({
url: "insert_com.php",
method: "POST",
data: commentString,
dataType: "JSON",
success: function(response) {
if (!response.error) {
$("#commentForm")[0].reset();
$("#message").html(response.message);
showComments();
} else if (response.error) {
$("#message").html(response.message);
}
}
});
}
function showComments() {
$.ajax({
url: "get_com.php",
method: "POST",
success: function(response) {
$("#showComments").html(response);
}
});
}
</script>
The file insert_com.php, which submits the comment to the database, to where AJAX posts in the submitComment() function:
<?php
if(!empty($_POST["comment"])){
$new_com_date = date('Y-m-d H:i:s');
$insertComment = "INSERT INTO comments (text, date) VALUES ('".$_POST["comment"]."', '".$new_com_date."')";
mysqli_query($connect, $insertComment) or die("database error: ". mysqli_error($connect));
$message = '<label>Comment posted Successfully.</label>';
$status = array(
'error' => 0,
'message' => $message
);
} else {
$message = '<label>Error: Comment not posted.</label>';
$status = array(
'error' => 1,
'message' => $message
);
}
echo json_encode($status);
?>
And the file get_com.php, which retrieves and displays the comments but also retrieves the replies and contains the form for submitting the replies
<?php
require 'php/connect.php';
$comment = mysqli_query($connect, "SELECT * FROM `comments` ORDER BY `date` DESC");
$string ="";
foreach($comment as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$comment = $item['text'];
$comment_id = $item['id'];
$string .= '<div style="text-align:center;">'
.'<div id="'.$comment_id.'" style="text-align:center;">'
.'<span><b>'.$comment.'</b></span> '
.'<span><b>'.$date.'</b></span> '
.'<span><b>'.$comment_id.'</b></span>'
.'</div>';
$reply = mysqli_query($connect, "SELECT * FROM `replies` WHERE `comment_id`='$comment_id' ORDER BY `date` DESC");
foreach($reply as $com) {
$reply_date = new dateTime($com['date']);
$reply_date = date_format($reply_date, 'M j, Y | H:i:s');
$reply_com = $com['text'];
$com_id = $com['comment_id'];
$string.= '<div>'
.'<span>'.$reply_com.'</span> '
.'<span class="time">'.$reply_date.'</span> '
.'<span><b>'.$com_id.'</b></span>'
.'</div>';
}
$string .=
'<div>'
.'<form action="" method="post" id="replyForm">'
.'<textarea name="new-reply" id="new-reply" rows="1"></textarea>'
.'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
.'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
.'<span><b>'.$comment_id.'</b></span>'
.'</form>'
.'<span id="replymessage"></span>'
.'</div>'
.'</div>'
.'<hr style="width:300px;">';
}
echo $string;
?>
Now, here is where the problem comes in. I want to use AJAX to submit a reply to a particular comment with an id $comment_id. I want to get this id from the hidden input contained in the reply form (The form with id replyForm.
I wrote the following JavaScript to retrieve the id belonging to a particular comment:
<script>
function submitReply(){
var replyText = document.getElementById('new-reply').value; console.log(replyText);
var commId = document.getElementById('com_id').value; console.log(commId);
event.preventDefault();
...
</script>
As you can see, I log the form text (the reply) and the comment id to the console to see whether I am capturing the correct data, but it always returns the id of the last comment submitted. (i.e the reply form works for the last comment. The JavaScript logs the correct text and comment id for a reply on the last comment, but for all other replies it returns the text of the reply on the last comment and the id of the last comment.
I know it's quite a lot of code, so if anyone more experience could assist me it would certainly be appreciated.
You have more than one element with id="com_id". id should be unique. What you can do is when you are generating the DOM in get_com.php, instead of
'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
You can call submitReply() with the right ID, like so:
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply('.$comment_id.')">Reply</button> '
Then, the comment ID would be the argument of your submitReply method and you wouldn't need to read it from the input field.
<script>
function submitReply(commId){
var replyText = document.getElementById('new-reply').value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
Your <textarea> has the same issue as well.
I suggest to assign a unique ID to your <textarea> as well, something like "reply-'.$comment_id.'". Then, when submitReply(comment_id) gets called, you know which comment ID is the call for, so you can construct the unique ID for the exact same textarea, and get the value of the desired element.
<script>
function submitReply(commId){
var replyText = document.getElementById('reply-' + commId).value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
I am working on POS web.
creating form for each item in cart/order i.e multiple forms in loop and giving them unique ids ('id'=>'cart_'.$line )(cart_1,cart_2).
and created an update link in loop for each form. code below
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control'));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control'));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
This fulfils the update requiremnt like when I update a quantity and click the link it updates the price.
But now the problem is that I want my form to submit on onChange event of quantity field.
1) First Try
<script type="text/javascript">
$("#quantity,#discount").on('change',function(){
var quantity=$("#quantity").val();
var discount=$("#discount").val();
if(quantity!=""&&discount!=""){
document.getElementById('anchor').click();
console.log('form send');
}
});
</script>
this is what I tired but it only works if there is only one item in order
2)Second try
function updateQuantity(anchorID){
if(anchorID != ""){
document.getElementById(anchorID).click();
}
}
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'onChange'=>'updateQuantity(HERE I WANT TO PASS "anchorID_LOOP VALUE")' 'id'=>'quantity','class'=>'form-control'));
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id='<?php echo 'anchorID_'.$line ?>' title=<?php echo $this->lang->line('sales_update')?> >
Rather than triggering a button.click() You should try the following:
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal line-item', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control cartline', 'data-form' => $line));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control cartline', 'data-form' => $line));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
Notice I gave the form control an extra class and a data- attribute to hold the $line variable
So now I can catch the event and submit the form
$(function(){
$('.cartline').change(function(){
var line = $(this).attr('data-form');
$('#cart_' + line).submit();
});
});
To send the form via AJAX, you have to handle the form submit function (I gave the form a new class line-item)
$(".line-item").submit(function(event) {
event.preventDefault();
var line_form = $( this ),
url = line_form.attr( 'action' );
//Make your data
$.post( url, { data-field1: $('text1').val(), data-field1: $('text2').val() }, function(data){
alert('Form Posted')
});
});
I have an ajax autocomplete where it returns the full name of the user. However, when there are instances where some names or values are the same, it doesn't return the correct value. Rather, it returns the first value in the dropdown. Even if it has 4 same occurences, it still returns the first value.
When I click Stannis Arryn Baratheon, it returns Stannis Targaryen Baratheon.
Here is my php code (sql/php code; ad.php):
<?php
include('config.php');
if($_POST)
{
if($_POST['search_keyword'])
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
//$name = $row['fullname'];
//$copiedname = $row['fullname'];
//$b_name= '<strong>'.$similar.'</strong>';
//$final_name = str_ireplace($similar, $b_name, $name);
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
HTML input form:
<form method="post" action="try.php" name="try">
<div class='web'>
<input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
<input type="hidden" name="resID" id="resID"/>
<div id="result"></div>
<input type="submit" name="try" value="Submit">
</div>
AJAX/JS/JQUERY CODE (i think this is where the problem occurs):
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "ad.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").on("click", function(e)
{
/*var $clicked = $(e.target);
var $name = $clicked.find('.returnName').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
var $clicked = $(e.target);
var $id = $clicked.find('.returnID').html();
var id = $("<div/>").html($id).text();
$('#resID').val(id);
*/
$name = $('span.returnName',this).html();
$name = $("<div/>").html($name).text().toString();
$('#search_keyword_id').val($name);
$id = $('span.returnID',this).html();
$id = $("<div/>").html($id).text().toString();
$('#resID').val($id);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
jQuery("#result").hide();
}
});
});
</script>
It really returns the first value even if I click the second or third or fourth value. Where did I go wrong in my code? Please help me. Thank you so much!
Your code is currently collecting all elements with class returnName in #result, and by calling .html() on that collection jQuery will only return the html of the first element found. The same goes for the your returnID search. This is why you are only getting the first returned entry.
Modify your #result click handler to only trigger for elements with class show, since that is the element that will contain your data.
jQuery("#result").on("click", ".show", function(e){
Then all you have to do is search for the elements with class returnName and returnID and call .text().
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
So all together
jQuery("#result").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
});
Though note there are probably better ways of returning your data, and utilizing it rather than transporting it in html elements. For example use data-* attributes instead of using a separate span element to contain your id.
Another option is to use jQuery-UI's autocomplete that does most of the client side work for you and just return the raw data in JSON format from your php script.
In your php code, change this:
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
With this:
<div class="show" align="left">
<span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>
And your new jquery function:
jQuery("#result").on("click","'.returnName" function(e)
{
var choosenName = $(this).html();
var choosenId = $(this).data('id');
$('#search_keyword_id').val(choosenName );
$('#resID').val(choosenId );
});
Jquery/Ajax rookie here
This is how my code should work...
When the submit button is clicked, JavaScript handles the form and post the values to the same page. The values are used in a SQL query to update a column in the database. The value from the column is echoed out and updated each time the button is clicked (SQL UPDATE QUERY), all this would be done without refreshing the page using ajax (i.e "ONLY" the value from the database would be refreshed when the button is clicked and the page shouldn't scroll back to the top). The problem is my JavaScript isn't handling the form submission as i expect it to. The div around the value isn't refreshing, i have to redirect to a different page and back to see the changes (SQL query works). How do i solve my problem to achieve this?
file.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ajaxform').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
url: "file.php", // the file to call
success: function(response) { // on success..
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" id="ajaxform"
enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
echo '<div id="emailform"></div>';
}
?>
</body>
</html>
query.php
<?php
if( isset( $_POST['lkcv'] ) && is_array( $_POST['lkcv'] ) )
{
$idArray = array();
foreach( $_POST['lkcv'] as $value )
{
$idArray[] = intval( $value );
}
$db->query( "UPDATE comment SET like1 = like1 + 1 WHERE id IN (".implode(
',', $idArray ).")" );
}
?>
NOTE: file.php always has a dynamic url such as "file.php?post=1"
I don't know php, so apologies if some of this is wrong.
does file.php write out a full html page? If so, it should only be sending out a fragment as ajax deals with partial updates rather than pulling in an entire page.
In your success handler, you are only updating the #emailForm div, when really you also want to be replacing the content on the page with the new version.
2nd, in html, tags with an id are expected to be unique. You output
<div id="emailForm"></div>
in a loop, therefore, it isn't unique on the page, so you might not get the right one being updated
There is a parameter for $.ajax called cache, setting that will append a timestamp to your query, ensuring it is unique, no need to manually create a unique url.
$.ajax({
cache: false,
....
Lastly, to make sure that you are getting fresh content, check your web server logs to look for a http response, which means that the content hasn't changed, so the webserver sent a cached copy
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#content').on("submit", "form", function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
cache: false,
url: "file.php?=" + $(e.currentTarget).find("name=lkcv[]").val(), // the file to call
success: function(response) { // on success..
$(e.currentTarget).html(response); // only replace the form that caused the submit
$('#emailform').html("Thank you!"); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...................
echo '<div id=content>';
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
}
echo '</div>';
echo '<div id="emailform"></div>';
?>
I am working in wordpress and I want to fetch the updated value of aid field from form each time a submit button is pressed. There are two submit buttons and I want the id as per the clicked row
HTML Form(it is shown dynamically with php code)
foreach( $results as $result ) {
$form.= '<form id="voteform" action="" method="post">';
$form.= "<input id='aid' name='aid' type='text' value='$result->aid'>";
$form.=" <input class='star' class='star' id='star5' type='submit' name='star5' value='5'>";
$form.=" <input class='star' class='star' id='star6' type='submit' name='star5' value='5'></form";
jQuery
$(document).on("click",".star", function(e) {
e.preventDefault();
var aidd = jQuery("#aid").val();
sentdata =({
action: 'star',
aid:aidd,
})
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
alert(aid);
$("#myresult").html(res);
return false;
} //end of function
,
'json'); }); //end inner function
}); //end main function
php code
add_action( 'wp_ajax_star', 'star' );
add_action( 'wp_ajax_nopriv_star', 'star');
function star()
{
$aid = $_POST['aid'];
echo json_encode($aid);
die();
}
So you have to get the closest parent form element for the submit button then.
Try like this:
var aidd = $(this).closest("form").find("#aid").val();