Below is a user_id value that I obtained in the script
<script>
$.ajax({
dataType: "json",
url: "/index.php?ctl=user&act=userdetail",
async: true,
success: function(result) {
var user;
user = result.user
var user_id = user.id
}
})
</script>
I want to send this user_id value in the form below, but I could not find how to add it to the value part. Is there any other way to post this to that page or?
<div class="card shadow">
<ul>
<li class="pack">100 Points</li>
<li id="one" class="price bottom-bar">$79,99</li>
<li class="bottom-bar">100 Points</li>
<form action="test.php" method="post">
<input type="hidden" name="amount" value="$79,99">
<input type="hidden" name="package" value="100 Points">
//Here I want to send the user_id value.
<input type="submit" class="btn" value="Send">
</form>
</ul>
</div>
>Solution :
In the AJAX callback function you could dynamically generate and add a new hidden input element that takes the value from the ajax response, like this:
$.ajax({
dataType: "json",
url: "/index.php?ctl=user&act=userdetail",
async: true,
success: function(result) {
var user = result.user;
var user_id = user.id;
var input = document.createElement('input');
input.type='hidden';
input.value=user_id;
input.name='user_id';
document.querySelector('form').appendChild( input );
}
})
Or, add the hidden input manually and assign the value in the callback. Either way the form would have that field in the submitted data.
ie:
<div class="card shadow">
<ul>
<li class="pack">100 Points</li>
<li id="one" class="price bottom-bar">$79,99</li>
<li class="bottom-bar">100 Points</li>
<form action="test.php" method="post">
<input type="hidden" name="amount" value="$79,99">
<input type="hidden" name="package" value="100 Points">
<input type='hidden' name='user_id' disabled /><!-- input is here but disabled -->
<input type="submit" class="btn" value="Send">
</form>
</ul>
</div>
And then to target and populate the hidden input
$.ajax({
dataType: "json",
url: "/index.php?ctl=user&act=userdetail",
async: true,
success: function(result) {
var user = result.user;
var user_id = user.id;
var input = document.querySelector('form input[name="user_id"]')
input.disabled=false;
input.value=user_id;
}
})