Prevent Page Load on Jquery Form Submit with None Display Button

淺唱寂寞╮ 提交于 2019-11-26 02:16:58
cssyphus

I think you're looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without reloading the page.

The page is reloading because you are using a <form>. When the submit button is pressed, it submits the form, which always refreshes the page. However, if you use AJAX you can send the data, (optionally receive a response) and carry on as normal.

In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.

Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.


Also, change the Submit button's type from type="submit" to type="button"


To detect when a user presses ENTER in the input field, and then click the submit button, try this:

$(function(){
    $('#user-response').keyup(function(){
        var keycode = (e.keyCode ? e.keyCode : e.which);
        if(keycode == '27'){ $('form').fadeOut();}
        if(keycode == '13'){ 
            $('#user_submit').click();
        }
    });
});

In such case when you don't need to have the submit button, just use form's submit method, like first you provide your form tag an id (e.g. myForm)

<div id="bot">
  <form id="myForm">
    <input id="user-response" type="text" placeholder="" autocomplete="off" autofocus />
    <button id="user-submit" type="submit" style="display: none !important;">Send</button>
  </form>
</div>

and then to submit the form use

document.getElementById("myForm").submit();

and if you want this to happen when you press enter in textbox then use it like

$('#user-response').on('keypress', function(event){
   if (event.which === 13 || event.keyCode === 13) {
      document.getElementById("myForm").submit();
   }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!