hulkinBrain hulkinBrain - 3 months ago 6
PHP Question

How to submit one of the dynamically generated forms (generated by php)

PHP CODE

echo '
<div class = "card locations userNameContainer">
<div class = "row" style = "padding: 0 !important;">
<div class = "userName col s5" style = "display: inline-block;">
'.$name.'
</div>

<form class = "setPrivilegeForm col s6" id = "setPrivilegeForm">
<input type="hidden" value='.$userID.' name="userID" > </input>
<select name="userType" id = "userType" class = "customSelect" onchange = "ajaxPrivilegeSubmit()">
<option value="" disabled selected class = "grey-text">'.$typeText.'</option>
<option value="1">Administrator</option>
<option value="2" >Operator</option>
<option value="3">Patron</option>
</select>
</form>

<i class = "material-icons col s1">delete</i>
</div>
</div>

';




Preview image of generated list of forms:preview

Script:

function ajaxPrivilegeSubmit(){
$.ajax({
type: "post",
url: "setPrivilegeForm.php",
data: $('#setPrivilegeForm').serialize(),

success: function(data){

$(".userNameList").html();
Materialize.toast('Hello', 4000);

}
});

//$('this').closest('.setPrivilegeForm').submit();
}


I want to be able to submit the form (each list item is a form) when the value of the dropdown present in that form changes but, currently only the first form is being submitted instead of the form whose dropdown was selected (yes i know the reason why).

Could someone guide me so as how to use some unique identifier which would help in submitting that form whose
<select>
value has changed?

Answer

Give your form an id like 'setPrivilegeForm_1' and your select the id '1'. On the next one 'setPrivilegeForm_2' and '2' etc. Change your onchange function to ajaxPrivilegeSubmit(this.id) and change the actual function to

function ajaxPrivilegeSubmit(num){ $.ajax({ type: "post", url: "setPrivilegeForm.php", data: $('#setPrivilegeForm_'+num).serialize(),

  success: function(data){

    $(".userNameList").html();
    Materialize.toast('Hello', 4000);

  }

});

//$('this').closest('.setPrivilegeForm_'+num).submit(); }

Comments