Multiple instance jquery function with bootstrap modal - javascript

I am trying to run jquery function once modal is shown, but I close modal by clicking on the side or one close button and then open I find multiple instances of the inner function running.
<script type="text/javascript">
$(document).ready(function () {
$(".test").click(function () {
var cid = $(this).attr('cid');
$("#post-form").one('submit',function (event){
event.preventDefault();
$.ajax({
url: '{% url 'create_request' %}',
type: 'POST',
data: {
'cid': cid,
'req_num' : $('#request_number').val(),
},
success: function (data) {
console.log("success")
if (data['request']=='0')
{
alert("Request is already there");
}
else if(data['request']=='1')
{
alert("Not enough components:(");
}
$("#exampleModal").modal('hide');
}
})
})
})
})
</script>
test is the class given to button which opens bootstrap modal
post-form is the id given to my form

Attach the submit event listener outside the click function, otherwise you will create one listener per click.
$(document).ready(function () {
$("#post-form").one('submit',function (event){
event.preventDefault();
$.ajax({
url: '{% url 'create_request' %}',
type: 'POST',
data: {
'cid': cid,
'req_num' : $('#request_number').val(),
},
success: function (data) {
if (data['request']=='0')
{
alert("Request is already there");
}
else if(data['request']=='1')
{
alert("Not enough components:(");
}
$("#exampleModal").modal('hide');
}
})
})
})
This will of course break the context for this in $(this).attr('cid');, so you will have to update that to reflect the changes. I'd suggest placing it inside a hidden field in your form, or as an attribute to your modal, whatever is more convenient.

Related

jQuery Ajax submitting form multiple times

I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.
Here's my Ajax code :
$(document).ready(function () {
var id_js;
$(document).on('click', '.btn-success', function () {
id_js = $('#ID_TXT').val();
$('form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
return false;
});
});
});
Also I have tried .one() and .stopImmediatePropogation() but still no results
I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.
I hope this works well for you.
$(document).ready(function () {
function postDataToServer() {
var id_js = $('#ID_TXT').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
}
$(document).on('click', '.btn-success', postDataToServer);
});
The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.
If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.
$(document).ready(function() {
var id_js;
$(document).on('click', '.btn-success', function() {
id_js = $('#ID_TXT').val();
});
$('form').submit(function(e) {
if (id_js !== undefined) {
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function(response) {
$('#result').html(response);
}
});
} else {
alert("You need to click on the success button first");
}
return false;
});
});

How to check a form is submitted or other links are clicked in jquery?

Currently i have a $(window).unload function which do some tasks on leaving that page. but i need these actions to be done only if a form is not submitted. This is what i have done so far`
$(window).unload(function () {
var flag=0;
$("#id-message-form").submit(function(){
flag=1;
});
if(flag!=1){
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
async: false,
data:{},
beforeSend: function() {
},
complete: function() {
},
success: function(data) {
}
});
}
});`
You could set a flag when a form is submitted - and then check that in your unload function.
// Set this globally
var formSubmit = false;
$('form').on('submit', function() {
formSubmit = true;
}
Then in your window unload function;
if(!formSubmit) {
// your code that submits the form
}
The issue is due to the scope of the flag variable and the submit handler. Place them outside the unload handler. I'd also suggest changing flag to a boolean value.
var formSubmitted = false;
$("#id-message-form").submit(function() {
formSubmitted = true;
});
$(window).unload(function() {
if (!formSubmitted) {
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
data: {},
async: false,
beforeSend: function() {},
complete: function() {},
success: function(data) {}
});
}
});
The submit() will no matter submit the form by default. You should try click() function to store flag value instead.

Open Javascript Id on a new window

