php - Implement Ajax to load HTML depending on radio button value
Hello I am really new to AJAX PHP and JQuery so any suggestion is really apprecciated.
I have an HTML page with a form, in this form I have 3 radio buttons with 3 values. My objective is to print some HTML depeding on this values.
For example if I select the radio button 2 (value=2) so -->
echo <input type="text">
echo <input type="text">
I managed to print the value in a empty div under the buttons but I don't know how to generate code with the $_POST variable (I tried to iclude the action page but it didn't work)
HTML:
<div class="hide">
<input type="radio" name="cat_2" value="1">One
<input type="radio" name="cat_2" value="2">Two
<input type="radio" name="cat_2" value="3">Three
</div>
<div id="response"></div>
<?php include 'gen.php'; ?> //my failed test
JQuery:
<script>
$(document).ready(function () {
$('.hide input[type="radio"]').click(function(){
var value= $(this).val();
$.ajax({
url: "ajax_page.php",
type: 'post',
data: {ajax: 1, value: value},
success: function (response) {
$('#response').text(value);
}
});
});
});
</script>
ajax_page.php just to test the value:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['value'];
} else {
echo "Nothing to Show";
}
?>
I don't know if I was enough clear, any idea would be really helpful I don't even know what to search for :)
Answer
Solution:
gen.php
is run before the webpage is sent to the browser. You won't be able to access any return variables or information from the ajax call because thegen.php
code will already have run.gen.php
will need to have all the information BEFORE it runs/the browser loads the page. If you need code to run AFTER the browser loads the page, you'll have to do that on yourajax_page.php
.Just a hint for your ajax_page. You should avoid using the supervariables directly and filter the input first (to prevent malicious or accidental problems). Something like this:
You should capture the error from the ajax call as well and log it to the console (or present it to the user). Here is how you can log it to the console.