Question

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

My.php

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

I try to extract the title and message 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 is not working. What is wrong with this logic? Should I use another function to extract the title and message?

Was it helpful?

Solution

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

The key is using .filter, not .find as the two divs are 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);
}

OTHER TIPS

If the response is coming back as you wrote it then the code which I gave you will work.

You really need to learn how to use a debugger (Firebug) and put breakpoints into your code so you can use the console to test selectors and look at the values of variables, etc. Also you should really have responded to the original question and answer that I gave rather than opening a whole new question especially since you have not even cross referenced your original.

Try using this instead:

var oneval = $("#response #title").text();
var subval = $("#response #message").text();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top