Because my actual example is way too big I made a very short example:
test1.php
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <!--jQuery-->
<body>
<p> What is the first letter of the alphabet?</p>
<button type="button" id="button">Tell me!</button>
<div id="div"></div>
<script>
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
success: function() {
$('#div').html();
}
});
});
});
</script>
</body>
</html>
test2.php
<?php
echo "It's the letter A!";
?>
I want to this to print out "It's the letter A!" when I hit the button, which does not seem to work. Could somebody help end tell me why this doesn't work and how to fix it?
Thanks
3 Answers 3
1st : Should be enclosed by quotes $('#button')
2nd : Get the response in success function like this.
success: function(res) {
$('#div').html(res);
}
3rd : Set data type to text .
dataType:'text'
Update 1:
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
dataType:'text',
success: function(res) {
$('#div').html(res);
}
});
});
});
Comments
Its because you haven't output the result you got from ajax.
<script>
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: 'test2.php',
success: function(data) { //<---result from ajax
$('#div').html(data); //<----add result to div element
}
});
});
});
</script>
Comments
If your script is only a call of a page without GET/POST arguments, the simpliest way with jQuery is $.load() :
<script>
$(document).ready(function() {
$('#button').click(function() {
$.load("test2.php #div");
});
});
</script>
doc here : http://api.jquery.com/load/
$('#button'),