Submit Form With JQuery And Ajax - javascript

I am working on discussion that works like a forum. There can be several posts and users are supposed to comment.
I have this html post comment form which repeats itself after every post
<form method="POST" action="/discussion/post-comment" id="post-comment-form" class="form-horizontal subcommentcofrm" role="form">
<div class = "form-group">
<div class = "col-sm-6">
<input type = "text" class = "form-control comment-yako" id = "comment-field" placeholder = "Type your comment here..." autocomplete="off">
</div>
</div>
</form>
And this is my JQuery code with ajax submission:
$("input.comment-yako").live('keypress', function(e) {
if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
console.log('heey');
$(this).closest('form').submit(function(e){
console.log('heeeeeeey');
var data = $(this).serializeArray();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
cache: false,
data: data,
success: function(data) {
var item = $(data).hide().fadeIn(800);
$('.disc-content-reply').append(item);
},
error: function(e) {
alert(e);
}
});
e.preventDefault();
});
$(this).closest(".comment-yako").val("");
return false;
} else {
return true;
}
});
Submission is supposed to take place when the user hits enter key.
My problem is, when I hit enter, the form does not submit. I do not know where the problem is; what am I doing wrong?
Any help will be much appreciated.
Thanks

You should send the AJAX request in the keypress handler itself, not in a submit handler that you bind after the keypress occurs. Most of the time it's wrong to bind one event handler inside another event handler; if you find yourself doing that, think very hard about whether it's really what you want to do.
In addition to changing that, I've converted the .live() call to .on(). I also changed from .serializeArray() to .serialize(), as this is the normal way to send form fields.
$(document).on('keypress', 'input.comment-yako', function(e) {
if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
console.log('heey');
var form = $(this).closest('form');
var data = form.serialize();
var url = form.attr("action");
$.ajax({
url: url,
type: 'POST',
cache: false,
data: data,
success: function(data) {
var item = $(data).hide().fadeIn(800);
$('.disc-content-reply').append(item);
},
error: function(e) {
alert(e);
}
});
e.preventDefault();
$(this).val("");
return false;
} else {
return true;
}
});

Related

Django : Ajax form still reloads the whole page

I am using a django form with ajax using this code:
<form id="form-id">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
and the Javascript code:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
});
But here is the thing, everytime the submit event is triggered, I feel like the whole page is reloaded (it blinks). What could I do to prevent this from happening?
Your change event is submitting your form and page refreshes. Delete it and add change event to second function, where you're currently waiting for submit event.
$('#form-id').on('change', function(evt) {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
To prevent submit on enter, add keypress event to function and detect when enter is pressed. Like this:
$('#form-id').on('change keypress', function(evt) {
var key = evt.which;
if (key == 13) {
return false;
} else {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
}
});
Key number 13 is enter. When it's pressed, nothing is returned. You could have also replaced return false with evt.preventDefault(). And for other keys, Ajax will be triggered.
What if you add:
return false;
To your code, like so:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
return false;
});
});
Got this from:
https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
A very important detail here: in the end of the function we are
returning false. That’s because we are capturing the form submission
event. So to avoid the browser to perform a full HTTP POST to the
server, we cancel the default behavior returning false in the
function.
How I specify my form in html / django template:
<form id="form-id" action="required-url-goes-here" method="post">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
The tutorial I pointed to above works in a different way then you do. It specifies, inside the ajax request:
- url
- type
- data
- dataType
It also uses a different way to reference the form, and it is the only way I know, so I can't judge if there is an error in the rest of your code.

How to create search button for existing code which execute search on enter press? php/javascript/mysql

