Reputation: 21406
I have a form like below;
<form>
<table>
<tr><td><input class="asdf" type="text" name="qwerty" value=""/></td></tr>
<tr><td><input class="items" type="text" name="item" value=""/></td></tr>
<tr><td><input class="items" type="text" name="item" value=""/></td></tr>
<tr><td><input class="items" type="text" name="item" value=""/></td></tr>
<tr><td><input class="items" type="text" name="item" value=""/></td></tr>
<tr><td><button id="mybutton">clickme</button></td></tr>
</table>
</form>
I have some fields with similar name. I want to pass these into my ajax handler in a single instance. Also according to the ajax reply, the corresponding input field's value may be changed to either true or false.
$('#mybutton').click(function(){
var myitem = $('.items').val();
$.ajax({
type: 'POST',
url: 'ajaxhandler.php',
data: 'qwerty='+$('.asdf').val()+'&item='+myitem,
cache: false,
success: function(result) {
if(result == "true"){
//change each correspinding input field to true
}else{
//change each correspinding input field to false
}
}
});
});
Also I am little confused how to do the ajax reply. How can I achieve this? Below is an image showing the form before and after ajax (what I am trying to achieve);
The input form fields (items) are generated dynamically. Sometimes there may be 1, sometimes 5 or 10. So it is not possible to give them separate names (like item1, item2 etc) and a common class, and catch them inside php like $_POST['item1']
, $_POST['item2']
etc. I want to know how to set the JavaScript as well as the ajax PHP.
Upvotes: 1
Views: 3616
Reputation: 20418
Try with this
<form>
<table>
<tr><td><input class="asdf" type="text" name="qwerty" value="0"/></td></tr>
<tr><td><input class="items" type="text" name="item[]" value="1"/></td></tr>
<tr><td><input class="items" type="text" name="item[]" value="2"/></td></tr>
<tr><td><input class="items" type="text" name="item[]" value="3"/></td></tr>
<tr><td><input class="items" type="text" name="item[]" value="4"/></td></tr>
<tr><td><button id="mybutton">clickme</button></td></tr>
</table>
</form>
Script
$('form').serialize()
In your code
$('#mybutton').click(function(){
var mydata = $('form').serialize()
// it will return like this qwerty=0&item%5B%5D=1&item%5B%5D=2&item%5B%5D=3&item%5B%5D=4
$.ajax({
type: 'POST',
url: 'ajaxhandler.php',
data: mydata,
cache: false,
success: function(result) {
if(result == "true"){
//change each correspinding input field to true
}else{
//change each correspinding input field to false
}
}
});
});
Upvotes: 4