My Ajax form is submitting twice for some reason even using preventDefault() and return false.
<script type="text/javascript">
$("#form_codes").submit(function(e) {
e.preventDefault();
$.ajax({
data: $('#form_codes').serialize(),
type: 'POST',
url: '{{url('save_code')}}',
success: function(msg) {
$('#product_codes > tbody:last-child').append('<tr><td>' + $('#code').val() + '</td><td>' + $('#description').val() + '</td></tr>');
$('#code').val('');
$('#description').val('');
},
error: function(msg) {
}
});
return false;
});
</script>
Try adding e.stopImmediatePropagation() to the submit event, as it prevents every other event from executing so this may stop the second form submit.
<script type="text/javascript">
$("#form_codes").submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
data: $('#form_codes').serialize(),
type: 'POST',
url: '{{url('save_code')}}',
success: function(msg) {
$('#product_codes > tbody:last-child').append('<tr><td>' + $('#code').val() + '</td><td>' + $('#description').val() + '</td></tr>');
$('#code').val('');
$('#description').val('');
},
error: function(msg) {
}
});
return false;
});
</script>
Turns out in my blade template engine i was yielding my script twice (effectively including it twice.)
The function works fine and only submits once now.
Related
I am trying to get the value from the Kendoui Checkbox but without success so far.
<input type="checkbox" id="telephonyeq1" name="telephonychk[]" class="k-checkbox telephonycb">
The script
<script>
if($('#telephonyeq1').is(":checked"))
{
var telephonycb = "true"
}
else {
var telephonycb = "false"
}
</script>
when i am POST the data through AJAX i am always receiving value as "False", even if it's checked or unchecked.
Telephony: false
And the Ajax
$("#save").click(function() {
$.ajax({
url: "/test",
method: "post",
data: {
.....
"telephonycb": telephonycb,
"internetcb": internetcb,
"_token": "{{ csrf_token() }}"
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg(data.success);
} else{
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg (msg) {
......
}
function printSuccessMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','none');
$(".print-success-msg").css('display','block');
$("h5 span").html(
'<br /><h5><strong>Incident Description</strong>
.......
'</code><br /><h5><strong>Impact on Services</strong></h5>Telephony: <code>' + telephonycb + '</code> Service Issues <code>' + telephony.value() + '</code> - Affected Users: <code>' + telephonyaffected.value() +
'</code><br />Internet: <code>' + internetcb + '</code> Service Issues <code>' + internet.value() + '</code> - Affected Users: <code>' + internetaffected.value() +
......
);
}
});
</script>
update the line inside the ajax
"telephonycb": (($('#telephonyeq1:checked').length > 0) ? "true ": "false"),
If what you are trying is sending the value telephonycb through Ajax, it's always going to be false.
The script you have is executed only once at load time. If you want to keep the variable, you can add the function change so it updates the variable when you click the box.
Example:
$('#telephonyeq1').change(function(){
if($('#telephonyeq1').is(":checked"))
{
var telephonycb = "true"
}
else {
var telephonycb = "false"
}
});
I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.
I have a textarea field where some data already exist
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="message" id="editor1">There is some lines with basic html tags like strong,underline</textarea>
If I change above to like this
<textarea name="message" id="editor1">Some new lines with basic html tags like strong,underline</textarea>
But after submit action Everything works fine but I always get old textarea data not new updated data.
While js code
$(document).on('click', ".send-mail", function (e) {
e.preventDefault();
var s_message=$("textarea[name=message]").val();
$('#send_mail').modal({backdrop: 'static', keyboard: false}).one('click', '#sendmail', function () {
sendMail(s_message);
});
});
function sendMail(s_message) {
jQuery.ajax({
url: 'request/sendmail.php',
type: 'POST',
data: s_message,
dataType: 'json',
success: function (data) {
if (data.status == "Success") {
$("#notify .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#notify").removeClass("alert-danger").addClass("alert-success").fadeIn();
$("html, body").scrollTop($("body").offset().top);
} else {
$("#notify .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#notify").removeClass("alert-success").addClass("alert-danger").fadeIn();
$("html, body").scrollTop($("body").offset().top);
}
}
});
}
</script>
I need new updated data to a PHP Post variable. Why it is not working?
I have a button, that is created by jquery after success of ajax call.
I wanted to change its background-color also by jquery but it doesn't work at all.
What is interesting, I have tried to add exactly the same button outside of the script, in html area and it works fine. How to deal with it?
<script>
$(".submitInput1").click(function() {
event.preventDefault();
$(".toBanList").html("");
$.ajax({
type: "GET"
url: "/searchFriendsToBlock",
dataType: "json",
data: {
},
success: function(msg) {
for (var i = 0; i <= msg.length; i++) {
$(".banSearchResultList").append("<li class='toBanList'><img class='avatarImage' src='" + msg[i]['avatar'] + "'>" + msg[i]['login'] + "<br>" + msg[i]['first_name'] + " " + msg[i]['last_name'] +
"<button class='blockButton2' style='background-color:blue'>Block user</button>\n\
<button class='blockButton1' style='background-color:blue'>Block chat</button></li>");
}
}
});
});
</script>
<script>
$(".blockButton1").click(function() {
$(".blockButton1").css("background-color", "red");
$(".blockButton1").attr("background-color", "red");
})
</script>
I belive the problem is that click() only works on elements that exist in the DOM when you register the handler. Try using on() instead: http://api.jquery.com/on/
In your example:
$(".banSearchResultList").on('click','.blockButton1',function() {
$(this).css("background-color", "red");
});
You will need to use event delegation, since the button is created dynamically, using the on method as follows :
$(".banSearchResultList").on("click", ".blockButton1", function() {
$(this).css("background-color", "red");
})
please use this
$("body").on('click', '.blockButton1', function(e) {
$(this).css("background-color", "red");
});
<script>
$(".submitInput1").click(function() {
event.preventDefault();
$(".toBanList").html("");
$.ajax({
type: "GET"
url: "/searchFriendsToBlock",
dataType: "json",
data: {
},
success: function(msg) {
for (var i = 0; i <= msg.length; i++) {
$(".banSearchResultList").append("<li class='toBanList'><img class='avatarImage' src='" + msg[i]['avatar'] + "'>" + msg[i]['login'] + "<br>" + msg[i]['first_name'] + " " + msg[i]['last_name'] +
"<button class='blockButton2' style='background-color:blue'>Block user</button>\n\
<button class='blockButton1' style='background-color:blue'>Block chat</button></li>");
}
// Adding this line of code.
$(".blockButton1").on('click',function() {
$(".blockButton1").css("background-color", "red");
});
// End
}
});
});
</script>
You have to add commented block of code in success of ajax call otherwise it will not work. Because the syntax I used it only work if your selector is exist in your DOM.
I have an ajax function, which submits the data and refreshes the div after the data has been updated. The problem is that the jQuery elements within the div breaks after the form has been submitted, and the div has been refreshed.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit" ,function(){
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function(msg){
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(function() {
$('a[id^="teamname"]').editable({
ajaxOptions : {
type : 'post'
}
});
});
$(document).ready(function() {
$('select[id="swap"]').change(function(){
$( "#saveprogress" ).show("fade");
});
});
You need to use event delegation to support dynamically added elements also you need to initialize the plugin again once the div is refreshed
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
tournamentid = getURLParameter('id');
$(document).ready(function () {
$(document).on('click', "button#submit", function () {
$.ajax({
type: "POST",
url: "test.php?page=tourneys&id=" + tournamentid + "&action=teams&submit=true", //process to mail
data: $('#swapteams').serialize(),
success: function (msg) {
createNoty('The teams has been updated!', 'success');
// Refresh the div after submission and pass a callback which will initialize the plugins
$("#refresh").load("test.php?page=tourneys&id=" + tournamentid + "&action=teams #refresh", createEditable);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
});
});
// the plugins and jQuery variables within the refresh div
$(document).ready(createEditable);
function createEditable() {
$('a[id^="teamname"]').editable({
ajaxOptions: {
type: 'post'
}
});
}
$(document).ready(function () {
//use event delegation
$(document).on('change', 'select[id="swap"]', function () {
$("#saveprogress").show("fade");
});
});