Reputation: 2649
Using ajax, I'm trying to display what is being selected, but it's not displaying anything at all for some reason. I know the ajax function itself got called, by using alert inside the function, and I think the real problem is actually in test2.php, but I'm not sure what I did wrong. Please take a look:
test1.php
<?php
include('ajax.php');
echo "<select name = 'select' onchange = 'ajax(\"test2.php\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "<option value = '3'> 3 </option>";
echo "</select>";
echo "<div id = 'output'/>";
?>
test2
<?php
$select = $_POST['select'];
echo $select;
?>
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,id) {
$.ajax({
type: "POST",
url: url,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
Upvotes: 0
Views: 1228
Reputation: 1
You are missing data attribute in Ajax request.
Its a bad practice to mix php scripts and html together. Always think about separation of concern.
Here is how you should do it.
<?php
include('ajax.php');
?>
<select name = 'select'>"
<option value = '1'> 1 </option>
<option value = '2'> 2 </option>
<option value = '3'> 3 </option>
</select>
<div id = 'output'/>
Ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
$(function () {
$(document).on('change','select',function () {
var data = $(this).val();
$.ajax({
type: "POST",
url: "test2.php",
data: data,
error: function(xhr,status,error){alert(error);},
success:function(response) {
$("#output").html(response);
}
});
});
});
</script>
Upvotes: 0
Reputation: 13918
you have not post data to test2
!!
<?php
include('ajax.php');
echo "<select id = 'select' onchange = 'ajax(\"test2.php\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "<option value = '3'> 3 </option>";
echo "</select>";
echo "<div id = 'output'/>";
?>
function ajax(url,id) {
$.ajax({
type: "POST",
url: url,
data : {select:$('#select').find("option:selected").val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
Upvotes: 1