I want to create an ajax post request that gets the value of the radio button then use it in a PHP conditional statement.
So far i have tried this code (all code is from one php file):
$(document).ready(function () {
$('.radio-buttons input[type="radio"]').click(function(){
var subject= $(this).val();
$.ajax({
url: 'home.php',
type: 'POST',
data: {
'subject': subject
},
success: function(response) {
alert(response);
}
});
});
});
<form id="form1" method="POST" class="radio-buttons ">
<input class="radio-filter" type="radio" name="subject" value="A">A</input>
<input class="radio-filter" type="radio" name="subject" value="B">B</input>
</form>
if (isset($_POST['subject'])) {
echo "Showing!";
}
the alert message shows the value of the radio button when I clicked them but the echo in PHP condition is not showing.
My Answer:
The issue here is that the AJAX request is sending the data to the same page (home.php) but the PHP conditional statement is checking for the data in the same page where the form is located.
To fix this issue, you can separate the PHP code into a different file (e.g. process.php) and then modify the AJAX request to send the data to that file. Here's how you can do it:
1. Create a new PHP file called process.php and move the PHP conditional statement code to that file:
process.php:
php
if (isset($_POST['subject'])) {
echo "Showing!";
}
2. Modify the AJAX request to send the data to process.php:
javascript
$(document).ready(function () {
$('.radio-buttons input[type="radio"]').click(function(){
var subject= $(this).val();
$.ajax({
url: 'process.php',
type: 'POST',
data: {
'subject': subject
},
success: function(response) {
alert(response);
}
});
});
});
3. Update the form action attribute to point to the process.php file:
html
Now, when you click on the radio buttons, the AJAX request will send the data to process.php where the PHP conditional statement will check for the data and echo "Showing!" if the data is set.
Rate this post
5 of 5 based on 9013 votesComments