jquery key up firing multiple time - php

i have this code:
$("#search").keydown(function (e) {
var str = $(this).val();
alert(str);
var url = $("#url").val() + "?ajax=true&q=" + str;
$("#tableWrap").load(url, function () {});
});
#search is id of a textbox that filter information shown in a table. when i type in that for first key the function is firing one time . when i type second key in it the function is firing two time ... .any idea?
Edit:all code.
$(document).ready(function(){
// $("#search").val("جست و جو...");
$("#search").live('click', function(){
$(this).val("");
});
$("#search").keyup(function (e) {
var str = $(this).val();
alert(str);
var url = $("#url").val() + "?ajax=true&q=" + str;
$("#tableWrap").load(url, function(){
});
});
/* $("#search").live('keyup', function(){
var str = $(this).val();
var url = $("#url").val() + "?ajax=true&q=" + str;
$("#tableWrap").load(url, function(){
// $("#search").focus().val(str);
});
});*/
$(".pg_class a").live('click',function(){
showLoading();
$("#load").fadeIn("slow");
loadAJAX(this+"&ajax=true");
return false;
});
$("#tableWrap th").live('click',function(){
showLoading();
$("#load").fadeIn("slow");
loadAJAX($(this).children("a").attr("href") + "&ajax=true");
return false;
});
$("#tableWrap th a").live('click',function(){
showLoading();
$("#load").fadeIn("slow");
//alert($(this).attr("href"));
// alert("salam");
loadAJAX($(this).attr("href") + "&ajax=true");
return false;
});
$(".header select").live('change',function(){
showLoading();
$("#load").fadeIn("slow");
var pageSize = $('.header select option:selected').text();
var url = $('.header select').val();
// alert(url+pageSize+"&ajax=true");
loadAJAX(url+pageSize+"&ajax=true");
});
});
</script>

for future.
i solve the problem with this:
jQuery("#search").one("keyup", function (e) {
var str = $(this).val();
var url = $("#url").val() + "?ajax=true&q=" + str;
$("#tableWrap").load(url, function(){
});
});

Related

Hide data in url when using window.open in jquery

i was performed onclick to download pdf in below there is my jQuery code
$("#mlt_voucher").on("click", function () {
var checkedId = [];
var deduction = $('#dynamicmodel-deduction_type').val();
// alert(deduction);
$.each($("input:checkbox[class=chkItem]:checked"), function(){
checkedId.push($(this).attr("id"));
});
window.open('$deductiondown?checkedId='+checkedId+'&deduction='+deduction, '_blank');
});
there is the url look like
http://localhost/fads/admin/master-beneficiary/deductiondown?checkedId=29155,29152&deduction=1
i want hide my data in that url what can i do for that ?
and also i don't want to use that code in below
$("#mlt_voucher").on("click", function () {
var checkedId = [];
var deduction = $('#dynamicmodel-deduction_type').val();
alert(deduction);
$.each($("input:checkbox[class=chkItem]:checked"), function(){
checkedId.push($(this).attr("id"));
});
$.post(
'$deductiondown',
{ checkedId:checkedId,deduction:deduction},
// function(response){
// // console.log(response);
// location.reload();
// }
);
});

Simple php ajax pagination, how to get request url

