in_array always returns false? - php

I want to make checked box checked once its checked for that I am pushing filter ids into the array and whichever filter id coming that should be checked In order to this I am getting all filter in $_GET['filter'] but while Am comparing this with $filter array means in_array always returns false please help me out someone
Below is HTML and PHP code,
<?php echo $header;
if(isset($_GET['filter']))
{
$selected_filter[] = explode(",",$_GET['filter']);
print_r($selected_filter);
// $flag = 1;
}
?>
<div class="wrapper">
<?php echo $column_left; ?>
<div class="filterDiv">
<h3>Filters by :</h3>
<!-- <div class="flList">
<p>price</p>
<div class="flDrop price_Module"><div class="flDropDiv">price div</div></div>
</div> -->
<!-- <div class="list-group-item flList filter_options">
<div class="flDrop price_Module"><div class="flDropDiv">price div</div></div>
<span id="amtmin"></span> - <span id="amtmax"></span>
<input type="hidden" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range"></div>
</div> -->
<div class="flList">
<p>Categories</p>
<div class="flDrop">
<div class="flDropDiv category_fl">
<?php foreach ($categories as $category) {
$category_name = explode("(",$category['name'])
?>
<div class="flItems"> <?php echo $category_name[0]; ?> </div>
<?php }?>
</div>
</div>
</div>
<?php //echo "<pre>"; print_r($filter_groups); die; ?>
<?php foreach ($filter_groups as $filter_group) { ?>
<div class="flList">
<p><?php echo $filter_group['name']; ?></p>
<div class="flDrop">
<div class="flDropDiv">
<?php
// $filter_string = "";
foreach ($filter_group['filter'] as $filter) {
// $filter_string = implode(',',$filter['']);
// print_r($filter_string);
if(isset($selected_filter) && in_array($filter['filter_id'],$selected_filter))
{ ?>
<input name="filter[]" type="checkbox" value="<?php echo $filter['filter_id']; ?>" checked> <?php echo $filter['name'] ?>
<?php } else {?>
<input name="filter[]" type="checkbox" value="<?php echo $filter['filter_id']; ?>"> <?php echo $filter['name'] ?>
<?php }?>
<?php }?>
</div>
</div>
</div>
<?php }?>
<div class="flList">
<?php
$amount_min = $min_product_price;$amount_max = $max_product_price;
if(isset($_GET['amtmin']) && $_GET['amtmin']!=""){
$amount_min = $_GET['amtmin'];
}
if(isset($_GET['amtmax']) && $_GET['amtmax']!=""){
$amount_max = $_GET['amtmax'];
}
?>
<p>Price</p>
<div class="flDrop price_Module">
<div class="flDropDiv">
<!-- <a class="list-group-item fltrHdng">Price</a> -->
<div class="price_slide">
<!-- <label for="amount">Price range</label> -->
<input type="hidden" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
<div id="slider-range"></div>
<div class="cf mb10"></div>
<span class="pull-left" id="amtmin"></span> <span class="pull-right" id="amtmax"></span>
</div>
</div>
</div>
</div>
<div class="cf"></div>
<?php
if(isset($min_p) && ($max_p)){
?>
<div class="filterSelectPrice filterSelect afr">
<div id="fSprice" class="fSbtn">Rs.<?php echo $min_p; ?> - Rs.<?php echo $max_p; ?> <span class="clear fSp"></span></div>
</div>
<?php } ?>
<div class="filterSelect" id="auto_filter_values"></div>
</div>
</div>
Below is my jQuery code:
<script type="text/javascript">
$('input[name^=\'filter\']').on('change', function() {
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
$(filter).prop('checked',true);
});
// console.log(filter);return false;
window.history.pushState("","",'<?php echo $action; ?>&filter=' + filter.join(','));
//return false;
$.ajax({
url: '<?php echo $action; ?>&filter=' + filter,
type: 'post',
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$('#content').block({message:'<img src="<?php echo HTTP_SERVER; ?>image/ajax-loader.gif">'});
//$("#content").fadeOut("slow");
},
complete: function() {
// $(this).remove();
//$("#content").fadeIn("slow");
$('#content').unblock();
},
success: function(data) {
$("body").empty().append(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
</script>

You are defining a multidimensional array when doing []:
$selected_filter[] = explode(",",$_GET['filter']);
in_array() is looking in the top level which is an array so it won't work. Just do:
$selected_filter = explode(",",$_GET['filter']);

Related

Trying to sort my multi-dimensional array by price

I am very new to PhP and programming in general, I looked at similar questions and tried most of the offered solutions but couldn't find a way to apply it to my situation.
I made a filter option on a page, I am now trying to have the filtered results come out as Ascending by price. If I am to use a sort function, where should I be using it in the code for it to make sense?
<?php
require "voitures.php"; [my array][1]
if (isset($_GET["prixMin"])) {
$prixMin = $_GET["prixMin"];
$prixMax = $_GET["prixMax"];
$voitures2 = [];
foreach ($voitures as $voiture) {
if ($prixMin <= $voiture['prix'] && $prixMax >= $voiture['prix']) {
$voitures2[] = $voiture;
}
}
}
?>
<form action=" <?= $_SERVER['PHP_SELF'] ?>" method="GET">
<label for="prixMin">Prix minimal : </label>
<input type="text" name="prixMin" value="<?php if(isset($_GET['prixMin'])){ echo $_GET['prixMin']; }?>">
<label for="prixMax">Prix maximal : </label>
<input type="text" name="prixMax" value="<?php if(isset($_GET['prixMax'])){ echo $_GET['prixMax']; }?>">
<input type="submit" value="Rechercher">
</form>
<br>
<div class="g" style="grid-template-columns: repeat(4, max-content)">
<div class="t">Marques</div>
<div class="t">Modeles</div>
<div class="t">Annee</div>
<div class="t">Prix</div>
<?php if (isset($_GET['prixMin'])) { ?>
<?php foreach ($voitures2 as $voiture2) : ?>
<div class="l">
<div class="c dr"><?= $voiture2["marque"] ?></div>
<div class="c"><?= $voiture2["modele"] ?></div>
<div class="c"><?= $voiture2["annee"] ?></div>
<div class="c mi"><?= $voiture2["prix"] ?></div>
</div>
<?php endforeach ?>
<?php } else { ?>
<?php foreach ($voitures as $voiture) : ?>
<div class="l">
<div class="c dr"><?= $voiture["marque"] ?></div>
<div class="c"><?= $voiture["modele"] ?></div>
<div class="c"><?= $voiture["annee"] ?></div>
<div class="c mi"><?= $voiture["prix"] ?></div>
</div>
<?php endforeach ?>
<?php } ?>
</div>
</main>
<footer>
</footer>
</body>
</html>
array_sort_by_column($voitures2,'prix',SORT_DESC)
function array_sort_by_column($array, $column, $direction = SORT_ASC) {
$reference_array = array();
foreach($array as $key => $row) {
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
return $array;
}

issue with php code and meta tags

I need little bit of help with a small issue,
I need you to fix some line in PHP
What is the issue:
when we share our page on facebook linkedin it comes with
<ol> <li> <span> or <p>
For example the second line on post comes like this!
<ol> <li>Oversee the safety and compliance programs for all the facilities operated by PWSAC.
<?php error_reporting(0);
$user_data=$this->session->userdata('session_user_data');
$f=$this->uri->segment('1');
$p=$this->uri->segment('2');
$i=$this->uri->segment('3');
//echo $apply_url=$f.'/'.$p.'/'.$i; exit;
$this->session->set_userdata('session_apply_job_url',$apply_url);
$image=base_url().'img/user.png';
if(#$company_details[0]->logo!=''){
if (file_exists('./upload/user/resize/'.$company_details[0]->logo)){
$image=base_url().'upload/user/resize/'.$company_details[0]->logo;
}
}
$selectSkill='';
$skill_arr=array();
$selectSkill=#$candidate_profile[0]->skills;
if(!empty($selectSkill)){
$skill_arr=explode(',',$selectSkill);
}
$client_ip=$this->Common->get_client_ip();
$job_visits=$this->Common->selectMultiWhere('tbl_job_visits',$where=array('ip_addtess'=>$client_ip,'job_id'=>$i));
if(empty($job_visits)){
$this->db->insert('tbl_job_visits',array('ip_addtess'=>$client_ip,'job_id'=>$i,'user_id'=>#$this->userId,'date'=>date('Y-m-d h:i:s')));
}
$related_jobs=array();
if(!empty($selectSkill)){
$related_jobs=$this->Common->related_jobs($selectSkill);
}
//echo '<pre>';print_r($user_data[0]->ID);exit;
?>
<style>
.btn-disable_b {
background-color: #c0c0c0;
color: #c0c0c0;
cursor: not-allowed;
display: inline-block;
pointer-events: none;
}
.bg-whit.newmainAdd { background: #f5f5f5 !important;}
</style>
<!--<div id="main">
<div id="container"></div>
Keep Going!
</div>
<div id="footer">You Made It!</div>-->
<section class="wow fadeIn no-padding-bottom newmainAdd" id="main">
<div class="container">
<div class="row">
<div class="col-md-8 col-sm-7 col-xs-12 bg-aqt">
<div class="leftModal newadd1">
<div class="full p-r-15">
<div class="jobDescription">
<div class="jobDescriptionLeft"> <img src="<?php echo $image; ?>" alt="<?php if(isset($candidate_profile[0]->job_title)){echo $candidate_profile[0]->job_title;}?>"> </div>
<div class="jobDescriptionRight">
<h2>
<?php echo glang('Jobs at');?> <?php if(isset($users_info[0]->company_name)){echo $users_info[0]->company_name;}?> : <?php if(isset($candidate_profile[0]->job_title)){echo $candidate_profile[0]->job_title;}?> <?php echo glang('in');?> <?php if(isset($job_description[0]->location)){echo $job_description[0]->location;}?> - <?php echo glang('AquacultureTalent');?>
</h2>
<h3><span>
<?php
//$arr = substr($str, 0, strpos($str, '('));
if($job_description[0]->role_description!=''){
$arr = explode(".", $job_description[0]->role_description, 2);
echo $arr[0].'.';
}
?>
</span></h3>
</div>
</div>
<div class="fullTimeArea full">
<ul>
<li>
<?php if(isset($job_description[0]->job_type)){if($job_description[0]->job_type=='fulltime'){echo 'Full-time';}else if($job_description[0]->job_type=='contract'){echo 'Contract';}elseif($job_description[0]->job_type=='parttime'){echo 'Part-time';}else{echo 'Full-time';}} ?>
</li>
<li><i class="fa fa-calendar"></i> <?php echo $this->Common->time_passed(strtotime($post_jobs_info[0]->approved_date)); ?> </li>
<li><i class="fa fa-map-marker"></i><a href="javascript:;">
<?php if(isset($job_description[0]->location)){echo $job_description[0]->location;}?>
</a></li>
<?php if($job_description[0]->show_salary==1){ ?>
<li><i class="fa fa-eur"></i><a href="javascript:;" data-toggle="tooltip" data-placement="top" title="Gross Anual Salary">
<?php if(isset($job_description[0]->gross_salary_low)){echo $job_description[0]->gross_salary_low;}?>
-
<?php if(isset($job_description[0]->gross_salary_high)){echo $job_description[0]->gross_salary_high;}?>
</a></li>
<?php } ?>
<!--<li><i class="fa fa-bar-chart-o"></i> Intermediate</li>-->
<li><a href="javascript:;" data-toggle="tooltip" title="Preferred spoken language!"><i class="fa fa-language"></i>
<?php if(isset($candidate_profile[0]->language)){echo $candidate_profile[0]->language;}?>
</a></li>
<li> <i class="fa fa-briefcase abs"></i>
<ul>
<li><a href="javascript:;"><span>
<?php if(isset($position_category[0]->title)){echo $position_category[0]->title;}?>
</span></a></li>
</ul>
</li>
<li> <i class="fa fa-tags abs"></i>
<ul>
<?php for($i=0;count($skill_arr)>$i;$i++){ ?>
<?php $skill_category=$this->Common->selectMultiWhere('tbl_talent_profile_option',$where=array('optionsId'=>$skill_arr[$i])); ?>
<li><span><?php echo $skill_category[0]->title; ?></span></li>
<?php }?>
</ul>
</li>
</ul>
</div>
<div class="offerSection full">
<?php if(isset($job_description[0]->role_description)){echo $job_description[0]->role_description;}?>
</div>
<div class="offerSection full">
<h3><?php echo glang('Main requirements');?></h3>
<?php if(isset($job_description[0]->main_requirements)){echo $job_description[0]->main_requirements;}?>
</div>
<div class="offerSection full">
<h2><?php echo glang('Nice to have');?></h2>
<?php if(isset($job_description[0]->nice_to_have)){echo $job_description[0]->nice_to_have;}?>
</div>
<div class="offerSection full">
<h2><?php echo glang('Perks');?></h2>
<?php if(isset($job_description[0]->perks)){echo $job_description[0]->perks;}?>
</div>
</div>
</div>
</div>
<div class="col-md-4 col-sm-5 col-xs-12" >
<div class="" >
<div class="full" id="container">
<div class="rightModal newadd2">
<?php
$string=$candidate_profile[0]->job_title;
$string_slug=$this->Common->create_slug($string);
$i=$this->uri->segment('3');
if(!empty($user_data)){
$student_application_details=$this->Common->selectMultiWhere('tbl_job_application_list',$where=array('applicant_id'=>$this->userId));
$application_array=array();
foreach($student_application_details as $row){
$application_array[]=$row->job_id;
}
?>
<?php if($this->userRoll==3 || $this->userRoll==2 || $this->userRoll==4){ ?>
<a class="applyNow button-3d btn-disable" href="javascript:;"><?php echo glang('apply');?></a>
<?php }else{?>
<?php if(in_array($i,$application_array)){?>
<a class="applyNow button-3d btn-disable" href="javascript:;"><?php echo glang('Already applied');?></a>
<?php }else{ ?>
<a class="applyNow button-3d" href="<?php echo base_url()?>apply-job/<?php echo $string_slug?>/<?php echo $p;?>"><?php echo glang('apply now');?></a>
<?php } ?>
<?php } ?>
<?php }else{ ?>
<a class="applyNow button-3d" href="<?php echo base_url();?>login?login_for=apply"><?php echo glang('Sign up to apply');?></a>
<?php } ?>
<div class="full m-t-30">
<?php if(!empty($user_data)){?>
<?php $bookmark_info=$this->Common->selectMultiWhere('tbl_bookmarks',$where=array('user_id'=>$user_data[0]->ID));
$bookmark_array=array();
foreach($bookmark_info as $row){
$bookmark_array[]=$row->job_id;
}
?>
<?php if($this->userRoll==3 || $this->userRoll==2 || $this->userRoll==4){ ?>
<div id="bookmarksBtn" class="btn-disable_b"> <a class="bookmarksBtn m-t-20 <?php if(in_array($i,$bookmark_array)){ echo 'remove_bookmark active';}else{echo 'add_bookmark';} ?>" data-id="<?php echo $i;?>" href="javascript:;"><i class="fa fa-bookmark"></i>
<?php if(in_array($i,$bookmark_array)){ echo glang('Remove Bookmark');}else{ echo glang('Bookmark'); } ?>
</a> </div>
<?php }else{ ?>
<div id="bookmarksBtn"> <a class="bookmarksBtn m-t-20 <?php if(in_array($i,$bookmark_array)){ echo 'remove_bookmark active';}else{echo 'add_bookmark';} ?>" data-id="<?php echo $i;?>" href="javascript:;"><i class="fa fa-bookmark"></i>
<?php if(in_array($i,$bookmark_array)){ echo glang('Remove Bookmark');}else{ echo glang('Bookmark'); } ?>
</a> </div>
<?php } ?>
<?php }else{ ?>
<a class="bookmarksBtn m-t-20" href="<?php echo base_url();?>login?login_for=apply"><i class="fa fa-bookmark"></i> <?php echo glang('Sign up to Bookmark');?></a>
<?php } ?>
</div>
<div class="full shereArea m-t-30">
<h4><?php echo glang('SHARE');?></h4>
<ul>
<li><i class="fa fa-facebook"></i></li>
<li class="twit"><i class="fa fa-twitter"></i></li>
<li class="linkD"><i class="fa fa-linkedin"></i></li>
<li class="mail2"><i class="fa fa-envelope"></i></li>
</ul>
</div>
<div class="full shereArea m-t-50">
<h4><?php echo glang('Related job offers');?></h4>
<div class="clearfix"></div>
<ul class="full offerspart">
<?php foreach($related_jobs as $r_job){ ?>
<?php if($r_job->id!=$i){ ?>
<?php $string=$r_job->job_title;
$string_slug=$this->Common->create_slug($string);
?>
<li><a href="<?php echo base_url()?>offer-details/<?php echo $string_slug?>/<?php echo $r_job->id; ?>">
<h5>
<?php if(isset($r_job->job_title)){ echo $r_job->job_title;} ?>
</h5>
<p>
<?php if(isset($r_job->company_name)){ echo $r_job->company_name;} ?>
</p>
</a></li>
<?php } ?>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
</section>
<script>
$(document).on('click', '.add_bookmark', function() {
var id = $(this).data('id');
$.ajax({
url: base_url + 'apply/add_bookmark',
type: 'post',
data: {id: id},
dataType: 'json',
beforeSend: function(){
//$(self).parent().addClass('active');
},
complete: function(data){
$("#bookmarksBtn").load(location.href + " #bookmarksBtn>*", "");
},
success: function(json){},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
$(document).on('click', '.remove_bookmark', function() {
var id = $(this).data('id');
var self = this;
$.ajax({
url: base_url + 'apply/remove_bookmark',
type: 'post',
data: {id: id},
dataType: 'json',
beforeSend: function() {
//$(self).parent().parent().children('.bookmark').removeClass('active');
},
complete: function(data) {
$("#bookmarksBtn").load(location.href + " #bookmarksBtn>*", "");
},
success: function(json) {},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
$(".clickIcon").click(function(){
$(".dashLeft").toggleClass("dashLeft-left");
});
</script>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
<script type="text/javascript" >
jQuery(document).ready(function($){
//variables
var $window = $(window);
var $container = $("#container");
var $main = $("#main");
var window_min = 0;
var window_max = 0;
var threshold_offset = 50;
/*
set the container's maximum and minimum limits as well as movement thresholds
*/
function set_limits(){
//max and min container movements
var max_move = $main.offset().top + $main.height() - $container.height() - 2*parseInt($container.css("top") );
var min_move = $main.offset().top;
//save them
$container.attr("data-min", min_move).attr("data-max",max_move);
//window thresholds so the movement isn't called when its not needed!
//you may wish to adjust the freshhold offset
window_min = min_move - threshold_offset;
window_max = max_move + $container.height() + threshold_offset;
}
//sets the limits for the first load
set_limits();
function window_scroll(){
//if the window is within the threshold, begin movements
if( $window.scrollTop() >= window_min && $window.scrollTop() < window_max ){
//reset the limits (optional)
set_limits();
//move the container
container_move();
}
}
$window.bind("scroll", window_scroll);
/**
* Handles moving the container if needed.
**/
function container_move(){
var wst = $window.scrollTop();
//if the window scroll is within the min and max (the container will be "sticky";
if( wst >= $container.attr("data-min") && wst <= $container.attr("data-max") ){
//work out the margin offset
var margin_top = $window.scrollTop() - $container.attr("data-min");
//margin it down!
$container.css("margin-top", margin_top);
//if the window scroll is below the minimum
}else if( wst <= $container.attr("data-min") ){
//fix the container to the top.
$container.css("margin-top",0);
//if the window scroll is above the maximum
}else if( wst > $container.attr("data-max") ){
//fix the container to the top
$container.css("margin-top", $container.attr("data-max")-$container.attr("data-min")+"px" );
}
}
//do one container move on load
container_move();
});
</script>
If you visit this job: https://aquaculturetalent.com/offer-details/123/hatchery-operation-manager and view its source, you'll see this code:
<meta name="description" content="<p>The Hatchery Operations Manager basic functions:</p>
<ol>
<li>Oversee all non-fish culture hatchery operations and staff involved with these tasks including the M/V Alaskan Challenger</li>
<li>Prepare annual budgets with hatchery managers for each facility and the annual budget for the Anchorage Distribution Center to present the General Manager/CEO</li>
<li>To work on a daily basis with the General Manager/CEO and members of the top management team to carry out the directives of the Board</li>
<li>Oversee the safety and compliance programs for all the facilities operated by PWSAC.">
Notice there's HTML inside the content=. Somewhere along the line you're not closing the li or ol and meta tags correctly. Update your back-end code that populates those pieces of data to be valid HTML and it should be fine.
You need to filter to remove tags and escape HTML entities, before content is placed into the meta description, wherever that is happening. Example...
<?php
$desc = "<p>The Hatchery Operations Manager basic functions</p>";
$desc_sanitized = filter_var($desc, FILTER_SANITIZE_STRING);
echo '<meta name="description" content="' . htmlspecialchars($desc_sanitized) . '">';

AJAX pagination not working properly after new entry

I am having a main page "landing.php", here in a div i am calling another page using ajax function "fetch_pages.php". In fetch_pages.php, i am loading data from db as 5 records at a time, when the user reaches the end of page then next 5 records are displayed. Thats working perfectly.
But in landing.php, when i enter a new record and reload the div, then the div content becomes blank, it doesn't show the latest content, after refreshing the full page manually then its again shows all the records. Can't understand whats wrong, kindly help.
landing.php page
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$ProfilePic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name; ?></div>
<p><?php echo $UT." - ".$Designation." - ".$Company; ?></p></div>
<textarea id="posting" name="posting" rows="2" cols="50" placeholder="Share something here..."></textarea>
<div class="clear"></div>
<hr>
</div>
<div class="fileUpload btn btn-default">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i>Upload Image</span>
<input type="file" class="upload" />
</div>
<div>
<input class="postall btn btn-primary pull-right" type="submit" onClick="UserPost()" value="Post">
</div>
<div class="clear"></div>
</div>
<!-- Loading User Posts -->
<div id="mainsectionID">
<div id="results"><!-- results appear here as list --></div>
</div>
<script>
(function($){
$.fn.loaddata = function(options) {// Settings
var settings = $.extend({
loading_gif_url : "images/ajax-loader.gif", //url to loading gif
end_record_text : 'No more records found!', //no more records to load
data_url : 'fetch_pages.php', //url to PHP page
start_page : 1 //initial page
}, options);
var el = this;
loading = false;
end_record = false;
contents(el, settings); //initial data load
$(window).scroll(function() { //detact scroll
if($(window).scrollTop() + $(window).height() >= $(document).height()){ //scrolled to bottom of the page
contents(el, settings); //load content chunk
}
});
};
//Ajax load function
function contents(el, settings){
var load_img = $('<img/>').attr('src',settings.loading_gif_url).addClass('loading-image'); //create load image
var record_end_txt = $('<div/>').text(settings.end_record_text).addClass('end-record-info'); //end record text
if(loading == false && end_record == false){
loading = true; //set loading flag on
el.append(load_img); //append loading image
$.post( settings.data_url, {'page': settings.start_page}, function(data){ //jQuery Ajax post
if(data.trim().length == 0){ //no more records
el.append(record_end_txt); //show end record text
load_img.remove(); //remove loading img
end_record = true; //set end record flag on
return; //exit
}
loading = false; //set loading flag off
load_img.remove(); //remove loading img
el.append(data); //append content
settings.start_page ++; //page increment
})
}
}
})(jQuery);
$("#results").loaddata(); //load the results into element
</script>
fetch_pages.php code-
<?php
session_start();
include 'db.php'; //include config file
$UserID=$_SESSION['uid'];
$UserType=$_SESSION['utype'];
$GLOBALS['lks']=0;
$GLOBALS['cmnts']=0;
$GLOBALS['disabled']="";
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
?>
<!---post start -->
<?php
//fetch records using page position and item per page.
$results = $linkID1->query("select slno,posts,img_link,video_link,likes,comments,shares,post_date,post_time,UserID from user_posts where UserID='$UserID' or UserID in(select MyFriendsUserID from user_connections where MyUserID='$UserID') or UserID in(select MyUserID from user_connections where MyFriendsUserID='$UserID') order by slno desc LIMIT $position, $item_per_page")
or
die(mysqli_error());
//output results from database
?>
<?php
while($row = mysqli_fetch_array($results))
{ //fetch values
$CUID=$row['UserID'];
$stmt = $linkID1->prepare("select Name,Company,Designation,UserType from user_details where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($Name2,$Company2,$Designation2,$UType);
$stmt->fetch();
$stmt->close();
$UT2='';
if($UType=='A')
{
$UT2='Advertiser';
}
else if($UType=='P')
{
$UT2='Publisher';
}
$stmt = $linkID1->prepare("select ProfilePic from user_picture where UserID=?");
$stmt->bind_param("s", $CUID);
$stmt->execute();
$stmt->bind_result($PPic);
$stmt->fetch();
$stmt->close();
?>
<div class="mainsection">
<div>
<div class="pull-left postimage"><?php echo "<img src=profile_pic/".$PPic ." />"; ?></div>
<div class="pull-left posttext">
<div class="postname"><?php echo $Name2; ?></div>
<p><?php echo $UT2." - ".$Designation2." - ".$Company2; ?></p></div>
<div class="clear"></div>
<div class="postdowntxt"><p><?php echo $row['posts']; ?></p></div>
<hr>
</div>
<div class="btnclasess" id="likescommentID<?php echo $row[slno]; ?>">
<div class="likescomment"><?php dataLC($linkID1, $row['slno'],$CUID); ?><a style="padding-right: 7px" href="#"><?php if($GLOBALS['lks']==0){echo '';}else{ echo $GLOBALS['lks']." Likes"; } ?></a><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></div>
<div class="pull-left likebtn"><button <?php echo $disabled; ?> class="btn" id="likeButton<?php echo $row[slno]; ?>" onClick="connect(<?php echo $row[slno]; ?>)"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</button></div>
<button class="pull-left btnhideshow show_hide" data-toggle="collapse" data-target="#demo<?php echo $row['slno']; ?>"><li class="fa fa-comments show_hide" style="margin-right: 6px;"></li>Comment</button>
<button class="pull-left btnhideshow show_hide"><li class="fa fa-share-alt show_hide" style="margin-right: 6px;"></li>Share</button>
<div class="clear"></div>
<div class="clear"></div>
</div>
<!-- Display All Comments -->
<div id="myModal<?php echo $row['slno']; ?>" class="modal">
<div id="DialogDiv<?php echo $row['slno']; ?>">
<!-- Modal content -->
<div class="modal-content" id="modalDialog<?php echo $row['slno']; ?>">
<p class="popupheading"><?php if($GLOBALS['cmnts']==0){echo '';}else{ echo $GLOBALS['cmnts']." Comments"; } ?></p>
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where PostID='$row[slno]' order by upc.slno")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<div id="nReply2<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo $row2['slno']; ?>" onkeyup="enter_reply2(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>,<?php echo $row['slno']; ?>);">
</div>
</div>
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmntsDialog" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox2<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply2(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
<?php
}
?>
<div class="invidone">Close</div>
</div>
</div>
</div>
<!-- Display All Comments -->
<div class="slidingDiv collapse" id="demo<?php echo $row['slno']; ?>">
<div class="viewallcomments">View All Comments</div>
<div class="allcomment" id="commentsLoad<?php echo $row['slno']; ?>">
<?php
$result2 = $linkID1->query("select upc.slno,upc.Comment,upc.CommentedUserID,up.ProfilePic from user_posts_comments upc join user_picture up on upc.CommentedUserID=up.UserID where upc.PostID='$row[slno]' order by upc.slno desc limit 3")
or
die(mysqli_error());
while($row2 = mysqli_fetch_array($result2))
{
?>
<!-- Showing Top 3 Comments -->
<div id="nestedReplyDiv<?php echo $row['slno']; ?>">
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row2['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row2['Comment']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo $row2['slno']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo $row2['slno']; ?>" onkeyup="enter_reply(<?php echo $row2['slno']; ?>,<?php echo $CUID; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<!-- Nested Comments Starts -->
<div id="NestedCmnts" class="nestedcmnts">
<?php
$result3 = $linkID1->query("select upcr.slno,upcr.PostID,upcr.ReplyTo,upcr.ReplyBy,upcr.Comments,up.ProfilePic from user_posts_comments_reply upcr join user_picture up on upcr.ReplyBy=up.UserID where upcr.PostID='$row2[slno]' and (upcr.ReplyTo='$row2[CommentedUserID]' or upcr.ReplyBy='$row2[CommentedUserID]') order by upcr.slno")
or
die(mysqli_error());
while($row3 = mysqli_fetch_array($result3))
{
?>
<div class="pull-left commnetprofile"><?php echo "<img src=profile_pic/".$row3['ProfilePic']." />"; ?></div>
<div class="pull-right commentextstyle commentandreply">
<?php echo $row3['Comments']; ?>
</div>
<div class="pull-left likebtn"><i class="fa fa-reply" style="margin-right: 6px;"></i>Reply</div>
<div class="clear"></div>
<div id="nReply<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" class="collapse">
<div>
<input class="replybox" type="text" id="nReplyBox<?php echo ($row3['slno'] * $row3['slno'])+$row3['PostID']; ?>" onkeyup="enter_nested_reply(<?php echo $row3['slno']; ?>,<?php echo $row3['ReplyBy']; ?>,<?php echo $row['slno']; ?>,<?php echo $row3['PostID']; ?>);">
</div>
</div>
<!--<div class="pull-left likebtn"><i class="fa fa-thumbs-up" style="margin-right: 6px;"></i>Like</div>-->
<div class="clear"></div>
<?php
}
?>
</div>
<!-- Nested Comments Ends -->
</div>
<?php
}
?>
</div>
<textarea id="commentarea<?php echo $row[slno]; ?>" class="secondtextareay pull-left" rows="2" cols="50" placeholder="Post comments here..." onkeyup="enter_comment(<?php echo $row['slno']; ?>,<?php echo $CUID; ?>);"></textarea>
<!--<div class="fileUpload second_fileupload btn btn-default pull-left">
<span><i class="fa fa-camera-retro" style="margin-right: 6px;" aria-hidden="true"></i></span>
<input type="file" class="upload" />
</div>-->
<div class="clear"></div>
</div>
</div>
<?php
}
?>
<!--post end-->
<?php
function dataLC($linkID1, $val, $CUID)
{
$UserID=$CUID;
$LgUserID=$_SESSION['uid'];
$stmt = $linkID1->prepare("select likes,comments from user_posts where slno=?");
$stmt->bind_param("s", $val);
$stmt->execute();
$stmt->bind_result($lksD,$cmntsD);
$stmt->fetch();
$stmt->close();
$GLOBALS['lks']=$lksD;
$GLOBALS['cmnts']=$cmntsD;
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt);
$stmt->fetch();
$stmt->close();
if($cnt>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $UserID,$LgUserID,$val);
$stmt->execute();
$stmt->bind_result($cnt2);
$stmt->fetch();
$stmt->close();
if($cnt2>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
$stmt = $linkID1->prepare("select count(slno) from user_posts_likes where MyUserID=? and FrUserID=? and PostID=?");
$stmt->bind_param("sss", $LgUserID,$UserID,$val);
$stmt->execute();
$stmt->bind_result($cnt3);
$stmt->fetch();
$stmt->close();
if($cnt3>=1)
{
$GLOBALS['disabled']="disabled";
}
else
{
$GLOBALS['disabled']="enabled";
}
}
?>
<script>
$('.btn').on('click', function(e)
{
$(this).prop('disabled',true); });
</script>
<script>
function UserPost() {
var x = document.getElementById('posting').value;
var timezone_offset_minutes = new Date().getTimezoneOffset();
timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
$.ajax({
type: "POST",
url: "user-post.php?p="+x+"&tz="+timezone_offset_minutes,
success: function(data) {
$("#mainsectionID").load(" #mainsectionID");
document.getElementById('posting').value='';
}
});
}
</script>
<script type="text/javascript">
function connect(num) {
$.ajax({
type: "POST",
url: "user-likes.php?id="+num,
success: function(data) {
if(data=='1')
{
$("#likescommentID"+num).load(" #likescommentID"+num);
}
}
});
}
function enter_comment(postid,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('commentarea'+postid).value;
$.ajax({
type: "POST",
url: "user-comments.php?id="+postid+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+postid).load(" #commentsLoad"+postid);
$("#likescommentID"+postid).load(" #likescommentID"+postid);
}
}
});
document.getElementById('commentarea'+postid).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_reply(slno,userpostedid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#commentsLoad"+slno).load(" #commentsLoad"+slno);
}
}
});
document.getElementById('nReplyBox'+slno).value='';
}
else{
//nothing
}
}
function enter_reply2(slno,userpostedid,dno) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var cmnt = document.getElementById('nReplyBox2'+slno).value;
$.ajax({
type: "POST",
url: "user-comments-reply.php?id="+slno+"&cmnt="+cmnt,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+dno).load(" #DialogDiv"+dno);
//$("#modalDialog"+dno).load(" #modalDialog"+dno);
}
}
});
document.getElementById('nReplyBox2'+slno).value='';
}
else{
//nothing
}
}
</script>
<script type="text/javascript">
function enter_nested_reply(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#nestedReplyDiv"+divNo).load(" #nestedReplyDiv"+divNo);
}
}
});
document.getElementById('nReplyBox'+tot).value='';
}
else{
//nothing
}
}
function enter_nested_reply2(slno,userpostedid,divNo,pid) {
if (event.keyCode == 13 && event.shiftKey) {
// shift+enter pressed
}
else if(event.keyCode == 13){
//enter key pressed
var tot=(slno*slno)+pid;
var cmnt = document.getElementById('nReplyBox2'+tot).value;
$.ajax({
type: "POST",
url: "user-comments-reply-nested.php?id="+slno+"&cmnt="+cmnt+"&upid="+userpostedid,
success: function(data2) {
if(data2=='1')
{
$("#DialogDiv"+divNo).load(" #DialogDiv"+divNo);
//$("#modalDialog"+divNo).load(" #modalDialog"+divNo);
}
}
});
document.getElementById('nReplyBox2'+tot).value='';
}
else{
//nothing
}
}
</script>
<script>
function LoadComment(num) {
var modal2 = document.getElementById('myModal'+num);
var span2 = document.getElementById("close3");
span2.onclick = function() {
modal2.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal2) {
modal2.style.display = "none";
}
}
var x = document.getElementById('myBtn2');
modal2.style.display = "block";
}
</script>
Problem resolved. Called the pagination again in the success method of ajax.

