Martin
Martin

Reputation: 249

JQuery & advanced javascript

i am trying to get a value in input box automatically by clicking button "get name", from database. how can i implement it...?

my so far work is below...

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){


        var n = $("#div2").load("getTotal.html #p1").val();
                $("#div2").val(n);
    });
});
</script>
</head>
<body>

<input type="text" id="div2" value=""/>
<button>Get Name</button>

</body>
</html>

and getTotal.html page contents...

<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">John D. Feller</p>

in doing so.... i am getting an error "[object, Object]".

Help me out....with this error and advice me how can i take values from database.

Upvotes: 0

Views: 66

Answers (1)

JM Yang
JM Yang

Reputation: 1208

Issues in the code:

1) $("#div2").load(...) doesn't make much sense because it's telling jQuery to pull the content of the URL as HTML content of #div2. Here #div2 is an input which is not supposed to have HTML content. http://api.jquery.com/load/

2) You may want to load only the content of #p1 by using getTotal.html #p1, but this syntax won't work as you expected. jQuery can only pull the full content of getTotal.html, then you need to extract content of #p1 from it.

Assuming getTotal.html page is in same directory as your main page, the JS code can be modified to:

$(document).ready(function(){
    $("button").click(function(){
        $.get("getTotal.html", null, function(text) {
            $("#div2").val($(text).filter("#p1").html());
        });
    });
});

Upvotes: 1

Related Questions