0

I have few field within a form to dynamically add data to database. I send data from couple fields to php using ajax and receive correct response. But when i click button with attached click handler to submit required fields whole form being reloaded i dont know why. Could somebody please help me out. Anyway thanks in advance ;)

  $("#button").click(
    function(){
        var somedata1= $(".someinput").val();
        var somedata2= $(".someselect").val();
        ajax_post('http://someurlhere', 
        'some1='+somedata1+'&some2='+somedata2+'&csrf_token='+csrf_token, handle_submit, handle_error);
    }
);
  • Look for `event.preventDefault()` function. – Ele Aug 14 '18 at 19:39
  • @U-ways CORS?.. – Ele Aug 14 '18 at 19:40
  • with event.preventDefault() click handler doesnt submit required fields, ajax submitting empty request. I have read messages related to the thread very attentively but havent found anything working enought. Probably i put it in wrong place. – Martin Brewer Aug 14 '18 at 19:58

1 Answers1

1

You need to prevent the default action that submitting a form does (reloading the page).

$("#button").click(
  function(e){
    // this prevents the default action from the submit action
    e.preventDefault();
    var somedata1= $(".someinput").val();
    var somedata2= $(".someselect").val();
    ajax_post('http://someurlhere', 
    'some1='+somedata1+'&some2='+somedata2+'&csrf_token='+csrf_token, handle_submit, handle_error);
  }
);
larz
  • 5,724
  • 2
  • 11
  • 20