Posting Comments to PHP Using Ajax

I'm having this comment form. this comment form works but not correctly whenever I post comment it works on 1 post and on another it refreshes the page and data is also not inserted all the post are fetch by while loop
JS:
< script type = "text/javascript" >
$(function() {
$("#submit").click(function() {
var mcomment = $("input#mcomment").val(); // define the name variable
var mesgid = $("input#mesgid").val();
if (mcomment == '') // if name field is empty
{
alert("Write Comment Please."); // alert an error mesaage
} else {
$.ajax({ // JQuery ajax function
type: "POST", // ajax submit method
url: "status/savecomment.php",
data: 'mcomment=' + mcomment + '&mesgid=' + mesgid, // data sent to php file
cache: false,
success: function(html) { // if the result returns success
$("#comment_display").after(html);
}
});
}
return false;
});
});
< /script>
HTML:
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.png">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="
<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
here is all new edited code
<?php
$msql=mysql_query("SELECT * from `messages` ORDER BY `msg_id` DESC LIMIT
$post_limit");
while($messagecount=mysql_fetch_array($msql))
{
$id=$messagecount['msg_id'];
$msgcontent=$messagecount['message'];
$usermsg=$messagecount['username'];
$userimg=$messagecount['image'];
$userimg1=$messagecount['user_img'];
$usertime=$messagecount['time'];
?>
<i class="pointer" id="pagination-<?php echo $id;?>"></i>
<div style="display: block;" class="timeline-item" id="clone-3">
<div class="panel">
<div class="panel-heading">
<span class="panel-title" style="color:#000;"><?php echo
ucfirst($usermsg); ?> Updated a </span><a href="post.php?id=<?php echo
$id;?>">Post</a>
<span class="panel-date pull-right mr10 text-muted fs12">
<?php echo timeAgo($messagecount['time']);?> via Web</span>
</div>
<div class="panel-body">
<p><img src="image.php/<?php echo $userimg1;?>?width=60&
height=70&nocache&quality=100&image=http://localhost/niftians/profile
/upload/<?php echo $userimg1;?>" /> <?php echo
parse_smileys(make_clickable(nl2br(stripslashes($msgcontent))),
$smiley_folder); ?><br><br><?php if(!empty($messagecount['image'])) { ?>
<img src="status/image.php/<?php echo
$messagecount['image'];?>?width=350&nocache&quality=100&
image=http://localhost/niftians/profile/upload/<?php echo
$messagecount['image'];?>" style="margin-left:10%;">
<?php } ?></p>
</div>
</div>
</div>
<?php
$sql=mysql_query("select * from comments where msg_id_fk='$id' order by
com_id");
$comment_count=mysql_num_rows($sql);
if($comment_count>2)
{
$second_count=$comment_count-2;
?><div class="comment_ui" id="view<?php echo $id; ?>">
<div>
<a href="#" class="view_comments" id="<?php echo $id; ?>">View all <?php
echo $comment_count; ?> comments</a>
</div>
</div>
<?php
}
else
{
$second_count=0;
}
?>
<div id="view_comments<?php echo $id; ?>"></div>
<div id="two_comments<?php echo $id; ?>">
<?php
$listsql=mysql_query("select * from comments where msg_id_fk='$id' order
by com_id limit $second_count,2 ");
while($rowsmall=mysql_fetch_array($listsql))
{
$c_id=$rowsmall['com_id'];
$comment=$rowsmall['comments'];
$userid3=$rowsmall['username'];
$userimg5=$rowsmall['user_img'];
$usercom=$rowsmall['time'];
?> <div id="comment_display"></div>
<div class="media mt15" id="aniket">
<a class="pull-left" href="#"> <img class="media-
object thumbnail thumbnail-sm rounded mw40" src="image.php/<?php echo
$userimg5;?>?width=60&height=60&nocache&quality=100&
image=http://localhost
/niftians/profile/upload/<?php echo $userimg5;?>" alt="..."> </a>
<div class="media-body mb5">
<h5 class="media-heading mbn"><a href="<?php echo
$userid3; ?>"><?php echo ucfirst($userid3); ?></a>
<small> -<?php echo timeAgo($rowsmall['time']);?>
</small>
</h5>
<p><?php echo
parse_smileys(make_clickable(nl2br(stripslashes($comment))),
$smiley_folder); ?></p>
</div>
</div>
<?php } ?>
</div>
<form method="POST" id="commentform">
<div class="panel-footer p15">
<div class="admin-form">
<img src="image.php/<?php echo $info->img;?>?width=45&nocache&
quality=100&image=http://localhost/niftians/profile/upload/<?php echo
$info->img;?>">
<label for="reply1" >
<input name="mesgid" id="mesgid" type="hidden" value="<?php echo $id ?>">
<input name="mcomment" id="mcomment" placeholder="Respond with a
comment." type="text" style="width:130%;">
</label>
<button type="submit" id="submit" class="button
btn-primary submit-btn" name="" style="width:90px; margin-
left:50px;">Comment</button>
</div>
</div>
</form>
<br>
<?php
}
?>
What you need to do is
Remove Submit Button and add <input type="button">
2nd create a div in your page named as <div id="comment_display"></div>
And if this does not solve problem, post your While loop.
Replace this line
$("#submit").click(function() {
with
$("#submit").on('.submit','click',function(e) {
e.preventDefault();
Note: Your submit can work too, but you would have to stop its default behavior using jquery

Show user inputs on a summary page

I have several quantity boxes next to products so a user can input what quantity they want of a certain product.
The setup uses a step by step process using Jquery with the first step made up of checkboxes, the second made up of quantity inputs (where I need the help!) and the final step shows what has been selected... on submit it all gets emailed to me.
Step 1 with checkboxes is complete (with a lot of help from #Beetroot-Beetroot -Step by step checkbox process with summary of selections). Step 2 is where I need the help, how can I show the user quantity inputs on the summary page?
Here's the HTML:
<form id="customisesystem" method="post" action="">
<div id="first-step">
<div class="steps">
<p><b>Step 1 of 3</b></p>
</div>
<div class="progress-buttons"></div>
<div class="clear"></div>
<div id="customise-area">
<div id="customise-title">
<p><b>1. Hardware & software options</b> <span>Please choose one or more of the following</span></p>
</div>
<div id="customise-area">
<?php $posts = get_field('options');
if( $posts ):
$items = 0;
foreach( $posts as $post): // variable must be called $post (IMPORTANT)
setup_postdata($post); ?>
<div class="custom-option">
<p><b>
<?php the_title(); ?>
</b></p>
<br />
<div> <?php echo the_content(); ?> </div>
<?php $counter = 1; while(the_repeater_field('images')): ?>
<?php if($counter <= 1) { ?>
<img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
<?php } ?>
<?php $counter++; endwhile; ?>
<p>
<input type="checkbox" name="hardware[]" value="<?php the_title(); ?>">
Select</p>
<div class="clear"></div>
</div>
<?php $items++; endforeach;
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
endif; ?>
</div>
</div>
</div>
<!-- end first-step -->
<div id="second-step">
<div class="steps">
<p><b>Step 2 of 3</b></p>
</div>
<div class="progress-buttons"></div>
<div class="clear"></div>
<div id="customise-area">
<div id="customise-title">
<p><b>2. Accessories</b> <span>Please choose one or more of the following</span></p>
</div>
<div id="customise-area">
<?php $posts = get_field('accessories');
if( $posts ):
$items = 0;
foreach( $posts as $post): // variable must be called $post (IMPORTANT)
setup_postdata($post); ?>
<?php if ($items&1) { ?>
<div class="custom-option">
<p><b>
<?php the_title(); ?>
</b></p>
<br />
<div> <?php echo the_content(); ?> </div>
<?php $counter = 1; while(the_repeater_field('images')): ?>
<?php if($counter <= 1) { ?>
<img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
<?php } ?>
<?php $counter++; endwhile; ?>
<p style="clear:right;float:right;width:180px;">
<?php if(get_field('sizes')) { ?>
<?php while(the_repeater_field('sizes')) { ?>
<input type="text" name="quantity[]" style="width:15px;" value="0">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?> - <?php echo the_sub_field('size'); ?>">
<?php } ?>
<?php } else { ?>
<input type="text" name="quantity[]" style="width:15px;" value="">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?>">
<?php } ?>
</p>
<div class="clear"></div>
</div>
<?php } else { ?>
<div class="custom-option">
<p><b>
<?php the_title(); ?>
</b></p>
<br />
<div> <?php echo the_content(); ?> </div>
<?php $counter = 1; while(the_repeater_field('images')): ?>
<?php if($counter <= 1) { ?>
<img width="180" height="136" src="<?php the_sub_field('image'); ?>" alt="<?php the_title(); ?>" />
<?php } ?>
<?php $counter++; endwhile; ?>
<p style="clear:right;float:right;width:180px;">
<?php if(get_field('sizes')) { ?>
<?php while(the_repeater_field('sizes')) { ?>
<input type="text" name="quantity[]" style="width:15px;" value="0">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?> - <?php echo the_sub_field('size'); ?>">
<?php } ?>
<?php } else { ?>
<input type="text" name="quantity[]" style="width:15px;" value="">
<?php echo the_sub_field('size'); ?><br />
<input type="hidden" name="product[]" value="<?php echo the_title(); ?>">
<?php } ?>
</p>
<div class="clear"></div>
</div>
<?php } ?>
<?php $items++; endforeach;
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
endif; ?>
</div>
</div>
</div>
<!-- end second-step -->
<div id="third-step">
<div class="steps">
<p><b>Step 3 of 3</b></p>
</div>
<div class="progress-buttons"></div>
<div class="clear"></div>
<div id="customise-area-3">
<p>Summary</p>
<div id="customise-area-3-child">
<input type="submit" name="submit" id="submit" value="submit" />
</div>
</div>
</div>
<!-- end third-step -->
</form>
Here's the Jquery:
jQuery(document).ready(function( $ ) {
//Create nav wrapper
var $nav = $('<div/>').addClass('prev-next');
//Create Prev button, attach click handler and append to nav wrapper
$('<a class="prev" href="#">Back</a>').on('click', function () {
$(this).closest(".step").hide().prev(".step").show();
}).prependTo($nav);
//Create Next button, attach click handler and append to nav wrapper
$('<a class="next" href="#">Next</a>').on('click', function () {
$('.summary_text').html(makeSummary());
var $step = $(this).closest(".step");
if (validate($step)) {
$step.hide().next(".step").show();
}
}).appendTo($nav);
//In one long jQuery chain ...
//* prepend nav to each step div
//* hide all steps except the first
//* convert first 'Back' link and last 'Next' link to spans.
var $steps = $(".step").prepend($nav).hide()
.filter(":first").show().find("a.prev").after('Back').remove().end().end()
.filter(":last").find("a.next").after('').remove().end().end();
//Set step titles
$steps.each(function (i, step) {
$(step).find(".step-title").text('Step ' + (i + 1) + ' of ' + $steps.length);
});
$('a.back-to-product').click(function(){
$(".customise").hide();
$(".entire_product").show();
});
//Unfortunately, hidden form elements are not inlcuded in the submission,
//so all steps must be shown before the form is submitted.
var $submitButton = $("input[name='submit']").on('submit', function () {
$steps.show();
return true;
});
function validate($step) {
//var valid = false;
var valid = true; //for debugging
//Perform validation
switch ($step.index(".step")) { //index-origin is zero
case 0:
//Validate step 1 here
//if valid, set `valid` to true
break;
case 1:
//Validate step 2 here
//if valid, set `valid` to true
break;
case 2:
//No validatation required
break;
}
return valid; //Important - determines behaviour after validate() returns.
}
function makeSummary() {
var summary = [];
$steps.not(":last").each(function (i, step) {
$step = $(step);
summary.push('<p><b>' + $step.data('name') + '</b></p>');
var $ch = $step.find('input[type="checkbox"]:checked');
if (!$ch.length) {
summary.push('<p>No items selected</p><br />');
} else {
$ch.each(function (i, ch) {
summary.push('<p>' + $(ch).val() + '</p><br />');
});
}
});
return summary.join('');
}
});
First, make the quantity[] and product[] fields more readily selectable by hard-coding class="quantity" and class="product" in the HTML.
<input type="text" name="quantity[]" class="quantity" style="width:15px;" value="0">25 cm²<br />
<input type="hidden" name="product[]" class="product" value="Equipment Electrode Set - 25 cm²">
Here's the javascript :
function makeSummary() {
var summary = [];
$steps.not(":last").each(function (i, step) {
$step = $(step);
summary.push('<p><b>' + $step.data('name') + '</b></p>');
var $ch = $('input[type="checkbox"]:checked', $step);
var $qty = $('input.quantity', $step).filter(function() {
return this.value !== '0';
});
var $selected = $ch.add($qty);//jQuery collection of checkeboxes, or quantity fields, or a mixture of both.
if (!$selected.length) {
summary.push('<p>No items selected</p><br />');
} else {
$selected.each(function (i, s) {
var $s = $(s);
var prefix = ($s.hasClass('quantity')) ? ($s.nextAll("input.product").val() + ' : ') : '';
summary.push('<p>' + prefix + $s.val() + '</p><br />');
});
}
});
return summary.join('');
}
By doing it this way, the function remains general with regard to the number of steps, but also with regard to the composition of each step; it will handle completely specialized "checkbox step(s)" and "quantity step(s)", and (should you ever have the need) mixed "checkbox/quantity step(s)". In every case, the selected items will be summarized in their original DOM order.
DEMO

Categories