Adrian Gheorghe Adrian Gheorghe - 6 months ago 8
Ajax Question

Ajax works only on first id submitted (with php from db)

I'm developing an editor for navigation bar , to can reorder them , edit them and things like this. I made the part of sortable in ajax , but I got stuck at the submit function .

I want to change the name-viewed immediatly when i press the save button , and it works! , but only for my first placed navbar .
At the second and third (in this example) , ajax won't work only If i replace them into the position one .
maybe I can get some help from you guys , thanks in advance

Down here I will provide you my relevant codes for this part , and a screenshot
at the end

ajax code

$('.nav-form').submit(function(event){

var navData = $(this).serializeArray();
var navLabel = $('input[name=label]').val();
var navID = $('input[name=id]').val();

$.ajax({

url: "ajax/nav-form.php",
type: "POST",
data: navData

}).done(function(){

$("#label_"+navID).html(navLabel);

});


calling the alert method for navLabel and navID , i observed that they call only the first positioned item (even if i'm trying to edit the second or third navbar) , doesn't matter which one is it , if it's first placed

alert(navLabel);
alert(navID);





event.preventDefault();

});



}); // END document.ready();


the relevant php/html codes

<ul id="sort-nav" class="list-group">

<?php

$q = "SELECT * FROM navigation ORDER BY position ASC";
$r = mysqli_query($dbc, $q);

while ($list = mysqli_fetch_assoc($r)) { ?>

<li id="list_<?php echo $list['id']; ?>" class="list-group-item">


Form here i call the id in ajax

<a id="label_<?php echo $list['id']; ?>">
<?php echo $list['label']; ?>
</a>





<button class="btn btn-success pull-right" data-toggle="collapse" data-target="#form_<?php echo $list['id']; ?>"><i class="fa fa-chevron-down"></i></button>

<div id="form_<?php echo $list['id']; ?>" class="collapse">


<form class="form-horizontal nav-form" action="index.php?page=navigation&id=<?php echo $list['id']; ?>" method="post" role="form">



this part of code I've erased because it's irelevant

<button type="submit" class="btn btn-default">Save</button>
<input type="hidden" name="submitted" value="1">

<input type="hidden" name="openedid" value="<?php echo $list['id']; ?>">

</form>
</div>

</li>
<?php } ?>


enter image description here
hope I dind't gave you headaches with my bad english

Answer

Delegate the submit event so event listener isn't lost when the element gets moved

$(document).on('submit','.nav-form',function(event){
     // your same existing code
Comments