I have a website which someone else have been coding for me and i'm trying to understand how to change a simple thing.
I am not webdeveloper but on the last days I got familiar a bit with php, mysql and javascript (i'm familiar with java).
****The Question:****
On my website I have search form which works without search button (search function works on enter press or when choosing from autocomplete). How do i change it to work only with search button ?
The web developed with framework called CodeIgniter.
This is how controller looks like:
public function searchGym()
{
if($_POST)
{
$gym_name=$_POST['gym_name'];
$gym_name=trim($gym_name," ");
$data['details']=$this->user_model->getGymByName($gym_name);
$data['gym_name']=$gym_name;
$this->load->view('he/searched_gym',$data);
}
}
This is how model look like:
public function getGymByName($query_string)
{
$query_string=mysql_real_escape_string($query_string);
$query=$this->db->query("select * from gym_members_table where member_title like '%$query_string%'");
return $query->result_array();
}
</code>
And this is the index.php search form :
<div class="search-home">
<input type="text" onkeypress="gymhandle(event);" class="form-control gym_search" id="gym" name="gym" placeholder="
Search by Name
" >
<div class="autosuggest1"></div>
<div class="autosuggest"></div>
</div>
<script>
function settextbox(rval){
$('.autosuggest').hide();
$('#gym').val(rval);
$('#gym_search2').val(rval);
searchGymByName(rval);
}
$(document).ready(function(){
$('.autosuggest').hide();
$('#gym').keyup(function(e)
{
var code = (e.keyCode || e.which);
// do nothing if it's an arrow key
if(code == 37 || code == 38 || code == 39 || code == 40 || code==13) {
return;
}
var search_term = $(this).val();
var getdata = { 'search_term': search_term};
if(search_term!=''){
$.ajax({
url: "<?php echo site_url('hebrew/searchGymAuto');?>",
data: getdata,
type: 'POST',
success: function(data){
$('.autosuggest').show();
$('.autosuggest').html(data);
}
});
}
else
{
$('.autosuggest').hide();
}
});
});
$('.autosuggest').hide();
function searchGymByName(rval)
{
$('.autosuggest').hide();
var gym_name=rval;
$.ajax({
url:"<?php echo site_url();?>hebrew/searchGym",
type: "POST",
data:{gym_name: gym_name},
success:function(res){
$('html, body').animate({ scrollTop: 0 }, 0);
$("#ajax-map").hide();
$("#city").val('');
$("#city1").val('');
$("#ajax-page-hide").show();
$("#ajax-page-hide").html(res);
}
});
}
Thanks!!
You can cancel the enter keypress on those fields like this:
$('.gym_search').keypress(function(e){
if ( e.which == 13 ) return false;
//or...
if ( e.which == 13 ) e.preventDefault();
});
Remove the id attribute from the search input field, and place id="gym" on the search button. And then in $('#gym').click(function(e) [note: 'click' instead of 'keyup'], change the search_term to
var search_term = $("gym_search").val();
Remove onkeypress event from text box. Add ajax call for search in java script function and call that function on button click event

Combine if statement conditions for button clicked and "enter" key pressed on form

I have 2 functions in jQuery, both of which commit the same AJAX function when the input form's submit button is clicked or "Enter" key is pressed on the form. I have 2 identical forms with id 'reserve_email_1' and 'reserve_email_2'.
How do I combine the conditions of the if statement, so I don't need to repeat the same AJAX call for 4 times?
Thanks so much,
Major function:
$(function(){
$('#subscribe_1').click(function(){
$("#subscribe_1").text('Sending……');
var email = $('#reserve_email_1').val();
var name = $('#reserve_requirement_1').val();
var regex_email = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex_email.test(email)||email.match(/^\d+$/))
{
$.ajax({
type:"POST",
url: base_url + "interview/reserve",
data:{email : email, interview_id: interview_id, name: name},
dataType: "json",
success: function(data,status){
if(data.state == 'succ')
{
$("#subscribe_1").text(data.msg+'!');
$('#reserve_email_1').attr('readonly', true);
}
else
{
$("#subscribe_1").text(data.msg);
}
}
});
}
else
{
$("#subscribe_1").text('');
}
});
});
//end of subscribe part 1
and for the condition where the user press 'enter', I simply modify the top part to:
//beginning of subscribe on subscribe page part 1 with enter key
$(function(){
$("#reserve_email_1").bind('keyup', function(event){
if(event.keyCode == 13){
event.preventDefault();
and the rest remains the same. But I'm having trouble combining these 2 conditions ("click button" and "press enter") so I don't have to rewrite the whole ajax action again.
The situation is further complicated by the fact that I have another identical form called reserve_email_2, which calls the exact same function.
Thanks so much,
P.S. I posted this question earlier but didn't get an answer. As a result, I cleaned up my phrases and hoping it would be easier to solve.
You really don't have to duplicate your code. First of all you should not use click event for form submission, there is dedicated form event called onsubmit. The benefit is obvious - it will fire both on submit button press and on Enter key press. So in your form would be:
<form class="subscribe-form">
<input type="text" name="email" class="subscribe" />
<button type="submit" class="btn-subscribe">Send</button>
</form>
JS becomes:
$('.subscribe-form').submit(function (e) {
e.preventDefault();
var $btn = $(this).find('.btn-subscribe');
$btn.text('Sending……');
var $email = $('.subscribe');
var email = $email.val();
var name = $('.requirement').val();
var regex_email = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regex_email.test(email) || email.match(/^\d+$/)) {
$.ajax({
type: "POST",
url: base_url + "interview/reserve",
data: {
email: email,
interview_id: interview_id,
name: name
},
dataType: "json",
success: function (data, status) {
if (data.state == 'succ') {
$btn.text(data.msg + '!');
$email.attr('readonly', true);
} else {
$btn.text(data.msg);
}
}
});
} else {
$btn.text('Send');
}
});
So it will automatically work for all forms with .subscribe-form class. To make it reusable add the same class to email field like class="subscribe".

Enter key to submit Ajax form

I have a very simple AJAX form that asks for an email address and sends it to me after submitting.
How can I can I get the form to submit when hitting the enter key?
This runs when user clicks submit button:
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").click(function () {
// Get input field values:
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
});
// Reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function () {
$("#contact_form input, #contact_form textarea").css('border-color', '');
$("#result").slideUp();
});
});
</script>
I know this question has been asked before -- I'm having trouble getting the keypress function to work.
I tried this to no avail:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && (e.target.type != "textarea")) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
// Everything looks good! Proceed...
if (proceed) {
/* Submit form via AJAX using jQuery. */
}
}
});
The form is #contact_form.
Any help would be would appreciated…
Just bind the submit event to your form, and then the enter key will also work:
$("#contact_form").submit(function (e) {
e.preventDefault();
// Get input field values
var user_email = $('input[name=email]').val();
// Simple validation at client's end
// We simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
if (proceed) {
// Insert the AJAX here.
}
});
And the code is here: http://jsfiddle.net/6TSWk/6/
add new class in every fieldbox or checkbox => class keypressbutton
then replace your code on keypress with this, below :
$(document).on("keypress",".keypressbutton",function(event) {
var keyCode = event.which || event.keyCode;
if (keyCode == 13) {
$("#submit_btn").click();
return false;
}
});
$("#myform").keypress(function(event){
if(event.keycode===13){ // enter key has code 13
//some ajax code code here
//alert("Enter key pressed");
}
});
You have two opening brackets in your if statement and miss a closing bracket. Also, I would change e.target.type. Try this:
$("#contact_form").keypress(function (e) {
if ((e.keyCode == 13) && ($('input[name="email"]').is(':focus'))) {
e.preventDefault();
//get input field values
var user_email = $('input[name=email]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if (user_email === "") {
$('input[name=email]').css('border-color', 'red');
proceed = false;
}
}
});
Instead of using button on click function you can use submit button.
Load the validate.js file
function validateEmail(email)
{
var reg = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/
if (reg.test(email))
{
return true; }
else{
return false;
}
}
$("#test-form").validate({
submitHandler: function(form) {
//form.submit();
var email=$("#email").val();
if(email=='' )
{
// Here you can type your own error message
$('#valid').css("display","none");
$('#empty').css("display","block");
return false;
}
if (!(validateEmail(email))) {
$('#empty').css("display","none");
$('#valid').css("display","block");
return false;
}
else {
$.ajax({
url: "signup.php",
type: form.method,
data: $(form).serialize(),
success: function(response) {
}
});
}
}
});
});
Simple way is this:
In HTML codes:
<form action="POST" onsubmit="ajax_submit();return false;">
<b>First Name:</b> <input type="text" name="firstname" id="firstname">
<br>
<b>Last Name:</b> <input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="send" onclick="ajax_submit();">
</form>
In Js codes:
function ajax_submit()
{
$.ajax({
url: "submit.php",
type: "POST",
data: {
firstname: $("#firstname").val(),
lastname: $("#lastname").val()
},
dataType: "JSON",
success: function (jsonStr) {
// another codes when result is success
}
});
}

How to reset event.preventDefault() of a form submit event?

I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}

Categories