Trying to refresh a div on a form submit to display the newly added array values without the page refreshing.
in Using jQuery
•
7 years ago
I have a form to create a new item in the db, it does this through ajax. I also have an array on the page displaying all the current items. When I add a new item using ajax i want the items array to update and display the new item.
I'm using ruby on rails with the gon gem to make the js array so the js array isn't getting the values from the db its getting them from the rails array which is getting it from the db. If I update the js array on form submit it will still grab it from the rails array that hasn't been updated.
I figured to just have the submitted string value added to the array after it's saved to the db. And then have the array updated on the page without the page re loading.
My main problem is how to grab the submitted string value adding it to the array and once it is added to the array, updating the array items displayed on the page to show the newly added item.
here is the ajax coding
- $('#new_category_item_key').submit(function(event) {
- if ($(this).find('.required[value=""]').length == 0) {
- alert('Please submit a name!');
- event.preventDefault();
- } else {
- $.ajax({
- type: 'POST',
- url: $('#new_category_item_key').attr('action'),
- data: string
- }).success(function(json) {
- key_name.push( ?? ); // what value do use to add the submitted value to the array
- $("#keys_list").load(location.href + " #keys_list"); //not sure if this will work haven't got the coding to get this far yet
- alert('New key added');
- });
- }
- });
- });
here is how the
array is being displayed on the page
- <div id="keys_list">
- <script>
- for (i=0;i<key_name.length;i++)
- {
- document.write(key_name[i] + " | ");
- }
- end
- </script>
- </div>
I'm still
learning jquery and ajax so this is my best attempt at it.
Basically the coding always gets to the first if statement to
check if the value submitted was empty of not and then stops
with the 'Please submit a name' alert.
Appreciate the
help on this.
1