Reputation: 1533
I have a form that loads in a popup div layer. I also have a saveForm()
function that makes an AJAX post request.
How can I take the value from the two input fields into that saveForm()
function?
Name: <input type="text" id="description" name="description" value=""><br><br>
Description: <input type="text" id="description" name="description" value=""><br><br>
<button type="button" onclick="saveForm()">Save</button>
function saveForm() {
$.post("save.php", {
user_id: '1234'
}, function(data, status) {
alert(data);
});
}
Upvotes: 2
Views: 293
Reputation: 740
you can send post with data like this example,
<script type="text/javascript">
var form = $("#your-form-id");
var data = $(form).serialize();
$.ajax({
url: "your-url/save.php",
data: data,
method: 'POST',
success: function (response) {
//your js after success post
}
});
</script>
Upvotes: 0
Reputation: 337560
Give the two fields separate id
attributes then get their values and set them as properties of the object you provide as the body of the request to send in the AJAX request.
It's also worth noting that you should avoid using on*
attributes in your HTML where possible. It's better practice to use unobtrusive event handlers. As you've already included jQuery in the page, that can be done using on()
, like this:
Name: <input type="text" id="name" name="name" value=""><br><br>
Description: <input type="text" id="description" name="description" value=""><br><br>
<button type="button" id="save">Save</button>
jQuery(function($) {
$('#save').on('click', function() {
$.post("save.php", {
user_id: '1234',
name: $('#name').val(),
description: $('#description').val(),
}, function(data, status) {
console.log(data);
});
});
}
Better still would be to put the elements in a form
and change the button
to type="submit"
. Then you can hook to the submit
event of the form. This is in order to improve accessibility and the user experience.
Upvotes: 1