0

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
  • 1
    should be enclosed by quotes $('#button') , Commented Aug 22, 2017 at 9:07
  • 1
    Because you did nothing with the response..... have a look at the documentation for $.ajax Commented Aug 22, 2017 at 9:08
  • You are right! Fixed it, still doesn't work lol. Commented Aug 22, 2017 at 9:10

3 Answers 3

1

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);

            }
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.