I want to retrieve data from ajax call. I get data from a html select tag without any submit button that created by php code and then i want to pass them to an ajax call and use them in a php code at the same file.
I tried this code but no success:
<?php
if (isset($_POST['value'])) {
$selected_option = $_POST['value'];
echo $selected_option;
exit;
}
?>
<script>
$(document).ready(function() {
$('#percents').change(pass_the_value());
});
function pass_the_value() {
var selected = $('#percents').val();
$.ajax({
type: 'POST',
data: {
value: selected
},
success: function() {
alert(data);
},
error: function() {
alert('failure');
}
});
}
</script>
<div>
<select name='percents' id='percents' onchange='pass_the_value()'>
<option value="0.1" selected="selected">10%</option>
<?php
// A sample array
$products = array(
"0.2" => "20%",
"0.3" => "30%",
"0.4" => "40%",
"0.5" => "50%",
"0.6" => "60%",
"0.7" => "70%"
);
foreach ($products as $key => $item) {
echo "<option value='{$key}'>$item</option>";
}
?>
</select>
</div>
This is what i get in console log
(index):20 Uncaught ReferenceError: data is not defined
at Object.success
and this as php error:
Undefined index: value in C:xampp7htdocstestindex.php on line 3
2
Answers
You’re missing the URL you would like to call in
$.ajax
.Add this line to your AJAX call:
You need to specify a URL for the POST request. Look into the parameters here https://api.jquery.com/jquery.post/