Am trying to open an id on a new window, this is my code:
<script type="text/javascript">
$(document).ready(function () {
$('.myButton').click(function () {
$.ajax({
type: "GET",
url: $(this).parent().data("url"),
data: { callNumber: $(this).parent().data("callno") },
success: function (data) {
$("#CallDetail").html(data);
},
});
});
});
</script>
When i click .myButton class it opens the id:
<div id="CallDetail"></div>
thats located on the home page.
What i need is to open on a new window, i have tried doing this via the link :
<div data-callno='#parts.Call_Num' data-url="#Url.Action("GetCallInfo", "CallHandling" , new {target = "_blank"})">
<div class="myButton toolbarIcon">
<div class="toolbarIconText">View</div>
</div>
But no luck, at the moment it just opens in the same page i am doing this, the problem is am getting data called in the JavaScript so its trickier then i imagined. any ideas?
You can use jQuery's .find to search the returned HTML for a selector:
$(document).ready(function () {
$('.myButton').click(function () {
$.ajax({
type: "GET",
url: $(this).parent().data("url"),
data: { callNumber: $(this).parent().data("callno") },
success: function (data) {
$(data).find('#CallDetail');
},
});
});
});

New Javascript being loaded but old Javascript being called. MVC

I have 3 partial views with JS using JQuery in each to post a form and open a new partial view when the form is posted.
What I am finding is that the first time the JS fires it works fine but if I then go to post the form on the new page, I calls the function from the previous page.
The code:
$('#selector').click(function (e) {
var actionName = $(this).attr("id")
e.preventDefault();
e.stopImmediatePropagation();
alert("page1 js being called")
$('#page1Form').submit(function () {
$.ajax({
url: 'Dashboard/Page1/',
data: $(this).serialize(),
type: 'POST',
success: function () {
$.ajax({
url: 'Dashboard/LoadPartial',
data: { viewName: actionName },
type: 'GET',
success: function (d) {
$('#partial').html(d);
}
});
},
});
});
$('#page1Form').submit();
});
The second partial view has a function the same as that but only with the relevant selectors etc and for some reason the previous pages JS is being called as the alert alert("page1 js being called") is appearing in the browser!
Thanks in advance.
If you're loading partial views that means the entire page isn't being refreshed, and as a result the already loaded scripts will still be there. You'll need to remove the event handlers that correspond to the page1 content before adding the new content in:
$.ajax({
url: 'Dashboard/LoadPartial',
data: {
viewName: actionName
},
type: 'GET',
success: function (d) {
$('#selector').off('click'); // remove the click event handler
$('#page1Form').off('submit'); // remove the submit event handler
$('#partial').html(d); // add your new content
}
});

Script doesn't take effect on element recently created [duplicate]

This question already has answers here:
jQuery how to bind onclick event to dynamically added HTML element [duplicate]
(9 answers)
Closed 10 years ago.
I have created two scripts for managing a list. One for adding a li element in the page and saving it to the database, and the other one, for removing it. The fact is, when I create a li element, the second script (remove one), doesn't take effect on it (I must update the page to remove it). How can I make it work?
I leave you both scripts:
Adding:
function afegir() {
var fnom=document.getElementById('compranom').value;
var fnum=document.getElementById('quantitat').value;
$.ajax({
data: {
"nom": fnom,
"num":fnum
},
url: 'afegir.php',
type: 'post',
beforeSend: function () {
},
success: function (response) {
if(response!="-1") {
$('.llista').append('<li value="'+fnum+'" id="'+response+'" >'+fnom+'</li>');
}
else{
alert('Error');
}
}
});
}
Removing:
$(document).ready(function(){
$(".list li").click(function() {
var fid=$(this).attr('id');
$.ajax({
data: {
"id": fid
},
url: 'treure.php',
type: 'post',
beforeSend: function () {
},
success: function (response) {
if(response=="si") {
$("#"+fid+"").remove();
}
else{
alert('Error');
}
}
});
});
});
Thank you for your help.
use on event delegation for this..
$(document).ready(function(){
$(".list").on('click','li',function() {
var fid=$(this).attr('id');
$.ajax({
data: {
"id": fid
},
url: 'treure.php',
type: 'post',
beforeSend: function () {
},
success: function (response) {
if(response=="si") {
$("#"+fid+"").remove();
}
else{
alert('Error');
}
}
});
});
});
link here to read more about on delegated event
Can use live() for getting to newly created elements: http://api.jquery.com/live/
Description: Attach an event handler for all elements which match the current selector, now and in the future.

Categories