UPDATE 2 18.05.2020
(AJAX) URL pagination on refresh + window.history.replaceState + window.history.pushState +location.pathname
After refresh Test3
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$('#load_data').html('<div id="status" style="" ></div>');
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#load_data').html(data);
}
});
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
//Now push PAGE to URL
window.history.pushState({page}, `Selected: ${page}`, `${ 'page=' + page}`)
//window.history.pushState({page}, `Selected: ${page}`, `./selected=${page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
//history.replaceState({page: null}, 'Default state', './');
var params = new URLSearchParams(location.search);
params.set('page');
window.history.replaceState({}, "", decodeURIComponent(`${location.pathname}?${params}`));
});
I've built a PHP AJAX pagination that works -> ajax pagination.
I'm new to jQuery/ajax. I am not able to understand the usage the url parameter.
My output: pagination2.php
I want the output: pagination2.php/page=2,3,4....
Any ideas?
My code index.php
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$('#load_data').html('<div id="status" style="" ></div>');
var action = 'pagination2';
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
complete: function(){
alert(this.url)
},
success: function(data){
$('#load_data').html(data);
},
})
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
return event.preventDefault();
});
});
pagination2.php
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
UPDATE1
I added: history.pushState but I don't know if this method is correct. I can manipulate next - back /selected=2, selected=3... But, another problem arises, after refresh selected disappears. Test 2
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$('#load_data').html('<div id="status" style="" ></div>');
var action = 'pagination2';
$.ajax({
url:"pagination2.php",
method:"POST",
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
data:{page:page},
success:function(data){
$('#load_data').html(data);
},
})
}
$(document).on('click', '.pagination_link', function(event) pagination
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
history.pushState({page}, `Selected: ${page}`, `./selected=${page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
history.replaceState({page: null}, 'Default state', './');
});

How to make dynamically add or remove button

When I click add button, it is changed remove button. But I can not change remove button to add button again, When I click remove.
<head>
<script type="text/javascript" src="assets/js/jquery-2.0.3.min.js"> </script>
<script type="text/javascript" >
$(document).ready(function()
{
$(".add").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#" + I).attr("class", "remove");
$(".remove").text("Remove");
return false;
});
});
</script>
<script type="text/javascript" >
$(document).ready(function()
{
$(".remove").click(function(){
var element = this.id;
var I = element.attr("id");
var info = 'id=' + I;
$("#" + I).attr("class", "add");
$(".add").text("add");
return false;
});
});
</script>
<a class="add" id="1" href="#"> Add </a>
When you modify DOM elements with jQuery, anything that is loaded within $(document).ready() won't recognize the change. What you can do is wrap each step in a function, call these on document.ready, then call each again at the end of the other function:
<script type="text/javascript" >
$(document).ready(function()
{
addFunction();
removeFunction();
});
function addFunction(){
$(".add").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#result").text(I);
$("#" + I).attr("class", "remove");
$(".remove").text("Remove");
removeFunction();
return false;
});
}
function removeFunction(){
$(".remove").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#result").text(I);
$("#" + I).attr("class", "add");
$(".add").text("add");
addFunction();
return false;
});
}
</script>
You have both functions listed in document.ready, so you can't attach an event handler to the .remove class since it doesn't exist yet. I would suggest using delegated events:
$( ".LocationOfYourButtonInTheDom" ).on( "click", "ThingBeingClicked", function() {
//code here
});
Edit:
ThingBeingClicked would be the type of DOM object triggering the event, in your case this would be an "a" tag
You can read more about events and delegation from the jquery "on" documentation.

emulate jquery trigger on angularjs

i have a angular application and on controller init i have a jquery event that open a lightbox (Custombox), i need that i close this box run other angular controller that update cart items from php session the code is
aplicacion.controller("fichaTec",["$scope","$http","$stateParams","$sce","locaciones","carrito", function($scope,$http,$stateParams,$sce,locaciones, carrito){
//$scope = $scope.$new(true);
$scope.destino = $stateParams.path;
$scope.path=$stateParams.nad;
jqueryUtilities();
$scope.init=function(destino,nado){
jq(document).on("click","#openReserva", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var $value=jq(e.target).attr("data-value").split(",.-");
var $valueDes = $value[1];
$value=$value[0];
Custombox.open({
target: 'pages/reservaTour.php',
effect: 'blur',
cache:false,
overlayOpacity:0.7,
position:["center","center"],
loading:{
delay:6000,
parent:['sk-chasing-dots'],
childrens:[
['sk-dot1','sk-child'],
['sk-dot2','sk-child'],
]
},
complete:function(e){
jqueryUtilities();
var hoy = new Date();
jq('#dateReserva').datetimepicker({
format:"DD-MM-YYYY",
locale:'es',
minDate:hoy.setDate(hoy.getDate()+2),
//daysOfWeekDisabled:dias
});
jq("#locacionesReserva").selectpicker("val",$valueDes)
jq(document).on("change","#locacionesReserva",function(e,value){
e.preventDefault();
e.stopImmediatePropagation();
jq("#errLocacionesCR").fadeOut();
var valDes= jq(this).prop("value");
jq.ajax({
url:"_assets/_controllers/getNadosSelect.php",
type:"POST",
dataType:"JSON",
data:{ destino: valDes }
}).done(function(data){
jq("#programa").find("option").remove();
var element=data;
jq("#programa").append(jq("<option></option>").attr("value","0").text("Seleccione"));
for(var i=0; i<element.length; i++)
{
jq("#programa").append(jq("<option></option>").attr("value",element[i].clave).text(element[i].nombre));
}
jq("#programa").selectpicker('refresh');
jq("#programa").selectpicker('val',value);
});
getDiasInhabiles();
});
jq(document).on("change","#programa",function(e){
e.preventDefault();
e.stopImmediatePropagation();
jq("#errProgramaCR").fadeOut();
var destino = jq("#locacionesReserva").prop("value");
var nado=jq("#programa").prop("value");
//alert("des "+destino+" nado "+nado);
jq.ajax({
url:"_assets/_controllers/getNadosHorasSelect.php",
type:"POST",
dataType:"JSON",
data:{ destino: destino, nado:nado }
}).done(function(data){
jq("#hora").find("option").remove();
var element=data;
jq("#hora").append(jq("<option></option>").attr("value","0").text("Seleccione"));
for(var i=0; i<element.length; i++)
{
jq("#hora").append(jq("<option></option>").attr("value",element[i].hora).text(element[i].hora));
}
jq("#hora").selectpicker('refresh');
});
getDiasInhabiles();
});
jq(document).on("change","#hora",function(e){
e.preventDefault();
e.stopImmediatePropagation();
jq("#errHoraCR").fadeOut();
getDiasInhabiles();
});
jq(document).on("dp.change","#dateReserva",function(e){
e.preventDefault();
e.stopImmediatePropagation();
//alert(jq("#fechaServ").prop("value"));
if(jq("#fechaServ").prop("value")!=""){
jq("#errFechaCR").fadeOut();
}
});
jq(document).on("change","#adultosRev",function(e){
e.preventDefault();
e.stopImmediatePropagation();
if(jq(this).prop("value")!=0){
jq("#errAdultosCR").fadeOut();
}
});
jq(document).on("click","#botonAddReserva",function(e){
e.preventDefault();
e.stopImmediatePropagation();
var band = true;
var $nado = jq("#programa").prop("value");
var $destino = jq("#locacionesReserva").prop("value");
var $fechaServ = jq("#fechaServ").prop("value");
var $hora=jq("#hora").prop("value");
var $adultos=jq("#adultosRev").prop("value");
var $ninos=jq("#ninosRev").prop("value");
//alert($nado+" - "+$destino+" - - "+$fechaServ+" -- "+$hora+" - - - "+$adultos+"----"+$ninos);
if($nado==0){
jq("#errProgramaCR").fadeIn().addClass("bg-danger").text("Seleccione nado");
band=false;
}
if($destino==0){
jq("#errLocacionesCR").fadeIn().addClass("bg-danger").text("Seleccione destino");
band=false;
}
if($fechaServ==""){
jq("#errFechaCR").fadeIn().addClass("bg-danger").text("Ingrese fecha");
band=false;
}
if($hora==0){
jq("#errHoraCR").fadeIn().addClass("bg-danger").text("Seleccione hora");
band=false;
}
if($adultos==0){
jq("#errAdultosCR").fadeIn().addClass("bg-danger").text("Seleccione adultos");
band=false;
}
if(band){
jq.ajax({
url:"_assets/_controllers/addCarrito.php",
type:"POST",
data:{
nado:$nado,
destino:$destino,
fecha:$fechaServ,
hora:$hora,
adulto:$adultos,
ninos:$ninos,
}
}).done(function(data){
var dat=data.split(",");
if(dat[0]=="add"){
jq("#mensajeR").css("display","block").addClass("alert-success").text("Se ha agregado el nado");
setTimeout(function(){
//jq("#viewCarrito").trigger("click");
carrito.getTotalItems().then(function(total){
$scope.totalItems=total.total;
});
Custombox.close()
},2500);
}
});
}
});
jq("#locacionesReserva").trigger("change",[$value]);
setTimeout(function(){jq("#programa").trigger("change");},500);
//setTimeout(function(){jq("#")})
},
close:function(e){
e.preventDefault();
e.stopImmediatePropagation();
//i need run other controller or emulate ng-click here
}
});
});
},function(res){console.error("error ",status,data);});
}
$scope.init($scope.destino,$scope.path);
/*carrito.getTotalItems().then(function(total){
$scope.totalItems=total.total;
});*/
}]);
/* here is other controller*/
aplicacion.controller("carritoMenu",["$scope","carrito",function($scope,carrito){
//alert("la funcion es "+carrito.getTotalItems());
$scope.cambio=function(){
carrito.getTotalItems().then(function(total){
$scope.totalItems=total.total;
})
}
}]);
/* factory that return php session value */
aplicacion.factory("carrito",function($q,$http){
var locaciones=null;
var items="";
function getDatos(){
var defer=$q.defer();
$http.get("_assets/_controllers/getLocacionesSelect.php",{cache: "true"}).success(function(res){
//locaciones= res;
//this.resolve();
//console.log(locaciones.length);
defer.resolve(res);
});
return defer.promise;
}
function getTotalItems(){
var defer=$q.defer();
$http.get("_assets/_controllers/getItems.php",{cache: "true"}).success(function(res){
//alert("dkdkkddkdkdk");
defer.resolve(res);
});
return defer.promise;
}
var interfaz={
getLocaciones:getDatos,
getTotalItems:getTotalItems,
//setItems:setItems
}
return interfaz;
});
}
Sorry for my bad english, and if i post bad code (its my first time, please help me ) thank you

Thickbox not getting values of textbox using Jquery

I used thickbox components in Joomla. I am submitting form using jQuery ajax but jQuery not getting values after click on submit buttons. I used
and created script.js file containing :
jQuery(document).ready(function(){
jQuery('.wp_btn').click(function() {
var id = $j(this).attr('id');
var url = $j(this).attr('value');
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery("#dwnlnk").val(url);
TB_show('', '/#TB_inline?KeepThis=true&id=9876asdvfrty54321&height=250&width=350&inlineId=mypopup&caption=Subscription', '');
}else{
window.location = url;
}
});
//
jQuery(document).on('submit', '#subscription',function(){
return false;
});
jQuery(document).on('click', '#btnSubmit',function(){
var url = jQuery('#dwnlnk').val();
var txtname = $j('input[name=txtname]').val();
var txtemail = $j('input[name=txtemail]').val();
jQuery.ajax({
type: 'POST',
url: 'whitepapers/',
data: jQuery('#frmsubscription').serialize(),
success: function(data) {
alert(data);
//if(data == 'true') {
window.location = url;
//}
}
});
});//end click
});
I already tried document.getElementById('txtname').value but its not getting value of textbox. When I entered static value then its getting value.
You have to use jQuery or $ to select an element.
Try this
var txtname = jQuery('input[name="txtname"]').val();
var txtemail = jQuery('input[name="txtemail"]').val();
OR
var txtname = $('input[name="txtname"]').val();
var txtemail = $('input[name="txtemail"]').val();

Categories