Reputation: 637
I'm building a favorites tool where the users can create groups for their favorites. You add a favorite to a group via checkbox. That all works fine but one thing I would like add is when you create a new group, that new group appears in the existing list with an uncheck checkbox ready to go.
Using jQuery, what is the best method to return the last record the user added to the groups table as a callback from POST?
The JS:
$('.add_new_group').click(function(){
//var $add_new_group = $(this);
var user_id = $(document.body).attr('data-user-id');
var new_group = $('.new_group').val();
var data = {
'user_id' : user_id,
'new_group' : new_group
}
var url = "/wp-content/themes/testheme/action/new-group.php";
$.ajax({
type: "POST",
url: url,
data: data,
success: function(data) {
$('#new_group_container').html();
}
});
});
new-group.php
include('inc_db.php');
$user_id = $_POST['user_id'];
$new_group = $_POST['new_group'];
$check_records=mysql_query("SELECT user_id FROM tpl_groups WHERE user_id='$user_id' AND group_name='$new_group'");
$num_rows=mysql_num_rows($check_records);
if($num_rows < 1){
$query="INSERT INTO tpl_groups (user_id, group_name) VALUES ('$user_id', '$new_group')";
mysql_query($query) or DIE (mysql_error());
}
mysql_close();
Upvotes: 0
Views: 35
Reputation: 824
First, I'd be careful exposing your backend like that. You could redact anything that isn't critical to the question.
Is there a reason you're not just using the new_group value in the success method if that's the name of the group that's created with the script? Like so:
success: function(data) {
$('#yourtable').append('<tr><input type="checkbox">' + new_group + '</tr>');
}
If you'd like to get that data from the script, you can print data that can be used in the success function. For example,
<?php
echo $new_group;
?>
The former may be more straightforward, however.
Upvotes: 1