I have a form where users enter some text manually. Then I’d like to let the users choose a tag from a database through AJAX, not unlike how tag suggestions appear in the SO question form. While the div where the ajax call places the tag is inside the form, it does not seem to register and the tag is not picked up by the form. Am I missing something in my code, is this impossible or, if impossible there a better way to do this? Thanks for any suggestions.
Here is code:
html
<form method="post" action="enterdata.php">
<input type="text" name="text">Enter text here.
<div id="inserttags"></div><a href="javascript:void(0);" onclick="getTags()";>Get tags</a>
<form type="button" name="submit" value="Enter Text and Tag">
</form>
javascript
getTags() {
various Ajax goes here, then
//following line inserts value into div of html
document.getElementById("inserttags").innerHTML=xmlhttp.responseText;
// a bit more ajax, then following pulls tag from db
xmlhttp.open("GET","findtags.php",true);
xmlhttp.send();
} //end function
php
//gettags.php
//first pull tag from db. Then:
echo 'input type="text" name="tag" value= "html">Enter tag';
//above output gets inserted in div and is visible on page.
Though the above output is visible on page, the form does not seem to pick it up when you click “Enter Text and Tag” to submit the form.
After more research and much pondering, I don’t think you can do what I wanted to do…use the native html form to capture the javascript output even with the div inside the form. Instead, the way to do this is to capture the text field using javascript and then place it inside a form within the ajax outputted to the browser as a hidden value along with the tags. Then the user submits the form with both the text and tag, not using the original html but rather a button or link in the ajax output. If anyone knows a better way, I stand corrected, but this way will work, and the html form does not seem to recognize the values in the div inserted by javascript.