Event needs multiple clicks in Jquery - javascript

I am trying to get the response from the PHP scripts but the button takes multiple clicks on firing the event. I read about that on Google but unable to understand that why it is going to happen.
Html Code
<form action="javascript:MyResults()">
<input type="submit" value="Search" id ="button1"/>
</form>
Javascript Code
function MyResults(){
$(document).ready(function(){
$("#button1").click(function(){
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
}
</script>

You are declaring $(document).ready(function() inside MyResult function . In first case it will execute the MyFunction & in second case it will execute the code inside the ready function.
Actually there is no need to the action here. Following change will work
HTML
<form id='target'>
<input type="submit" value="Search" id="button1" />
</form>
JS
$(document).ready(function() {
$("#target").submit(function() {
event.preventDefault()
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type: "POST",
async: true,
data: {
"search": searchData,
},
success: function(value) {
alert(JSON.parse(value));
$.each(value, function(index, value1) {
console.log(value1);
});
}
});
});
})

The problem is that your current code doesn't set-up the click-handler for button until the form is submitted. That first click triggers the action attribute on the <form>, which sets up the handler. The second click then calls the button handler.
Instead of your current code, you probably want HTML like this:
<form>
<input type="submit" value="Search" id ="button1"/>
</form>
Use $(document).ready(...) without the wrapper function MyResults(), and be sure to cancel the click event to stop traditional form submission:
<script>
$(document).ready(function(){
$("#button1").click(function(event){
event.preventDefault();
event.stopPropagation();
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
</script>

Here fired one event at two times.
First fired when form submit.
action="javascript:MyResults()"
Second fired after form submit which you have defined in the function part.
$("#button1").click(function(){});

Related

Why is jquery-ajax submitting form multiple times?

I have read this: jQuery ajax form submitting multiple times
It didn't help.
If i type something on form and click the submit button then it sends one request. Second time if i type something and click it sends two requests. Third time it sends three requests and so on. Why is this? Did i do any mistake in jquery code?
Here is my code:
index.php =>
<div id="id_div_1" class="cl_div_comment_container"></div>
<form id="id_form_1" method="POST">
<input type="hidden" value="1" name="nm_hidden_post_id">
<textarea class="cl_textarea_comment" style="resize:none;" rows="1" cols="50" name="nm_comment_content"></textarea>
<input class="cl_submit_comment" type="submit" value="Comment" name="nm_submit_comment">
</form>
javascript.js =>
$(document).ready(function(){
console.log('hello');
$('input[name="nm_submit_comment"]').on('click',function(){
var frm = $(this).closest("form")[0];
var frm_id = $(frm).attr("id");
var frm_id_splitted = frm_id.split("_");
var frm_id_splitted_2 = frm_id_splitted[2];
console.log($('div#id_div_' + frm_id_splitted_2));
$(frm).on('submit',function(e){
e.preventDefault();
frm_serialized = $(this).serialize();
console.log(frm_serialized);
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function(data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
});
});
save-comment.php =>
<?php
if (session_id() == '') {
session_start();
}
echo json_encode($_POST);
?>
You are registering the event for form submit inside the code you have for the click event on the button. So every time you click the button, it will keep adding the event over and over.
This should be good enough.
$(document).ready(function(){
$('input[name="nm_submit_comment"]').on('click',function(e){
e.preventDefault();
var frm = $(this).closest("form");
var frm_id = frm.attr("id");
var frm_id_splitted = frm_id.split("_");
var frm_id_splitted_2 = frm_id_splitted[2];
var frm_serialized = frm.serialize();
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function(data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
});
Try one then on
$("#id_form_1").one('submit', function (e) {
e.preventDefault();
frm_serialized = $(this).serialize();
console.log(frm_serialized);
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function (data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
Also no need to make submit bind just serialize your nearest form and make ajax call. You are binding event inside and event performs multiple binding.
You can try this:
$(document).off().on("click","#submit",(function(e) {
e.preventDefault();
}

Onclick form submit as button submit

I have a link with onclick attr to submit my form. Like this:
lorem ipsum
function myFunc() {
$('.ajaxform').submit();
}
The problem is.. I'm using an ajax function to do a non-refresh submit.. And I have another script like this:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
If I use a input button type submit the ajax works.. But it doesnt work using the onclick submit... How can I solve this?
Thanks.
If you are using a <a> attribute then instead of inline onclick attribute write the click function seperately and then use event.preventDefault(); and then submit the form
<a id='someId' href="javascript:void(0);" onclick="myFunc()">Submit</a> //Give some id
$(function(){
$('#someId').click(function(){
event.preventDefault(); //This will prevent the default action of <a> attribute
$('.ajaxform').submit(function(){
//write the functionality here
});
});
});
Option 1
You can add css to a submit button to look like a link and replace it with your link.
Option 2
HTML
<form id="form1" method="POST" action="#" >
<input type="text" class="youwant" name="youwant" id="youwant" />
lorem ipsum
</form>
JavaScript
jQuery(document).ready(function(){
$('#myform').on("click", function(event) {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
I didn't try it but it may help you, just give a try and do reply if helpful.
$(function() {
$("#tbutton").click(function(){
var frmValues = $('#validation').serialize();
$.ajax({
type: $this.attr('method'),
url: "hello.php",
data: frmValues
})
.done(function () {
$("#para").text("Serialized! Input String is " + frmValues);
})
.fail(function () {
$("#para").text("An error occured");
});
event.preventDefault();
});
});

check if button was clicked in the controller

I have the following button and when clicked it's invoking a function,
Is there a way to know in the controller that this button was clicked ?
$("#RemoveFile").on("click", RemoveFile);
<button class="btn" style="height: 25px" type="button" id="RemoveFile"><p >Remove File</p></button>
As Edurado Says this the implementation which you asked to him
First set hidden field in html page (razor view/ aspx page)
<input type="hidden" id="StakeholderId" name="stakeholderId" />
Then add script like below
$( "#buttonID" ).click(function() {
$( "StakeholderId" ).val(true);
});
And get the value and posting the value to controller like below
var hidden= $('StakeholderId').val();
$.ajax({
type: "post",
url: "Controller/Method",
data: {
hiddenField1: hidden,
hiddenField2: "hiddenValue2",
},
success: function() {
alert("yay")
},
error: function(e) {
console.log(e);
}
});
Hope this helps....
When you click in the button, add an onclick event to this very button and save the clicked status in a hidden field. Then, whenever you send data to the controller, send this hidden field value, stating whether the button was clicked.
UPDATED:
Here is the HTML
<input id="hdnRemoveClicked" type="hidden" value="false" />
And here is the javascript which adds the click event in the button with ID="RemoveFile", and set the hidden field value as true, to show it is clicked.
$( "#RemoveFile" ).click(function() {
$( "hdnRemoveClicked" ).val(true);
// do other things, if needed
});
The only way I know of to so this in MVC is to make an Ajax call to the server via an anonymous function in the JQuery component. Example:
$("#RemoveFile").on("click", "RemoveFile", function () {
// tell server
var jqxhr1 = $.ajax({ type: 'POST', url: "/myControllerUrl",
data: { buttonID: "RemoveFile" } });
$.when(jqxhr1).done(function (response, textStatus, jqXHR) {
if (textStatus != "success") {
alert("Error, please try later");
return false;
}
// update the user interface
});
});
Make an ajax call to a method in Controller where a session keeps track if button was clicked.

Bootstrap popover repeats an action/ event twice?

Why Bootstrap's popover repeats an action twice? For instance, I want to submit a form inside the popover's data-content via ajax. It repeats all the form data twice and the posts form twice.
Any idea what I can do about it?
jquery + bootstrap,
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
$('.bootstrap-popover-method').on('shown.bs.popover', function () {
// do something…
console.log(this); // I get twice of the button element <button class="btn btn-default bootstrap-popover-method"...>
console.log($(".btn-submit").length); // I get twice of '1'.
$(".link").click(function(){
console.log($(this).attr("href")); // I get once of 'test.html'.
return false;
});
$(".btn-submit").click(function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
});
bootsrap + html,
<button type="button" class="btn btn-default bootstrap-popover-method" data-title="body" data-container="body" data-toggle="popover" data-placement="bottom">
Popover on bottom
</button>
<div id="popover-content">
hello
<form action="1.php" class="myform">
<input type="text" name="username" value="hello world!"/>
<input type="submit" value="submit" class="btn-submit"/>
</form>
</div>
This happens because popover.content checks if the tooltip is empty or not.
A simple fix would be to add a title attribute to popover.
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
title: "New Title",
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
https://github.com/twbs/bootstrap/issues/12563#issuecomment-56813015
This might be an old post, but i'm gonna leave here my work around.
I'm using bootstrap 3.3.5.
So the buggy behavior is that on every execution of "popover('show')", Bootstrap calls the rendering function twice, and only the second call is the one that actually renders the popup.
My fix is to return a short html string for the first call, and for the second call i let run the whole rendering function:
jQuery('.bootstrap-popover-method').popover({
html: true,
trigger: 'manual',
content: function(){//This is our rendering function for the popup's content
var __G_bs_popover_shown= jQuery.data(jQuery('body')[0], '__G_bs_popover_shown');
//Create a global variable, attached to the body element, to keep track of the repeating calls.
__G_bs_popover_shown= (typeof __G_bs_popover_shown == 'undefined') ? 1 : (__G_bs_popover_shown + 1) % 2;
//Update the global var
jQuery.data(jQuery('body')[0], '__G_bs_popover_shown', __G_bs_popover_shown);
//return a short string on every first call (this will not be rendered, anyway)
if(__G_bs_popover_shown == 1) return '<div>BLANK</div>';//==>this should not be an empty string!
//PLACE YOUR CODE HERE, E.G. AJAX CALLS, ETC..
//DON'T FORGET TO RETURN THE HTML FOR THE POPUP'S CONTENT!
}
});
I think you need to prevent the default event of the submit button
$(".btn-submit").click(function(e){
e.preventDefault();
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
$('.bootstrap-popover-method').off('shown.bs.popover')
.on('shown.bs.popover', function (e) {
e.preventDefault();
}
// unbind your submit button click
$(".btn-submit").off('click').on('click',function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});

jQuery Submit Refreshing Page

The following code is intended to do a purely ajax POST request, instead it seems to do the POST via ajax and then the browser navigates to the response.
The HTML...
<div id="bin">
<form class="add" method="post" action="/bin/add/">
<p>I'm interested! Save for later.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Save">
</form>
<form style="display:none;" class="remove" method="post" action="/bin/remove/">
<p>I changed my mind--I'm not interested.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Unsave">
</form>
</div>
The jQuery...
$('#bin form').submit(function() {
$.post($(this).attr('action'),{
success: function(data) { $(this).hide().siblings('form').show() },
data: $(this).serialize()
});
return false;
})
As far as I understand it, the return false; line should mean that no matter what, any calls to the submit function or clicks on the 'Submit' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add or /bin/remove. But for some reason, the browser is changing pages.
Any idea what I'm doing wrong here? Thanks.
It could be your JavaScript is failing, so the default behaviour is being executed.
Try to examine the XHR in a tool like Firebug.
Also, you could try event.preventDefault() (where the first argument to your event callback is event).
my bet it's because of the $(this), try it this way....
$('#bin form').submit(function() {
var $this = $(this);
$.post($this.attr('action'), {
success: function(data) {
$this.hide().siblings('form').show()
},
data: $this.serialize()
});
return false;
});
demo no error
demo with the error
Use event.preventDefault() to prevent the default action of the event. One benefit is that you can place this before the Ajax request, so that if it fails, you will still have prevented form submission.
Your code is failing because the value of this in your success callback is the global window object. Your attempt to hide it fails. You probably want this to refer to the form, like this:
$('#bin form').submit(function(ev) {
var _this = this;
ev.preventDefault();
$.post($(this).attr('action'), {
success: function() {
$(_this).hide().siblings('form').show();
},
data: $(this).serialize()
});
})
See a working example.
Is the $(...).submit(...) inside a $(document).ready(function(){ code here }); ?
should be like:
$(document).ready(function() {
$('#bin form').submit(function() {
$.post($(this).attr('action'), {
success: function(data) { $(this).hide().siblings('form').show(); },
data: $(this).serialize()
});
return false;
});
});

Categories

Resources