stopping a function after first click, to prevent more executions - javascript

I have this function
function display() {
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
and it serves its purpose, the only problem is, a user can click on for as many times as possible, and it will send just as many requests to new.php.
What I want is to restrict this to just 1 click and maybe till the next page refresh or cache clear.

Simple example would be :
<script>
var exec=true;
function display() {
if(exec){
alert("test");
exec=false;
}
}
</script>
<button onclick="javascript:display();">Click</button>
In your case it would be :
var exec=true;
function display() {
if(exec){
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
exec=false;
}
});
}
}

This should do what you want:
Set a global var, that stores if the function already was called/executed.
onceClicked=false;
function display() {
if(!onceClicked) {
onceClicked=true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
}

During onclick, set a boolean flag to true to indicate that user clicked the link before invoking the display() function. Inside the display() function, check the boolean flag and continue only if it is true. Reset the flag to false after the AJAX completed processing (successful or failed).

You can use Lock variable like below.
var lock = false;
function display() {
if (lock == true) {
return;
}
lock = true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function (data) {
$('.daily').html(data);
lock = false;
}
});
}

you can implement this with that way too
$(function() {
$('#link').one('click', function() {
alert('your execution one occured');
$(this).removeAttr('onclick');
$(this).removeAttr('href');
});
});
function display(){
alert('your execution two occured');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="display();" id='link'>Have you only one chance</a>

Related

JavaScript libraries are not working inside Ajax

#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
function notyfy() {
$.notify({
message: "Hello"
}, {
type: 'danger'
});
}
notyfy();//THis works
$("#btnSave").click(function (e) {
savedata();
});
function savedata() {
var items = new Array();
$("#tblGRN TBODY TR").each(function () {
var row = $(this);
var item = {
'PoNo': $("#PoNo").val(),
'FundSource': $("#FundSource").val(),
'Vote': $("#Vote").val(),
'Total': row.find("TD").eq(5).html(),
'InvoiceNo': $("#InvoiceNo").val(),
'ReceivedDate': $("#ReceivedDate").val(),
'Note': $("#Note").val()
}
items.push(item);
});
$.ajax({
type: "POST",
url: "/GRN/Create",
data: JSON.stringify(items),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
notyfy(); //This do not work
alert(r.responseText);
console.log(r);
$("#tbody").empty();
window.location = "/GRN/Create";
}
});
}
</script>
$.notify is not a function
$.notify works outside without any issue. anything I put inside the success function giving me not a function. all libraries are working fine outside the ajax.
The whole script part is above. please help me to solve the issue in this.

Why do the ajax requests fire multiple times

I have a form inside a modal that either saves a memo when one button is clicked or deletes it when another is clicked. The items get saved/deleted but the request count multiplies with each click. I'm getting 4 of the same request etc. How do i stop this. do i have to unbind something?
$('#modal').on('show.bs.modal', function (e) {
var origin = $(e.relatedTarget);
var memoId = origin.attr('data-id');
$('#modal').click(function(event){
if($(event.target).hasClass('memo-save')) {
event.preventDefault();
var memoText = $(event.target).parent().parent().find('textarea').val();
var memo = {
memo: memoText,
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/add-memo?memo=' +memo+'&id=' + memoId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Saved');
}
});
} else if($(event.target).hasClass('memo-delete')) {
event.preventDefault();
var memoText = "";
var memo = {
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/remove-memo?id=' + itemId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Deleted');
}
});
}
});
});
you can move the $('#modal').click outside the $('#modal').on('show.bs.modal' that way it will not re-add the listener each time the modal is shown

How to Hide multiple div on Ajax Success

I am trying to hide 2 div on Ajax Success by following code
$(".editButton").click(function () {
var self = this;
var membershipid = $(this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembershipDetail","User")',
data: { "MembershipID": membershipid },
success: function (data) {
$('#ddlStoreUpdate').val(data["fk_Store_ID"]);
$('#TxtTitleUpdate').val(data["MembershipTitle"]);
$('#TxtDescriptionUpdate').val(data["MembershipDescription"]);
$('#TxtTimeFrameUpdate').val(data["MembershipTimeFrame"]);
$('#TxtMembershipMinUpdate').val(data["MembershipMinVisit"]);
$('#chkUpdate').prop('checked', data["MembershipGroundLevel"]);
$('#HiddenMembershipID').val(membershipid);
if (data["MembershipGroundLevel"] == true)
{
alert("True");
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
}
else
{
alert("false");
$("#RowTimeFrame").show("slow");
$("#RowMinFrame").show("slow");
var storeid = $("#ddlStore").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetTimeFrame","User")',
data: { 'StoreID': storeid },
success: function (data) {
$("#TxtTimeFrame").val(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
},
error: function (data) {
alert(JSON.stringify(data));
}
})
$("#myModalUpdate").modal('show');
});
If condition is working well, but Div(s) doesn't hide
If I remove $(self).closest() from second div, first div hides all well, Issue is with multiple div
You can use class to hide it, like this:
$(".resetValueTo0").val(0);
$(".divToHide").hide();
Therefor, you don't need to do this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
You might want to try this:
Replace this code:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
To this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").each(function(){
$(this).hide();
});
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").each(function(){
$(this).hide();
});

