Yağız Muğulkoç Yağız Muğulkoç - 5 months ago 19
Javascript Question

Post form data onclick event of button using ajax in foreach loop

I hava a PHP MVC project. I read data from database and create a form for each record. I want to make update when pressed the button which it is in the form. But I confused how I can access form elements in javascript function. I used an index for each record but I could not overcome how I can find it in javascript.

My php file:

$index = 1;
foreach ($categories as $category) {
?>
<div class="row">
<form id="updateForm">
<div style="visibility: hidden">
<input type="text" name="editId<?php echo "$index"?>" id="editId<?php echo "$index"?>" value="<?php echo $category['id']; ?>">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control" name="editTitle<?php echo "$index"?>" id="editTitle<?php echo "$index"?>"
value="<?php echo $category['title']; ?>">
</div>
<div class="form-group col-md-4">
<select class="form-control" name="editline<?php echo "$index"?>" id="editline<?php echo "$index"?>">
<option disabled selected value="">Sıra</option>
<?php
for ($i = 1; $i <= $rows; $i++) {
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-1">
<a class="btn btn-success" id="btnUpdateSubmit" name="btnUpdateSubmit" href="<?php echo BASE_URL; ?>/category"
onclick="updatecategory();"><i class="fa fa-check"></i> Kaydet</a>
</div>
<div class="form-group col-md-1">
<a class="btn btn-danger" href="#"><i class="icon-trash icon-large"></i> Sil</a>
</div>
</form>
</div>
<?php
$index++;


And my javascript function:

function updatecategory() {
if (window.XMLHttpRequest){
xmlhtpp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhtpp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("existCategories").innerHTML = xmlhtpp.responseText;
}
};
xmlhtpp.open("POST", '<?php echo BASE_URL ?>/category');
}

Answer
  1. remove the ID from the form - IDs must be unique.

  2. Change the links to submit buttons

  3. add an event hander:


window.onload=function() {
  var forms = document.getElementsByTagName("form");
  for (var i=0;i<forms.length;i++) {
    forms[i].onsubmit=function() {
       updateCategory(this);
       return false; // cancel submit
    }
  }
}

then have

function updatecategory(theForm) {
  var categoy = theForm.elements[0].value; // editIdxxx
Comments