Grey13 Grey13 - 4 months ago 8
Javascript Question

JS How to get value of embeded element after using ajax

Here is my problem.
I have external file include.html which i load with $.ajax and append to the body.
Content of include.html:

<p id="descriptionText">My description</p>


I want to get value of p#descriptionText after ajax completed, but as the result i see "undefined"

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "include.html",
dataType: "html",
}).done(function (response) {
$('body').html(response);
});

console.log($('#descriptionText').val());
});
</script>
</head>
<body>

</body>
</html>


Result are the same even if i try to use closure. Example below.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script>
function func() {
$.ajax({
url: "include.html",
dataType: "html",
}).done(function (response) {
$('body').html(response);
});

return function() {
console.log($('#descriptionText').val());
}
}

func()();
</script>
</head>
<body>

</body>
</html>


If i use
async: false
parameter in
$.ajax
it works, but i need asynchronous exactly. What is my problem? Thank you!

Answer

In a nutshell: Move console.log($('#descriptionText').val()); into the .done() callback of the $.ajax()

like:

.done(function (response) {
    $('body').html(response);
    console.log($('#descriptionText').val());
});

Explanation:

.done() is the success callback when the promise is resolved. A promise in the async land means that the code will be executed at a point later than the current tick of clock. Your console.log is executed at this moment and so will always be undefined since, the promise hasn't been resolved yet.

So, soln is to take care that your console.log is executed after the promise has been resolved. Do this in many possible ways, one simple being like I mentioned earlier: Moving the statement inside the .done() after you have performed the .html() DOM Manipulation.