Jquery replaceWith in a Foreach loop - javascript

When I execute the below code all the img with the id of imgg will be replaced because they are in a foreach loop, but I want to apply that to the clicked one only. Can any one help?
Html:
<button type="submit" id="getRequest" class="btn btn-info btm-sm " role="button" style="width:100px;height:30px">
<p id="imgg">Add to Cart</p>
</button>
JS:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(imgg).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(imgg).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});

Thanks everyone i found the solution But you da real MVP, here it is
$(document).ready(function()
{
$(document).on('submit', '#reg-form', function()
{
var imgid = $(this).find("#imgg");
var data = $(this).find("#post_id").val();
//var ln = $("#lname").val();
//var data = 'fname='+fn+'&lname='+ln;
// var data = $(this).serialize();
$.ajax({
type : 'POST',
url : '{{url("/ajax")}}',
data: {'name':data, '_token': $('input[name=_token]').val()},
success: function(data) {
$(imgid).replaceWith('<img id=imgg src=img/ajax.gif> ');
var thisForm = this;
setTimeout(function() {
$(imgg).replaceWith(' <p id=imgg>Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error : function(data)
{
alert("You must Login First");
}
});
return false;
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});

Instead of using the $(imgg) use $(this), and you also missed the quotations when you where giving the id of iamge when you where using .replaceWith:
success: function(data) {
$(this).replaceWith('<img id="imgg" src="img/ajax.gif>" ');
var thisForm = this;
setTimeout(function() {
$(thisForm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
Reason?
Simple. The this object doesn't change. It is the owner of the function. See more about why here: Jquery - When to use "this" and when to use "$(this)"?
EDIT2
Now i have to put that in the upper level so this:
$(document).ready(function() {
$(document).on('submit', '#reg-form', function() {
var vm = this //Upper Level
var data = $(this).find("#post_id").val();
$.ajax({
type: 'POST',
url: '{{url("/ajax")}}',
data: {
'name': data,
'_token': $('input[name=_token]').val()
},
success: function(data) {
$(vm).replaceWith('<img id=imgg src=img/ajax.gif> ');
setTimeout(function() {
$(vm).replaceWith(' <p id="imgg">Add to Cart</p> ').hide('blind', {}, 500)
}, 1300);
console.log(data);
},
error: function(data) {
alert("You must Login First");
}
});
return false;
});
});
Please refer here about this particular problem:
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

Related

set Value of select mobius not working javascript

good afternoon, have all of you, I have this problem. I am using selectr mobius1 and when I click to edit data, the "Type of Service" field does not show me the value that it should show me.
my select is initialized like this
$selecttSE = new Selectr("#tipo_SAPIE",{});
I use this onchange so that when a product is chosen the list of services changes
$("#tipo_productoE").on('change', function() {
var tipoprod = $("#tipo_productoE option:selected").val();
var select_servapi = $("#tipo_SAPIE");
$.ajax({
url: '<?= base_url('productos/select_servicios') ?>',
type: 'get',
data: {
tipoprod: tipoprod
},
beforeSend: function(){
$selecttSE.removeAll();
},
success: function(response) {
if (response.length >2 ) {
select_servapi.attr('disabled', false);
$.each(JSON.parse(response), function(i, item) {
$selecttSE.add([{
value: item.servicioapiid,
text: item.alias+' '+item.moneda+''+item.costo}])
});
let select = $("#tipo_SAPIE").parents().children('small')[0];
$(select).empty();
$(select).html('Requerido');
$(select).addClass('badge badge-soft-danger');
} else {
select_servapi.attr('disabled', true);
}
},
});
});
And my function to get the data is this
function getProducto(idproducto) {
var idproducto = idproducto;
$.ajax({
url: '<?= base_url('productos/getProducto') ?>',
type: 'GET',
data: {
idproducto: idproducto
},
success: function(response) {
console.log(response)
$selecttSE.removeAll();
$.each(JSON.parse(response), function(i, item) {
document.getElementById("tipo_productoE").value = item.tipoproductoid;
$("#tipo_productoE").trigger('change');
$selecttSE.setValue(item.servicioapiid);
});
},
error: function(errors) {
},
});
}
Thank you for taking the time to see my post have a great afternoon and much success.

Verification with ajax call

I know it has been answered but since Im ignorant with javascript and ajax, need help. I had found a code for crud operations. My problem is that html verification is not working. When the modal submits the form the required fields in html cannot block the form operation not to be submited. Can anyone help with the script? Here is the code for all operations:
$(document).on('click','#btn-add',function(e) {
var data = $("#user_form").serialize();
$.ajax({
data: data,
type: "post",
url: "save.php",
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$('#modal_task').modal('hide');
alert('Η εργασία καταχωρήθηκε με επιτυχία!');
window.location.reload(true);
}
else if(dataResult.statusCode==201){
alert(dataResult);
}
}
});
});
$(document).on('click','.update',function(e) {
var id=$(this).attr("data-id");
var name=$(this).attr("data-name");
var email=$(this).attr("data-email");
var phone=$(this).attr("data-phone");
var city=$(this).attr("data-city");
$('#id_u').val(id);
$('#name_u').val(name);
$('#email_u').val(email);
$('#phone_u').val(phone);
$('#city_u').val(city);
});
$(document).on('click','#update',function(e) {
var data = $("#update_form").serialize();
$.ajax({
data: data,
type: "post",
url: "backend/save.php",
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$('#editEmployeeModal').modal('hide');
alert('Data updated successfully !');
location.reload();
}
else if(dataResult.statusCode==201){
alert(dataResult);
}
}
});
});
$(document).on("click", ".delete", function() {
var id=$(this).attr("data-id");
$('#id_d').val(id);
});
$(document).on("click", "#delete", function() {
$.ajax({
url: "backend/save.php",
type: "POST",
cache: false,
data:{
type:3,
id: $("#id_d").val()
},
success: function(dataResult){
$('#deleteEmployeeModal').modal('hide');
$("#"+dataResult).remove();
}
});
});
$(document).on("click", "#delete_multiple", function() {
var user = [];
$(".user_checkbox:checked").each(function() {
user.push($(this).data('user-id'));
});
if(user.length <=0) {
alert("Please select records.");
}
else {
WRN_PROFILE_DELETE = "Are you sure you want to delete "+(user.length>1?"these":"this")+" row?";
var checked = confirm(WRN_PROFILE_DELETE);
if(checked == true) {
var selected_values = user.join(",");
console.log(selected_values);
$.ajax({
type: "POST",
url: "backend/save.php",
cache:false,
data:{
type: 4,
id : selected_values
},
success: function(response) {
var ids = response.split(",");
for (var i=0; i < ids.length; i++ ) {
$("#"+ids[i]).remove();
}
}
});
}
}
});
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
var checkbox = $('table tbody input[type="checkbox"]');
$("#selectAll").click(function(){
if(this.checked){
checkbox.each(function(){
this.checked = true;
});
} else{
checkbox.each(function(){
this.checked = false;
});
}
});
checkbox.click(function(){
if(!this.checked){
$("#selectAll").prop("checked", false);
}
});
});

How to remove Local Storage in another JS file

From below case, can someone help me to know how to remove localStorage which i have implemented below :
var serverSelectorDemo = function() {
loadrightdata();
function loadrightdata() {
$('#kt_datatable_fetch_display2').html(localStorage.rightdata);
};
$('#kt_datatable2').on('click','tr button', function() {
var id = $(this).data('id');
$.ajax({
type: 'post',
url: 'src/khu-pusat/compare/right-side/right-value.php',
data: {
'rowid': id
},
success: function(data) {
$('#kt_datatable_nodata2').addClass('hidden');
localStorage.rightdata = data;
$('#kt_datatable_fetch_display2').html(localStorage.rightdata);
return false;
}
});
}).click(function() {
$('#kt_datatable_fetch_display2').empty();
});
};
So far I can't find a way that can do this.

reCAPTCHA: Multiple callbacks doesn't work

I'm creating a login and signup system and to avoid bots, i'm using google recaptcha and i'm trying to use multiple callbacks to send form data to the server via ajax request and this appeared in console:
ReCAPTCHA couldn't find user-provided function: [object Object]
This is the code (the problem is in the line 4):
$(window).on('load',function(){
grecaptcha.render('recaptcha', {
'sitekey' : '6LcFrN8cAAAAAMr2P3Nkvm7fDFzIykf30QykYlga',
'callback' : {onSubmitLogin, onSubmitSignUp},
'size' : 'invisible'
});
});
//Login
$('#login').submit(function (e) {
e.preventDefault();
grecaptcha.execute();
}
);
function onSubmitLogin(token){
var formEmail = $('#email-login').val();
var formPasswd = $('#password-login').val();
var reCaptchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'account.php?action=login',
method: 'POST',
data: {formEmail, formPasswd, reCaptchaResponse},
dataType: 'json',
beforeSend: function() { $('#loading').fadeIn("slow"); },
complete: function() {
$('#loading').fadeOut("slow");
grecaptcha.reset();
},
success: function(response){
if(response.status == 'error'){
$('#alert-container').prepend('<div class="alert ' + response.status + ' showAlert"><div class="alert-content"><i class="fas fa-exclamation-circle"></i><p>' + response.message + '</p></div><button class="alert-close"><i class="fas fa-times"></i></button></div>');
}else if(response.status == 'success'){
window.location = "dashboard";
}
}
})
};
//SignUp
$('#signup').submit(function (e) {
e.preventDefault();
grecaptcha.execute();
}
);
function onSubmitSignUp(token){
var formEmail = $('#email-sign-up').val();
var formPasswd = $('#password-sign-up').val();
var formConfirmPasswd = $('#confirm-password-sign-up').val();
var reCaptchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'account.php?action=create',
method: 'POST',
data: {formEmail, formPasswd, formConfirmPasswd, reCaptchaResponse},
dataType: 'json',
beforeSend: function() { $('#loading').fadeIn("slow"); },
complete: function() {
$('#loading').fadeOut("slow");
grecaptcha.reset();
},
success: function(response){
$('#alert-container').prepend('<div class="alert ' + response.status + ' showAlert"><div class="alert-content"><i class="fas fa-exclamation-circle"></i><p>' + response.message + '</p></div><button class="alert-close"><i class="fas fa-times"></i></button></div>');
}
})
};
why don't you do something like this instead?
grecaptcha.render('recaptcha', {
'sitekey' : '6LcFrN8cAAAAAMr2P3Nkvm7fDFzIykf30QykYlga',
'callback' : () => {
onSubmitLogin();
onSubmitSignUp();
},
'size' : 'invisible'
});