AJAX reloads the page without inserting into database

I am new to Ajax and confused. The problem is the ajax reloads the page. The function mentioned in the url inserts the data into database. but the page reloads. I guess the URL is not working but i am not sure on this.
Here is my Controller Function
public function insert_student_fee_payment()
{
$std_code=$this->input->post('std_code');
$total_fee=$this->input->post('total_fee');
$payable_fee=$this->input->post('payable_fee');
$date=date('Y m d');
$class_detail=$this->db->select('class.class_year,class.class_semester')
->join('class','class_student.class_id=class.class_id','LEFT')
->where('class_student.student_id',$std_code)
->where('class_student.class_student_status',2)
->limit(1)
->get('class_student')
->result();
if(count($class_detail)>0)
{
foreach($class_detail as $cd)
{
$year=$cd->class_year;
$semester=$cd->class_semester;
}
}
$data=array(
'std_code'=>$std_code,
'year'=>$year,
'semester'=>$semester,
'total_fee'=>$total_fee,
'payable_fee'=>$payable_fee,
'date'=>$date,
'status'=>2
);
if($this->db->insert('student_fees',$data))
{
echo '1';
}
}
and here is my Ajax code in form
<script type="text/javascript">
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '<?php echo base_url()."index.php/finance/insert_student_fee_payment;?>',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
});
});
any help guys
We don't see the HTML so it's hard to say what's wrong but my guess is that $('#insert_fee_payment') is a submit button so you have to cancel the action by default which is submitting the form.
$('#insert_fee_payment').click(function(e){
e.preventDefault();
};
or
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
return false;
});
Add return false after the error function.
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
return false;
});
});
});

Ajax Request Loop and Wait Until Complete

Is there a more efficient way to write the following? I need to loop through objList and pass the UnqKey to wfrmPrint. On success of that I then have to loop though the Pages. I am looping through the pages and unqkeys by passing a integer and checking to see if it is less than the length. I tried to use .when.apply taken from http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects, but it was loading the unqkeys and then the pages.
//sample objList
[
{
"UnqKey": 1,
"Pages": [
"wfrmSet1Page1.aspx",
"wfrmSet1Page2.aspx"
]
},
{
"UnqKey": 2,
"Pages": [
"wfrmSet2Page1.aspx",
"wfrmSet2Page2.aspx",
"wfrmSet3Page2.aspx",
"wfrmSet4Page2.aspx"
]
}
]
function Loop(iListIndex) {
var obj = objList[iListIndex];
if (iListIndex < objList.length) {
jQuery.ajax({
type: "GET",
url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + obj.UnqKey, //load session that is used in wfrmSet1Pages.. or wfrmSet2Pages..
success: function () {
AddPages(obj, iListIndex, 0);
}
})
} else {
alert('Done');
}
}
function AddPages(obj, iListIndex, iPageIndex) {
if (iPageIndex < obj.Pages.length) {
jQuery.ajax({
type: "GET",
url: obj.Pages[iPageIndex] + '?Print=1', //load html
async: true,
success: function (html) {
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
},
error: function () {
alert('Failed!');
iPageIndex++
AddPages(obj, iListIndex, iPageIndex);
}
});
} else {
iListIndex++
Loop(iListIndex);
}
}
You might be able to do something like this,
function getData(arr,arrindex) {
$.ajax({
type: "GET",
url: 'wfrmPRINT.aspx?action=LoadSession&UnqKey=' + arr[arrindex].UnqKey
}).then(function(data){
var deferredObj = $.Deferred(), defArr = $.map(arr[arrindex].Pages,function(page){
return $.ajax({type: "GET", url: page + '?Print=1'});
});
$.when.apply(null,defArr).done(deferredObj.resolveWith).fail(deferredObj.resolveWith);
return deferredObj.promise();
}).done(function(){
arrindex++;
if (arr[arrindex]) {
getData(arr,arrindex);
}
else {
alert("done!");
}
}).fail(function(){
alert("FAIL!");
});
}
getData(objList,0);
It gets each wfrm sequentially, and when each one finishes, requests all of the pages for that one at once. Somewhat of a combination between your loop and a deferred $.when
Edit: fixed $.map argument order

Categories

Resources