Reputation: 446
I'm trying to set a confirmation box to delete a message using javascript/jquery on a php page. The variables are being set correctly in the javascript function, but now I can't get the function to properly post to the page.
I have the following included in the head
<script src="http://code.jquery.com/jquery-latest.js"></script>
Now for the code.
//displays a list of messages w/ button to delete
if(mysql_real_escape_string($_GET['msg'] == "msgDetail")){
$msg->messageDetail($msgID);
$action = "delete";
$msgID = mysql_real_escape_string($_GET['msgID']);
//display a delete button that sends variables to javascript function
echo '<td>'.'<input type="button" value="Delete Message" name = "deleteMessage" onclick="deleteMessage(\'' . $msgID .'\', \'' .$action. '\',\'' .$userid. '\')" />'.'</td>';
}
?>
//javascript function for confirmation to delete message
<script type="text/javascript">
function deleteMessage(msgID, action, userid){
//document.write(msgID + action + userid) values are correctly showing up here when uncommented
if (!confirm("Are you sure?"))
return false;
$.post('messages.php',"msgID=" + msgID + "&action=" + action + "&user=" + userid, function(response) {
//window.location.reload()
});
}
</script>
<?
//check to see if the values have been posted
if($_POST['action']) == "delete"){
echo "success!";
....more code
}
As you can see, I'm trying to post the variables to messages.php but when I check if even one is posted, nothing happens.
Upvotes: 0
Views: 352
Reputation: 18078
Looking at just the javascript, deleteMessage()
could be written as follows to avoid messy string handling and to give you better feedback while debugging :
function deleteMessage(msgID, userid) {
if (!confirm("Are you sure?")) { return false; }
var data = {
'action': 'delete',
'msgID': msgID,
'user': userid
};
$.ajax({
url:'messages.php',
data: data,
type: 'POST',
success: function(response) {
alert(response);//debug message
//window.location.reload()
},
error: function((jqXHR, textStatus, errorThrown) {
alert((typeof errorThrown == 'string') ? errorThrown : textStatus);//debug message
}
});
}
You may choose to switch back to $.post()
when everything is debugged.
You'll see that 'action': 'delete'
is hard coded. It's a minor point but there's no point passing 'delete' through to deleteMessage
because a function so named isn't going to do anything else. A corresponding change needs to be made where the <td><input...onclick="..."/></td>
HTML is built.
Upvotes: 1