Jason Boyce Jason Boyce - 7 months ago 12
HTML Question

Ajax not seeing textarea value

I have a textarea input on my page that I want to post to the server using AJAX. The AJAX call is good, however, it will not see the value that's inside the textarea.

My HTML:

<div class="promptBody">
<div id="promptText" onclick="replaceWithInput(this)">
<p class="promptBody"><div id="prompty">{{prompt.prompt|linebreaks}}</div></p>
</div>
<form id="promptUpdateForm">
<div id="promptInput">
<p><textarea class="input" cols="40" id="id_prompt" name="prompt" placeholder="Prompt" rows="10"></textarea></p>
<p><input class="submit" type="submit" name="submit" id="submit" value="Edit Prompt" /></p>
</div>
</form>
</div>

<script type="text/javascript">
$(document).ready(function() {
$(document).on('submit', '#promptUpdateForm', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/apps/litprompt/a/{{prompt.id}}/update/',
data: {
'prompt': $('#id_prompt').val(),
csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val(),
},
success: function(json) {
$('#promptText').html(json.prompt_data);
var promptText = document.getElementById('promptText');
var promptInput = document.getElementById('promptInput');
promptText.style.display = 'block';
promptInput.style.display = 'none';
}
});
});
});
</script>


If I change my ajax code in data to 'prompt': 'blah', it works just fine. But every time I post with 'prompt': $('#id_prompt').val(), it is a null value.

Answer

The textarea HTML element is not self-closing. It has to be closed by </textarea>.

See as follows:

<div class="promptBody">
    <div id="promptText" onclick="replaceWithInput(this)">
        <p class="promptBody"><div id="prompty">{{prompt.prompt|linebreaks}}</div></p>
    </div>
    <form id="promptUpdateForm">
        <div id="promptInput">
            <p><textarea class="input" cols="40" id="id_prompt" name="prompt" placeholder="Prompt" rows="10"></textarea></p>
            <p><input class="submit" type="submit" name="submit" id="submit" value="Edit Prompt" /></p>
        </div>
    </form>
</div>