VIVA LA NWO
VIVA LA NWO

Reputation: 3912

AJAX with jQuery not returning data

This is my Javascript:

$(document).ready(function() {
    $('#like').bind('keydown', function(e) {
        if(e.keyCode == 13) {
            var likeMsg = $('#like').val();
            if(likeMsg) {
                // Send the AJAX request to like.php
                $.ajax({
                    url: 'like.php',
                    success: function(data) {
                        alert('Content: ' + data);
                    }
                });
            }
        }
    });
});

And this is my like.php file:

<?php

echo "It works! :)";

?>

When I press enter on the #like input, it seems the AJAX request is sent and an alert box comes up saying: Content:, but there's no data being sent back from like.php...

I have checked if the file exists and if it's in the same directory and whatever and it is, so I'm pretty much clueless atm.

Does anyone know what could be wrong here? Cheers.

Upvotes: 0

Views: 473

Answers (4)

VIVA LA NWO
VIVA LA NWO

Reputation: 3912

Figured it out guys. In my markup I had:

<form action="">
    <p><input type="text" id="like" class="like" /></p>
</form>

So the page was refreshing when I was pressing enter in the text box which is what I look for in my Javascript code. I removed the <form> elements and all works now.

Silly mistake, should of noticed it sooner. Thanks :)

Upvotes: 0

Alex Cook
Alex Cook

Reputation: 171

Actually, looks like all you want is to pipe the out put of a file somewhere. Check out $.load or $.get, both are more inline with what you are looking for I think.

Upvotes: 0

Jonathon Faust
Jonathon Faust

Reputation: 12545

See the docs:

http://api.jquery.com/jQuery.ajax/

If no dataType is provided, it tries to choose among: "xml, json, script, or html".

Try adding dataType with the value "text":

$.ajax({
        url: 'like.php',
        dataType: 'text',
        success: function(data) {
        alert('Content: ' + data);
      })

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382616

Everything seems to be fine but debugging the ajax request might lead to a better position.

Upvotes: 1

Related Questions