I've been trying to pass value to php variable from javascript. I'm able to pass the data when the url from another php file, but I fail to get the data to be passed on the same page.
Here is the javascript code :
<script>
$(document).ready(function(){
$(document).on('click', '#getUser', function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
$.ajax({
url: 'user.php',
type: 'POST',
data: 'id='+uid,
success: function(data) {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
}
})
});
});
</script>
Since you are using POST
type in your ajax
.So
data: 'id='+uid,
need to be
data: {"id":uid}, //or you can do data: {id:uid},
And on your user.php page:-
<?php
echo $_POST['id'];//check what it outputs in your console
You should pass JSON
to your server, example:
instead of
data: 'id='+uid
use
data: {"id":uid}
Here is pseudo code to help you understand how can you pass parameters in an AJAX request:
var paramsToSend = {};
paramsToSend['data1'] = 'data1';
paramsToSend['data2'] = 'data2';
$.ajax({
...
data: {params:JSON.stringify(paramsToSend)},
...
});
In your users.php you can:
$parameters = json_decode($_POST['params']
To convert them to array and have that array in $_POST, you can:
$_POST = (array) $parameters;