Form not submitting on ajax request - javascript

So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the .submit() somewhere else?
HTML code:
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<div><input id="answer-input" name="answer" type="text"></div>
<input type="hidden" id="id" name="id" value="<?=$id?>">
<div><button type="submit" id="validate">Valider</button></div>
</form>
</div>
JS code
$("#validate").click(function(e){
e.preventDefault();
$.post(
'includes/checkAnswer.php',
{
answer : $('#answer-input').val(),
id : $('#id').val()
},
function(data){
if(data === '1'){
$("#answer-warning").html("OK");
$("#answerInput").submit();
}
else{
$("#answer-warning").html("WRONG");
}
},
'text'
);
});

I think it is because you set your button type as submit. Why?
When you do $("#validate").click(function(e){, you implicitly replace the default submit behavior of the form.
As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.
Then the $("#validate").click(function(e){ will alter behavior of click, not the submit of form.

<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<input id="answer-input" name="answer" type="text">
<input type="hidden" id="id" name="id" value="<?=$id?>">
<button onlcick="validate()">Valider</button>
</form>
/******** JS ************/
function validate(){
var post = {};
post['answer'] = $('#answer-input').val();
post['id'] = $('#id').val();
$.ajax({
url: 'includes/checkAnswer.php',
type: 'POST',
data: {data: post},
success:function (data) {
console.log('succsess');
},
error:function (jQXHR, textStatus, errorThrown) {
console.log('failure');
}
});
}

Related

How to prevent auto form submit

I have the following input box which takes input from barcode scanner.
<form class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ url('updateInvoice') }}" id="invoice_update">
<div class="form-group m-form__group">
<label for="exampleInputEmail1">Search by item name or barcode</label>
<input type="text" autofocus class="form-control m-input" id="productSearch" placeholder="Item name">
</div>
<button type="submit" name="pdf" class="btn btn-success">Update & print
</button>
</form>
After getting the input from barcode it does following operation (from the input it checks value from database and add to row)
$( "#productSearch" ).change(function(event) {
event.preventDefault();
$.ajax({
type: "get",
context: this,
url: "{!! asset('searchByProductName') !!}",
dataType: 'json',
data: { name:this.value },
success: function(response)
{
if ($('#' + response.id).length !== 0)
{ $(this).val("").focus(); return false; }
var markup = "<tr id="+response.id+"><input type='hidden' name='product_id[]' value="+response.id+"><td><i class='flaticon-delete-1 delete-row' onclick='deleteRow(this)'></i></td><td>"+response.product_name+"</td><td>"+response.product_unit_price+"</td><td><input type='text' name='quantity[]' class='quantity' value='1'></td><td class='total'>"+response.product_unit_price+"</td><td>"+response.notes+"</td></tr>";
$("table tbody").append(markup);
$(this).val("").focus(); return false;
}
});
});
But the problem the form get auto submit ie, i can't add more than one value in the table. How do i prevent the form automatic submit so that more that one input can be taken with the above ajax code?
I'm not sure if the barcode scanner put the "enter key", but how about this one?
$("#form-id").on("submit", function(e) {
if ($("#input-id(productSearch)").is(":focus")) {
e.preventDefault();
}
});
IMO, the easiest way is to add a hidden input
<input type="hidden" />
browser will auto submit if there is one input in a form.

How to stop opening ACTION page after submitting FORM using JavaScript

When I am submitting the FORM using SUBMIT button, it takes me to the ACTION page. But I want to stay in same page after submission and show a message below the form that "Submitted Successfully", and also reset the form data. My code is here...
<h1>CONTACT US</h1>
<div class="form">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSe0dybzANfQIB58cSkso1mvWqKx2CeDtCl7T_x063U031r6DA/formResponse" method="post" id="mG61Hd">
Name
<input type="text" id="name" name="entry.1826425548">
Email
<input type="text" id="email" name="entry.2007423902">
Contact Number
<input type="text" id="phone" name="entry.1184586857">
Issue Type
<select id="issue" name="entry.1960470932">
<option>Feedback</option>
<option>Complain</option>
<option>Enquiry</option>
</select>
Message
<textarea name="entry.608344518"></textarea>
<input type="submit" value="Submit" onclick="submit();">
</form>
<p id="form_status"></p>
</div>
You need to use Ajax for sending Data and no refresh the page.
//Jquery for not submit a form.
$("form").submit( function(e) {
e.preventDefault();
return false;
});
//Ajax Example
$.ajax({
data: {yourDataKey: 'yourDataValue', moreKey: 'moreLabel'},
type: "POST", //OR GET
url: yourUrl.php, //The same form's action URL
beforeSend: function(){
//Callback beforeSend Data
},
success: function(data){
//Callback on success returning Data
}
});
Instead of adding onclick="submit()" to your button try capturing the submit event. In your submit function you also need to return false and prevent default to prevent the form from not submitting and taking you to the action page.
Using jQuery it would look something like this:
$("#id_form").on("submit", function(e){
//send data through ajax
e.preventDefault();
return false;
});

How do I submit form using ajax

I have my form and my ajax laid out but I am not sure how to submit the form using the ajax. I've tried $('#testform').submit() but it didn't call my ajax when I wrapped it with the submit. I might of been doing it wrong. How do I get my form to submit through the ajax and not submit regularly?
<form id="testform" action="https://example.com/api/payments/" method="post">
Name<input type="text" name="name" id="name">
Card Number <input type="text" name="card_number" id="card_number" maxlength="16">
Exp Month <input type="text" name="exp_month" id="exp_month">
Exp Year <input type="text" name="exp_year" id="exp_year">
CVC <input type="text" name="cvc" id="cvc" maxlength="3">
Amount <input type="text" name="amount" id="amount">
<input type="submit" id="submit">
frm = $('#testform');
frm.submit(function(ev)
{
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "html",
//Set the HTTP headers for authentication
beforeSend: function (xhr) {
xhr.setRequestHeader('api_key', 'tiyndhinzrkzti5ody0');
xhr.setRequestHeader('email', 'example#example.com');
},
//Serialize the data sent from the form inputs
data: frm.serialize(),
success: function(data) {
$('#return').append(data);
}
});
ev.preventDefault();
});
Instead of frm.submit(function(ev) try the following code
$("#testform").on('submit', function(ev) {
ev.preventDefault();
...
});
After clicking on the submit button you should see the ajax being posted in the console. The "magic" is to attach a handler to the submit event instead of invoking the event itself. Additionally, you had a typo in your previous code ($('testform') instead of $("#testform"))

ajax isnt sending post request to php

Javascript doesn't send any post data to php file
$(document).ready(function(){
function showComment(){
$.ajax({
type:"post",
url:"process.php",
data:"action=showcomment",
success:function(data){
$("#comment").html(data);
}
});
}
showComment();
$("#button").click(function(){
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
});
form:
<form action="" method="POST" enctype="multipart/form-data">
name : <input type="text" name="name" id="name"/>
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>
php
$action=$_POST["action"];
if($action=="addcomment"){
echo "Add comment WORKS!";
}
if($action=="showcomment"){
echo "default";
}
Tried to add such lines as if post addcomment than show some words, just for a test since sql request didn't but php doesn't show any response at all, like there was no post action at all.
ps. I'm really new ajax so if possible show me a solution to solve it.
You're using a submit button so it will be making the form submit and reload which will bypass your ajax, you can change your jQuery to listen for the form submit event instead like this:
$("form").on('submit', function(e){
// Stop form from submitting
e.preventDefault();
var name = $("#name").val();
var message = $("#message").val();
var dataString = "name="+name+"&message="+message+"&action=addcomment";
$.ajax({
type:"post",
url:"process.php",
data:dataString,
success:function(data){
showComment();
}
});
});
Or simply change the button from type="submit" to type="button" or replace it with a element.
You are using submit button as Dontfeedthecode mentioned. Your form does not have any action so it is self posting. I have added action and id to the html form and a hidden field to pass the action. Now javascript serialize the form and send it to the process.php.
$(function () {
$("#my-form").on("submit", function (e) {
$("#action").val("addcomment");
$.ajax(
{
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
showComment();
}
});
return false;
});
});
<form action="process.php" method="POST" id="my-form" enctype="multipart/form-data">
<input type="hidden" id="action" name="action" value="" />
name : <input type="text" name="name" id="name" />
</br>
message : <input type="text" name="message" id="message" />
</br>
<input type="submit" value="Post" name="submit" id="button">
<div id="info" />
<ul id="comment"></ul>
</form>

(button || input) type=submit - missing value in $_POST variable in jQuery AJAX

I have login form where are two buttons - "login" and "forgot password?" And I need to check what button user clicked.
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
</form>
var_dump($_POST) says:
array(2) { ["email"]=> string(0) "" ["password"]=> string(0) "" }
I am trying both ways (input type=submit and button type=submit) but none of them send the "submit" value.
(I am using jquery ajax)
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php", /* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function(data){
$("#login-error").html(data);
},
error:function(){
$("#result").html('There is error while submit');
}
});
});
Please do you know where the problem can be? I know, there are lot of threads about value of button but nothing works for me. I also tried this example:
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_value2
The .serializeArray() or .serialize() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.
Refer..
http://api.jquery.com/serialize
http://api.jquery.com/serializeArray
jQuery serializeArray doesn't include the submit button that was clicked
This is one way to do it, concatening data string with specific clicked button name attribute:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit">Login</button>
<button type="button" name="forgot" class="submit">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize() + '&' + this.name;
console.log(values);
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php",
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
But better would be to target specific server side script depending which button is clicked, e.g:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit" data-url="login.php">Login</button>
<button type="button" name="forgot" class="submit" data-url="forgot.php">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: $(this).data('url'),
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
It will be a lot easier to check if you name the submit input and the button differently.
You currently have this set up like this:
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
Try changing the name of the button to something like:
name="forgot"
then you can run a check on it such as
if (isset($_POST['submit'])){
stuff here
}
and a separate check for
if (isset($_POST['forgot'])){
stuff here
}
If there is not event in function then it will not prevent the submit function and by default get will be called and and $_POST will be empty for sure
Change
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
To
$("#loginForm").click(function(event){
/* Stop form from submitting normally */
event.preventDefault();
Make one more change
data: values,
To
data:$("#loginForm").serialize(),
Remove one submit type there should be only one submit type make it type of button and call onbutton click functiuon to submit via ajax it will work same as submit.

Categories

Resources