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', './');
});
Related
<script>
$(document).ready(function () {
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data).trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>
Above is my code to generate district based on state, and it works fine. I just want set the value what is selected by user. At present the selected value is cleared after selecting a state and submit.
You can use a global to hold selected value
var selectedDistrict = 0;
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
then do:
$("#district")
.html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
in your ajax success.
Means your code will become:
<script>
var selectedDistrict = 0;
$(document).ready(function () {
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>
enter link description hereI have following jquery ajax,which includes page into div after click on cells:
$(function () {
$('.yo').click(function (e) {
e.preventDefault();
var value = $('#prodajx').val();
var value1 = $('#cityajx').val();
var value2 = $('#regionajx').val();
$.post('demo_link_table_static.php', {value: value, value1: value1, value2: value2}, function (data) {
$("#search_results").html(data);
});
return false;
});
});
Now I want id of td in ajax post method... How can I get id of td (after click) and post it to another page? Thank you.
$(function () {
$('.yo').click(function (e) {
e.preventDefault();
var value = $('#prodajx').val();
var value1 = $('#cityajx').val();
var value2 = $('#regionajx').val();
var id_td = $(this).attr('id');
$.ajax({
url: "demo_link_table_static.php",
type: "POST",
data : "id_td="+id_td+"&value="+value+"&value1="+value1+"&value2="+value2,
success:function(data){
$("#search_results").html(data);
}
});
return false;
});
});
var id_current = $(this).attr('id');
var id_0 = $('#prodajx').attr('id');
var id_1 = $('#cityajx').attr('id');
var id_2 = $('#regionajx').attr('id');
I'm tryng to set up a panel, this one
The menu on the top calls different ajax functions in order to display a thumb. Clicking on the thumb you can see the details in the last box of the panel.
I have this php functions
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
function GetPostEnte(){
$catEnte = "loop_pb_ente";
get_template_part($catEnte);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostEnte', 'GetPostEnte');
function GetPostColl(){
$catColl = "loop_pb_coll";
get_template_part($catColl);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostColl', 'GetPostColl');
function GetPostMedia(){
$catMedia = "loop_pb_media";
get_template_part($catMedia);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostMedia', 'GetPostMedia');
function GetPostDetails(){
$pb_details = $_POST['postURL'];
get_template_part($pb_details);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostDetails', 'GetPostDetails');
And those are called by these ajax functions
$(document).delegate('h4.homus-partners-global-ajax[data-pb- cat*=pb_partner]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_partner";
var data = {
'action': 'GetPostPartner',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_ente]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_ente";
var data = {
'action': 'GetPostEnte',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_coll]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_coll";
var data = {
'action': 'GetPostColl',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_media]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_media";
var data = {
'action': 'GetPostMedia',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('li.homus-partners-section-single', 'click', function(event) {
event.preventDefault();
var pb_post_id = $(this).data('post-id');
var data = {
'action': 'GetPostDetails',
postURL : "single_pb_post_details",
post_id: pb_post_id
};
$.post(ajaxURL, data, function(response) {
$( '.homus-partners-detalis' ).html(response);
console.log(pb_post_id);
console.log(data.postURL);
console.log(response);
});
});
the response that I have is always 0 even if the console of the last ajax call here above return the right postid. You can find the whole project in this repo
https://github.com/wanbinkimoon/homus-web.git
in the code
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
instead of including the file by get_template_part paste the code here and then try
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
Problem: New Inserted Dom elements aren't been wired correctly, function deletepost not firing. This happens only on IE and for new elements only added to DOM.
$(function(){
$('#postentry').submit(function() {
var tyu = $('#tittle_ent').val();
if(tyu.length <= 2)
{alert('Enter More Text!'); return false;}else
{
$.ajax({
type:'post',
url: '/posts_in.php',
dataType: "json",
data: $("#postentry").serialize(),
success:function(data){
var tittle = data[0];
var id= data[1];
$('<div></div>').attr('id','post'+id).addClass('boxee').html(tittle).prependTo('#boxer');
$('<img src="img/page-text-delete-icon.png" name="'+id+'">').attr({id:'postchk'+id,onclick: 'deletepost(this.name);'}).appendTo('#post'+id);
$('#tittle_ent').val('').focus();
}
});
return false;
}
});
});
Use jquery live
$(function(){
$("#boxer img").live("click", function(){
deletepost($(this).attr("name"));
});
$('#postentry').submit(function() {
var tyu = $('#tittle_ent').val();
if(tyu.length <= 2)
{alert('Enter More Text!'); return false;}else
{
$.ajax({
type:'post',
url: '/posts_in.php',
dataType: "json",
data: $("#postentry").serialize(),
success:function(data){
var tittle = data[0];
var id= data[1];
$('<div></div>').attr('id','post'+id).addClass('boxee').html(tittle).prependTo('#boxer');
$('<img src="img/page-text-delete-icon.png" name="'+id+'">').attr({id:'postchk'+id,onclick: 'deletepost(this.name);'}).appendTo('#post'+id);
$('#tittle_ent').val('').focus();
}
});
return false;
}
});
});
'onclick' is ancient/oldschool stuff, especially when using jquery. Try this variant instead:
$('<img src="img/page-text-delete-icon.png" name="'+id+'">')
.attr('id', 'postchk'+id)
.click(function () { deletepost(this.name); }) /// use .click() instead.
.appendTo('#post'+id);
Yeah , You must used jQuery live() function, the more detail example can be found here http://developerfaq.wordpress.com/2011/07/28/fire-event-on-dynamically-generated-dom-element-with-jquery/