简体   繁体   中英

Submitting form with AJAX without button

I'm trying to send a form with AJAX and without submit button. Everything works just fine with submit button, but if I try to submit the form by clicking something else it won't work.

I searched for an answer for quite a while, but didn't find anything useful so far.

function ajaxSubmit(){
  var showHideForm = jQuery('#dashboard-hki-subjects-form').serialize();

 $.ajax({
  type:"POST",
  url: "/wp-admin/admin-ajax.php",
  data: showHideForm,
  success:function(data){
  $('#formMessage').html(data);
  }
  });

  return false;
  }

  $('.show-hide-subject-button').click(function(){ 
    var subject = $(this).attr('subject');
    $('#hide-subject').attr('value',subject);
  });


 $('#dashboard-hki-subjects-form').submit(ajaxSubmit);

I'm using Wordpress, so the AJAX is handeled with admin-ajax.php.

What if you just use an enter key handler...

Try this:

<input type="text" name="txt"/>

$('#txt').keydown(function (e){
    if(e.keyCode == 13){
        console.log('you pressed enter!'); //prints to the browser console...
        ajaxSubmit(); //the function you described in your question...
    }
})

You have to bind the ajaxSubmit() to whatever there is you're clicking, otherwise there simply will be nothing on your page to trigger it. Eg, if you want your form to be submitted whenever you click on the .show-hide-subject-button element, you have to call ajaxSubmit() explicitly:

$('.show-hide-subject-button').click(function(){ 
    var subject = $(this).attr('subject');
    $('#hide-subject').attr('value',subject);
    ajaxSubmit();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM