I want to get the value of data-id in my tag and transfer it to a PHP variable.
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
I already got the value of data-id using the javascript below and placed it into a variable, however its not posting on the page.
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid});
});
I tried doing this...
print_r($_POST);
but the array being displayed is empty What am I doing wrong here? Kinda new at this.
-
$.post() is sending that post data to another page. Are you trying to print the post array on this same page? Or are you trying to print it out on the page that the post data was sent to by javascript?TheOneWhoSighs– TheOneWhoSighs2014年09月18日 01:22:21 +00:00Commented Sep 18, 2014 at 1:22
-
seems no prob on Js, wheres the PHP? same page?Kevin– Kevin2014年09月18日 01:22:24 +00:00Commented Sep 18, 2014 at 1:22
-
You are passing the value adminid to post as admin_to_pass on the PHP side. So to print it do (echo $_POST['admin_to_pass'];)Tasos– Tasos2014年09月18日 01:25:16 +00:00Commented Sep 18, 2014 at 1:25
-
Im trying to print the post array on this same page. But it doesn't seem to be working.Nomad– Nomad2014年09月18日 01:25:45 +00:00Commented Sep 18, 2014 at 1:25
-
Posting a value via AJAX won't magically update the page you're already on. If you want to alter the current document after the POST is successful, add a callback function to do so.Phil– Phil2014年09月18日 01:26:57 +00:00Commented Sep 18, 2014 at 1:26
1 Answer 1
If you're trying to post on the same page (which is a bad idea anyway), you should have always have an exit/die;
on that PHP catch block, and a success function callback on the $.post
.
Example:
Simulated JS:
<?php $adminid = 1; ?>
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid}, function(response){
console.log(response);
});
});
</script>
Here on the PHP (same page):
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
}
Or
if(isset($_POST['admin_to_pass'])) {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
// you must have this or you'll catch the whole document
}
And since in your current code you don't have one, you need the success callback function to process the response which came from the server:
$.post("index.php", {admin_to_pass: adminid}, function(response){
^^^^
console.log(response); // your response from the server is inside (you can name it any name you want)
});
4 Comments
console.log
output. I get the feeling OP is very new to this