I have a jQuery/AJAX function that when triggered from a <select> menu change posts data to a php query and returns results. The results are placed in the <td><label class=count> on the same row as the <select> menu in my table. The function works just fine when the select menu is changed but I also want to trigger this function on page load. I have tried using .trigger(change); at the end of my code but all that does is place the results (2 in this case because there only two table rows) in the <td><label class=count> on the last row instead of placing the result in that cell of the parent row. Can someone help me get the function to run on page load, but the results in the <td><label class=count> of the same row as the select menu that triggered the result?
Here is jQuery:
<script type="text/javascript">
$(document).ready(function(){
$('.typeval').change(function(){
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <? echo $class_id; ?>;
$count = $(this).parents('tr').find('label.count');
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
success:(function(output) {
$.each(output, function(index, value){
//alert(value);
$count.append(output[index]);
}) // each
}) // success
}); // ajax
}); // .typeval
}); // document
</script>
Here is part of the HTML table:
<tr>
<td><input type="hidden" name="client_id[]" class="clientval" value="1"></td>
<td><input type="hidden" name="order[]" value="1A">1A</td>
<td><select name="movement[]" width=200 class="typeval"></select></td>
<td><input type="hidden" name="rest[]" value="Rest">Rest</td>
<td><label class="count"></label></td>
</tr>
<tr>
<td><input type="hidden" name="client_id[]" class="clientval" value="8"></td>
<td><input type="hidden" name="order[]" value="1A">1A</td>
<td><select name="movement[]" width=200 class="typeval"></select></td>
<td><input type="hidden" name="rest[]" value="Rest">Rest</td>
<td><label class="count"></label></td>
</tr>
Here is the movement_count.php
<?php
include('core/init.php');
protect_page();
$class_id = $_POST['class_id'];
if (isset($_POST['client_id'])){
$xmovement = x_move_performed($class_id, $_POST['client_id'], $_POST['movement']);
echo json_encode ($xmovement);
} // isset
?>
Here is the php function that queries the db and returns a number(COUNT)
function x_move_performed($class_id, $client_id, $movement){
$class_id = (int)$class_id;
$client_id = (int)$client_id;
$query = "SELECT COUNT(`movement`) FROM `completed_movements` WHERE `class_id` = $class_id AND `client_id` = $client_id AND `movement` = '$movement'";
$res = mysql_query($query);
$result = mysql_fetch_assoc($res);
return $result;
}
try to make the ajax synchronous: