Post serialized form data with ajax

I have this form

  <div class="tab-pane" id="trade">
  <br/>
  <div class="well">There are currently a total of <b>$traders traders</b> and this session has a total of <b>Ksh $total</b> you can earn this very minute.</div>
   <form class="form-horizontal" name="trade">
   <br/>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Telephone Number:</label>
      <div class="col-sm-10">
        <input type="text" class="form-control" id="email" placeholder="Enter Telephone Number" name="telephone"  required/>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Id Number:</label>
      <div class="col-sm-10">
        <input type="number" class="form-control" id="email" placeholder="Enter Id Number" name="nid"  required/>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Amount:</label>
      <div class="col-sm-10">
        <input type="number" class="form-control" id="email" placeholder="Enter Amount" name="amount"  required/>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="email">Direction:</label>
      <div class="col-sm-10">
       <select class="form-control" name="direction"><option value="up">Up</option><option value="down">Down</option></select>
      </div>
    </div>
    <div class="form-group">        
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-success pull-right">Submit</button>
      </div>
    </div>
  </form>
  </div>

I have this as my jquery

 $(document).ready(function(){

  var datastring = $("#trade").serialize();
   $.ajax({
    type: "POST",
    url: "http://localhost/lords/trade.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
       alert(data);
    },
    error: function() {

    }
    });

   });

However, i am not stopping default and the form reloads and no data is posted.

I have tried this

var frm = $('#trade');
    frm.submit(function (ev) {
        $.ajax({
            type: 'post',
            url: 'http://localhost/lords/trade.php',
            data: frm.serialize(),
            success: function (data) {
                alert(data);
            }
        });
        ev.preventDefault();
    });

But this does not post data. I am using jquery 3.3.1

This is the fiddle https://jsfiddle.net/e3zc1gpb/3/

1 answer

  • answered 2018-11-08 07:08 Heru Prasetyo Utomo

    add id="name" on form tag, or change

    var frm = $('#trade'); 
    

    to

    var frm = $('form[name="trade"]')