dios231 dios231 - 2 months ago 8
Ajax Question

How to select all input fields that sits in a table

I have a form that "sits" inside a table

<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-content">
<form id="form">
<input type="submit" value="send" class="btn btn-w-m btn-primary" style="float: left;">Add transaction</input>
<table class="table table-striped table-bordered table-hover " id="editable" >
<thead>
<tr>
<th>Date</th>
<th>Name<br>(Last name, Firstname,<br>
or Business name)
</th>
<th>Address</th>
<th>Phone</th>
<th>Price with VAT</th>
<th>VAT</th>
<th>Transaction type</th>
<th>Currency</th>
<th>Installments</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" name="date"/></td>
<td><input type="text" name="name"/></td>
<td><input type="text" name="address"/></td>
<td><input type="text" name="phone"/></td>
<td><input type="text" name="price_with_vat"/></td>
<td id="vat">25%</td>
<td class="exclude"><select>
<option value="value1">Value from database</option>
<option value="value2">Value from database</option>
<option value="value3">Value from database</option>
</select></td>
<td class="exclude"><select>
<option value="value11">Yes</option>
<option value="value23">No</option>
</select></td>
<td class="exclude"><select>
<option value="value21">Euro</option>
<option value="value22">USD</option>
<option value="value23">Pound</option>
</select></td>
</select></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</div>


What I want is to select all input values and send an Ajax request to a php end. The problem is that in my jquery function (code following) i cannot gather all the inputs. Also altough i have a
preventDefault
page still get refreshed.

var request;
$('#form').submit(function(event){

if (request){
request.abort();
}

var form = $(this)

var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
console.log(serializedData);
event.preventDefault();
});

Answer

Try this code

For a form element's value to be included in the serialized string, the element must have a name attribute.

$(document).ready(function() {
  //Form submit event
  $('#form').on('submit', function(e){

    // validation code here
    if(!valid) {
      e.preventDefault();
    }

    //Serialized data 
    var datastring = $("#form").serialize();

    //Ajax request to send data to server
    $.ajax({
        type: "POST",
        url: "your url.php",
        data: datastring,
        success: function(data) {
            alert('Data send');
        }
    });
  });
});