Returned data doesn't work in jQuery using Ajax

I have developed a code with Ajax and jQuery. I have a response from my.php and I have tried to extract the response values. Here's the code (HTML):

My.php

?php
    echo '<div id="title">My Title </div>';
    echo '<div id="message"> My message </div>';
?>

      

I am trying to extract the title and post so my code is below.

    <head>
        <script type="text/javascript" src="js/jquery-1.2.6.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert("OK");

                $.ajax({
                    type:"POST",
                    url: "my.php",
                    cache:false ,
                    success: function(data){
                        $("#response").html(data);
                        var $response = $(data);
                        var oneval = $response.find('#title').text();
                        var subval = $response.find('#message').text();
                        alert(oneval);
                    }
                });
            });
        </script>
    </head>

    <body>
        <div id="response">
        </div>
    </body>
</html>

      

...

The problem is when I tried to alert, it doesn't work. What's wrong with this logic? Should I use a different function to retrieve the header and message?

0


source to share


3 answers


OK, go to http://jsbin.com/udige/ and you can see how it works.

The key is using .filter

instead of .find as the two divs are the root elements in the response. My mistake.



Basically do the following:

success: function(data){
    $("#response").html(data);
    var $response = $(data);
    var oneval = $response.filter('#title').text();
    var subval = $response.filter('#message').text();
    alert(oneval);
}

      

+1


source


If the answer comes back when you wrote it, then the code I gave you will work.



You really need to learn how to use a debugger ( Firebug ) and put breakpoints in your code so that you can use the console to check selectors and look at variable values ​​etc. Also you should really have answered the original question and the answer I gave and not open up a completely new question, especially since you don't even cross-reference your original.

0


source


Try using this instead:

var oneval = $("#response #title").text();
var subval = $("#response #message").text();

      

-1


source







All Articles