javascript - JQuery and AJax for multiple submiting buttons of the same class without refeshing the page?
This is my first post I am able to call PHP without refreshing the page. But I am having trouble finding a way to generalize this for multiple buttons.
HTML
<form action="#" class="t" method="POST" id="p1">
<label for="t1">text_1</label>
<input type="text" id="t1" name="t1" value="<?= $t1='' ?>" />
<input type="submit" class="button" id="b1" name="insert" value="submit">
</form>
<form action="#" class="t" method="POST" id="p2">
<label for="t2">text_2</label>
<input type="text" id="t2" name="t2" value="<?= $t2='' ?>" />
<input type="submit" class="button" id="b2" name="select" value="submit">
</form>
I can send the value from the first text input to PHP, but I cannot figure how to do this with multiple forms.
JavaScript
$(document).ready(function(){
$('body').on('submit', '#p1', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
type : 'POST',
url : 'answers.php',
data : formData,
success : function(data) {
alert(data);
$('#p').text(data);
}
});
});
});
PHP
$tab1 = (isset($_POST['tab1'])) ? $_POST['tab1'] : null;
$t1 = (isset($_POST['t1'])) ? $_POST['t1'] : null;
echo $tab1;
echo $t1;
Answer
Solution:
I added a code snippet. When submitted it will console.log the value of the desired inputs value
$(document).ready(function(){
$('body').on('submit', '.t', function(event) {
event.preventDefault();
var formData = $(this).serialize();
console.log(formData);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" class="t" method="POST" id="p1">
<label for="t1">text_1</label>
<input type="text" id="t1" name="t1" value="1" />
<input type="submit" class="button" id="b1" name="insert" value="submit">
</form>
<form action="#" class="t" method="POST" id="p1">
<label for="t2">text_2</label>
<input type="text" id="t2" name="t2" value="2" />
<input type="submit" class="button" id="b2" name="select" value="submit">
</form>
Source