I have a form and a drop down menu. The drop down menu lists items (1, 2, 3). When you select any of the items, the content gets loaded via ajax. Item 1 (default) is automatically loaded on $(document).ready().
What I am trying to do is to save the values of the form when user changes from an item to an item. For example, item 1 has a description. After user edits the description and changes to item 2, the description of item 1 should be saved to a database. When the user finishes editing item to and goes back to 1, description of item 2 is saved, and description from item 1 is loaded.
The problem I am facing right now is that I am trying to use $("#myForm").serialize();
to get form values and pass them into save.php page, but since the input is loaded via ajax call, using
$(document).ready(function(){
draw_item_meta();
var vals = $("#myForm").serialize();
}
doesnt yield anything while
$("#select_item").on("change", function(){
save_item_meta(vals);
draw_item_meta();
});
selects target selected item and adds description from previous item. So if I edit description of item 1 and change to 2, description of item 1 will be saved as description of item 2.
Here's some of the code:
<script>
$(document).ready(function(){
draw_item_meta();
var vals = $("#myForm").serialize();
$("#select_item").on("change", function(){
save_item_meta(vals);
draw_item_meta();
});
});
function save_item_meta(vals) {
console.log(vals);
$.ajax({
url: "save.php",
method: "POST",
data: vals,
success: function(data) {
}
});
return false; // prevent from submit
}
function draw_item_meta() {
var ID = $("#select_item").val();
$.ajax({
url:"select_item_meta.php",
type:"POST",
data: {"ITEMID":ID, "RID":' . $_GET["ID"] . ',},
success: function(data) {
$("#lost_meta_box").replaceWith(data)
}
});
};
</script>
Form is pretty big, so I'll just paste the part I am trying to modify
<form class="form-horizontal" action="save.php" method="POST" id="myForm">
<textarea class="form-control" aria-label="With textarea" name="Desc">' . $r["Desc"] . '</textarea> <!-- $r["Desc"] pulled from db -->
</form>
P.S. I removed some php part from the code. Things like data: {"ITEMID":ID, "RID":' . $_GET["ID"] . ',}
work. My issue is with JS, not PHP or HTML.
Thank you
Edit:
I found a temporary solution of serializing data every n seconds via
var vals = null;
setInterval(function(){
vals = $("#myForm").serialize();
}, 1000); // 1000 = 1 sec
If anyone has a better solution please let me know.