I have two forms for buy now and for pincode when I click buynow button sending request through ajax and same thing is done for pincode form also.
HTML
<form method="POST" action="/cart/add" id="myForm">
.....
....
<input type="button" class="buyNowBtn" id="btnBuyNow"/>
</form>
<form action="#">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
In the same buynow click event I need to trigger a pincode submit button, so I did this
(document).on('click', '#btnBuyNow', function (e) {
....
....
$("#pinCheckTest").trigger('click');
....
});
the above trigger event is successfully calling pincode click event
$('#pinCheckTest').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {
}
else{
}
}
});
but I need to get ajax response back to trigger event so that I can do some operation is it possible?
something like
(document).on('click', '#btnBuyNow', function (e) {
....
....
$var output=$("#pinCheckTest").trigger('click');//I need to get ajax response back to this click
if(output=='true'){
......
}else{
.....
}
....
});
You can define a variable outside of both click handlers, when .trigger() is called, assign $.ajax() to variable, use .then() within first click handler to process results of $.ajax() call.
Note, included event.preventDefault() to prevent submission of <form>, as pointed out by #IsmailRBOUH
var dfd;
$(document).on('click', '#btnBuyNow', function (e) {
e.preventDefault();
....
....
$("#pinCheckTest").trigger('click');
if (dfd) {
dfd.then(function(output) {
// do stuff with output
console.log(output)
})
}
....
});
$('#pinCheckTest').click(function (e) {
e.preventDefault();
dfd = $.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {}
else{};
}
})
});
var dfd;
$("#first").click(function() {
$("#second").trigger("click");
if (dfd) {
dfd.then(function(data) {
alert(data)
})
}
})
$("#second").click(function() {
// do ajax stuff
dfd = $.when("second clicked")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first">first button</button>
<button id="second">second button</button>
Since you are binding the click event to a button inside form you have the prevent the default behaviour which is 'submit the form'. Change you code to :
$('#pinCheckTest').click(function (e) {
e.preventDefault();
//Your ajax call
});
Here is a demo to clarify the difference https://jsfiddle.net/qvjjo3jk/.
Update1:
Add an id to your form:
<form action="#" id="pinCheckForm">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
Then:
$('#pinCheckForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: url,
data: $(this).serialize(), //Sends all form data
success: function(output) {
if (output == 'true') {} else {}
}
});
});
Related
Below is my code of html and jquery, i want to dsiplay results on submit button on the same page rather than its goes on next page. But it is not returning me any results and go to next page.
HTML code
<form id="create" action="/engine_search/search/" method="get">
<input style="height:40px;" type="text" class="form-control" placeholder="Search" name="q">
<center>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search">
</center>
</form>
jquery code:
<script>
$(document).ready(function() {
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search" onclick="return SubmitFunction(this);">
Javascript :
function SubmitFunction(thisId){
$.ajax({ // create an AJAX call...
data: $(thisId).serialize(), // get the form data
type: $(thisId).attr('method'), // GET or POST
url: $(thisId).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
}
You should use event.preventDefault();
<script>
$(document).ready(function() {
$('#create').submit(function(event) { // catch the form's submit event
event.preventDefault();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
Look for console for any errors. It might be helpful.
Why does the below script cause the form to submit twice? I can't figure this out, even after trying other solutions posted around the internet. Submitting twice is causing duplicate entries in the database. Thank you in advance for looking into this!
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$("#form-submit").click(function(){
$("#form").submit();
});
});
$('#form').submit(function(e) {
register();
e.preventDefault();
});
function register()
{
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
}
function hideshow(el,act)
{
if(act)
{
$('#'+el).hide(0).slideDown(500, 'linear');
}
else $('#'+el).hide();
}
function error(act,txt)
{
if(txt)
{
$('#form-error').html(txt);
}
$('#form-error').hide(0).slideDown(500, 'linear');
}
</script>
HTML Form:
<form id="form">
<p>First Name:</p>
<input type="text" name="firstname" />
<p>Last Name:</p>
<input type="text" name="lastname" />
<p>E-Mail Address:</p>
<input type="text" name="emailaddress" />
<p>Sequence Assignment:</p>
<select name="sequence">
<option value="1">Default Sequence</option>
</select>
<button id="form-submit">Add User</button>
<p id="form-error"></p>
</form>
There are duplicated event listeners for the submit event:
1. When submit button clicked:
$("#form-submit").click(function(){
$("#form").submit();
});
2. When form is submitted:
$('#form').submit(function(e) {
register();
e.preventDefault();
});
You need only one of them.
Change your code like:
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$('#form').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
.
.
.
I had a similar issue to this. If you just single click on the button does it enter duplicate data?
The way I got around it is once the click happened I disabled the button until after the Ajax call.
function register()
{
//disable button
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
//Enable Button
}
Another option would be to do some checks in the php code that submits it to the database to see if that data already exists.
I want to clear all inputs value whenever result succeed.
I have tried unbind from Jquery but doesn't get any result
so any suggestion would be great
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="Result"></div>
<form id="Form" action="File.php" autocomplete="off">
<input type="text" name="Name" />
<br/>
<input type="text" name="Pass" />
<br/>
<input type="button" id="Submit" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#Submit").click(function()
{
$("#Form").submit(function(e)
{
$.ajax(
{
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function(data, textStatus, jqXHR)
{
$("#Result").html(data);
}
});
e.preventDefault();
});
$("#Form").submit();
});
});
</script>
</body>
</html>
please feel free to ask for more details
You can clear all inputs using
$("input[type='text']").val('');
You are binding an event handler inside another event handler. Each time the button is clicked, a new handler is attached to the form. So, after n number of clicks, you'll be sending n number of ajax requests, as you can see here
Ideally, your code should be
$(document).ready(function () {
$("#Submit").click(function () {
$("#Form").submit();
});
$("#Form").submit(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function (data, textStatus, jqXHR) {
$("input[type='text']").val(''); // reset the input values
$("#Result").html(data);
}
});
});
});
Demo.
Side note: You can simply use a submit button instead of triggering the form submission manually like this
Here you go:
$(document).find('input').each(function(){
$(this).val('');
});
More info on: http://api.jquery.com/val/
I am trying to submit a form through ajax function while button
but on safari browser its submitting like a normal form submitting.
and In other browser its working properly through ajax function
<g:form action="addEmpHistory" name="formNew" method="post">
<button id="submitBtn" name="submitBtn" onclick="submitform(formNew);"></button>
</g:form>
//Ajax code
function submitform(data){
$("#"+data).submit(function(event) {
new Event(event).preventDefault();
event.preventDefault();
$.ajax({
type: 'POST',
url: '/user/addUSer',
data: $('#'+data).serialize(),
success: function (data) {
location.reload();
}
});
});
}
Seen as you are using jQuery, consider removing onclick
<form action="addEmpHistory" id="formNew" name="formNew" method="post">
<button id="submitBtn" name="submitBtn">Submit</button>
</form>
and replacing your submitform function with jQuery event binding, something like:
$(document).ready(function() {
$("#formNew").submit(function() {
$.ajax({
type: 'POST',
url: '/user/addUSer',
data: $("#formNew").serialize(),
success: function(data) {
alert(data);
}
});
return false; // prevent actual form submit
});
});
I am having an infinite cycle using this jquery code, I know WHY but I dont know HOW to fix this:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true")
$('#submitme').submit();
});
});
</script>
The jQuery.validate plugin takes care of this and I would strongly recommend you using it:
$('#submitme').validate({
rules: {
n1: {
remote: {
url: 'validate.php',
type: 'post'
}
}
}
});
But if you don't want to use it another possibility is to use a global variable, like so:
$('#submitme').submit(function() {
if (!$.formSubmitting) {
var $form = $(this);
$.post('validate.php', { value: $('#n1').val() }, function (data) {
if (data == 'true') {
// set the global variable to true so that we don't enter
// the infinite loop and directly submit the form
$.formSubmitting = true;
$form.submit();
}
});
return false;
}
return true;
});
Just a remark: the button you have placed inside the form is not a submit button so clicking it will not trigger the submit handler. You should make it a submit button:
<input value="Send" type="submit" />
I am not a jQuery expert, but in Prototype, when you write an event handler for an action and you don't stop the default action, than it will be executed after all of your callback functionality was done. So by simply flipping the if-else statement you should be able to avoid a infinite loop:
$('#submitme').bind( 'submit', function(event) {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data != "true")
// if validation has failed, prevent default action (submit)
event.preventDefault();
});
// if default action was not prevented it will be executed
})
I found this solution:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
if ($.data( $('#submitme' ), 'validated'))
return true;
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true") {
$.data( $('#submitme'), 'validated', true );
$('#submitme').submit();
}
});
return false;
});
</script>