javascript: How to repeatedly call the function itself?

I want to repeatedly count time and update the current time every one minute. My code doesn't work. Firebug console says the final line function getStatus() is not defined. How to call this function repeatedly?
jQuery(document).ready(function($){
$(function() {
getStatus();
});
function getStatus() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url : ajaxurl,
data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
success: function(response) {
if(response == "false") {
alert("failed")
}
else {
$("#message").html(response)
}
}
});
setTimeout("getStatus()",60000);
}
},(jQuery));
your issue is getStatus is wrapped in another callback. either do window.getStatus = function(){}, or turn your code to this:
jQuery(document).ready(function($){
var getStatus = function() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url : ajaxurl,
data : {action: "update_edit_lock", post_id : post_id, nonce: nonce },
success: function(response) {
if(response == "false") {
alert("failed")
}
else {
$("#message").html(response)
}
}
});
setTimeout(getStatus,60000);
};
$(function() {
getStatus();
});
},(jQuery));
Passing a string to setTimeout will make it eval the string, which you should avoid, and generally not required by your code
You could use setInterval(getStatus, 60000) instead perhaps, but otherwise you should use setTimeout(getStatus, 60000). Do not use a string as the function callback but rather the named function.
Use setInterval(function, milliseconds)
jQuery(document).ready(function ($) {
var getStatus = function() {
var post_id = $('#post_id').val();
var nonce = $('#_wpnonce').val();
jQuery.ajax({
url: ajaxurl,
data: {
action: "update_edit_lock",
post_id: post_id,
nonce: nonce
},
success: function (response) {
if (response == "false") {
alert("failed")
} else {
$("#message").html(response)
}
}
});
}
setInterval(getStatus, 1000);
}, (jQuery));

Categories