JQuery not replacing content after AJAX GET call (PHP) - php

Once change INPUT value, content is replaced with a spinner and "Please Wait..." message, and once get response from GET I want to replace the spinner / message with new HTML returned however the new HTML returned is not replacing spinner / message.
The (dynamic PHP) HTML is below followed.
<script type="text/javascript">
$(document).ready( function() {
$( '#submit' ).click( function( e ) {
e.preventDefault();
});
});
</script>
<script type="text/javascript">
$(document).ready( function() {
$( '.basket-item' ).children( 0 ).children( 1 ).change( function( e ) {
e.preventDefault();
var q = $( this ).val();
var id = $( this ).parent().children( 0 ).val();
var elem = $( this ); // var content = elem.parent().parent().parent().html();
elem.parent().parent().parent().html( '<div class="basket-item item-border" style="width:896px;text-align:center;"><p class="para"><img src="<?php echo $this -> get( '__baseuri' ); ?>/media/images/spinner.gif" />Please wait...</p></div>' );
var url = '<?php echo $this -> get( '__baseuri' ); ?>shop/adjust/' + id + '/?quantity=' + q;
$.get( url, function( data ) {
elem.parent().parent().parent().html( data );
});
});
});
</script>
<h1>Shopping Basket</h1>
<div>
<div class="basket-item" style="width:512px;text-align:left;"><p>Product / Item</p></div>
<div class="basket-item"><p>Quantity</p></div>
<div class="basket-item"><p>Price £</p></div>
<div class="basket-item"><p>Total £</p></div>
</div>
<?php if( $this -> has( 'records' ) ): ?>
<form
method="post"
action="#"
accept-charset="utf-8">
<?php foreach( $this -> get( 'records' ) as $record ): ?>
<div>
<div class="basket-item item-border" style="width:512px;text-align:left;">
<p class="para">
<img
width="48"
height="48"
alt="<?php echo $record -> get( 'name' ); ?> (£<?php echo $record -> get( 'price' ); ?>)"
src="<?php echo $this -> get( '__baseuri' ); ?>media/images/products/generic/<?php echo $record -> get( 'image' ); ?>.jpg" />
<?php echo $record -> get( 'name' ); ?></p>
</div>
<div class="basket-item item-border">
<p>
<input type="hidden" name="product" value="<?php echo $record -> get( 'tainted' ); ?>" />
<input type="text" name="quantity" size="3" maxlength="3" value="<?php echo $record -> get( 'quantity' ); ?>" />
</p>
</div>
<div class="basket-item item-border"><p><?php echo $record -> get( 'price' ); ?></p></div>
<div class="basket-item item-border"><p> </p></div>
</div>
<?php endforeach; ?><div style="clear:both;"></div>
<div>
<div class="basket-item item-border" style="width:768px;text-align:right;"><p>Grant Total £ </p></div>
<div class="basket-item item-border" style="width:128px;text-align:center;"><p>14.91</p></div>
</div>
<div>
<div style="margin:0%;padding:16px 0%;width:896px;text-align:left;"><p>
<input id="submit" type="submit" value="Checkout&nbsp>>" />
</p></div>
</div>
</form>
<?php else: ?>
<div>
<div class="basket-item" style="width:896px;text-align:center;"><p>Please add one or more items to your shopping basket.</p></div>
</div>
<?php endif; ?>

Your url is not constructed correctly.
var url = '<?php echo $this -> get( '__baseuri' ); ?>shop/adjust/' + id + '/?quantity=' + q;
Probably needs to be.
var base_uri = "<?php echo $this->get('__baseuri') ?>";
var url = base_uri+'shop/adjust/' + id + '/?quantity=' + q;
The URL is quite acceptable and proper once parsed by server so no issues there, also the server returns content as expected the issue is client side only.

Related

Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?

i iclude a wordpress media selector in my wordpress plugin.
i got this error :
Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
error
i added to this code to wp-config.php file :
`
/** WordPress değişkenlerini ve yollarını kurar. */
require_once ABSPATH . 'wp-settings.php';
define( 'UPLOADS', 'wp-content/uploads' );
`
and added to myportfolio-form.php file
<?php
add_action( 'admin_footer', 'media_selector_print_scripts' );
function media_selector_print_scripts() {
$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );
?><script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>; // Set this
jQuery('#upload_image_button').on('click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
$( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );
$( '#image_attachment_id' ).val( attachment.id );
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery( 'a.add_media' ).on( 'click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script><?php
}
function portfolio_admin_myprojects_page_handler()
{
global $wpdb;
$table = new Portfolio_MyProjects_List_Table();
$table->prepare_items();
$message = '';
if ('delete' === $table->current_action()) {
$message = '<div class="updated below-h2" id="message"><p>' . sprintf(__('Items deleted: %d', 'portfolio-admin-myresume'), count($_REQUEST['ID'])) . '</p></div>';
}
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects_form');?>"><?php _e('Add new', 'portfolio-admin-myresume')?></a>
</h2>
<?php echo $message; ?>
<form id="myprojects-table" method="POST">
<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
<?php $table->display() ?>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_page_handler()
{
global $wpdb;
$table_name = $wpdb->prefix . 'portfolio_myprojects';
$message = '';
$notice = '';
$default = array(
'ID' => 0,
'projects_name' => '',
'projects_category' => '',
'projects_link' => '',
'projects_image' => '',
'order' => '',
);
if ( isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
$item = shortcode_atts($default, $_REQUEST);
$item_valid = portfolio_admin_validate_myprojects($item);
if ($item_valid === true) {
if ($item['ID'] == 0) {
$result = $wpdb->insert($table_name, $item);
$item['ID'] = $wpdb->insert_id;
if ($result) {
$message = __('Item was successfully saved', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while saving item', 'portfolio-admin-myresume');
}
} else {
$result = $wpdb->update($table_name, $item, array('ID' => $item['ID']));
if ($result) {
$message = __('Item was successfully updated', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while updating item', 'portfolio-admin-myresume');
}
}
} else {
$notice = $item_valid;
}
}
else {
$item = $default;
if (isset($_REQUEST['ID'])) {
$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $_REQUEST['ID']), ARRAY_A);
if (!$item) {
$item = $default;
$notice = __('Item not found', 'portfolio-admin-myresume');
}
}
}
add_meta_box('myprojects_form_meta_box', __('Work Details', 'portfolio-admin-myresume'), 'portfolio_admin_projects_form_meta_box_handler', 'myprojects', 'normal', 'default');
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects');?>"><?php _e('back to list', 'portfolio-admin-myresume')?></a>
</h2>
<?php if (!empty($notice)): ?>
<div id="notice" class="error"><p><?php echo $notice ?></p></div>
<?php endif;?>
<?php if (!empty($message)): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif;?>
<form id="form" method="POST">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<input type="hidden" name="ID" value="<?php echo $item['ID'] ?>"/>
<div class="metabox-holder" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<?php do_meta_boxes('myprojects', 'normal', $item); ?>
<input type="submit" value="<?php _e('Save', 'portfolio-admin-myresume')?>" id="submit" class="button-primary" name="submit">
</div>
</div>
</div>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_meta_box_handler($item)
{
// Save attachment ID
if ( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :
update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );
endif;
wp_enqueue_media();
?>
<tbody >
<div class="formdatabc">
<form >
<div class="form2bc">
<p>
<label for="projects_name"><?php _e('Project Name:', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_name" name="projects_name" type="text" value="<?php echo esc_attr($item['projects_name'])?>"
required>
</p>
</div>
<div class="form2bc">
<p>
<label for="projects_category"><?php _e('Project Category', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_category" name="skills_percent" type="text" value="<?php echo esc_attr($item['projects_category'])?>"
required>
</p>
</div>
<div class="form3bc">
</div>
<div>
<p>
<label for="projects_link"><?php _e('Project Link:', 'portfolio-admin-myresume')?></label>
<br>
<textarea id="projects_link" name="projects_link" cols="100" rows="3" maxlength="240"><?php echo esc_attr($item['projects_link'])?></textarea>
</p>
</div>
<div class='image-preview-wrapper'>
<img id='image-preview' src='' width='100' height='100' style='max-height: 100px; width: 100px;'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value=''>
</form>
</div>
</tbody>
<?php
}
`
i tried to iclude wordpress media selector to my plugin but it doesnt work.
error : Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
You need to change permissions of directories on server itself
chmod -R 777 /path/to/web-root/wp-content/uploads
(Linux example, this will change all files)
chmod 777 /path/to/web-root/wp-content
(this will change only directory itself, not all files)

Pass acf fields to Leaflet JS

I found this example on the internet that comes pretty close to what I want to do.
I have some ACF fields with the latitude and longitude of some markers, I am trying to show all the markers of the custom post type place in the same map.
But I only get 1, what am I doing wrong?
I think is something related with the marker div
<?php /* Template Name: Demo Page Template */ get_header(); ?>
<h1 class="main-title"><?= post_type_archive_title(); ?></h1>
<section class="list-cases">
<div class="container">
<div class="row position-relative">
<?php
$args = array(
'post_type' => 'lugar',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
?>
<?php $counter = 1; ?>
<?php while( $query->have_posts() ) : $query->the_post() ?>
<div class="item-case-<?= $counter ?> col-md-12" data-hover="<?= $counter ?>" data-aos="fade-up"
data-aos-duration="2000">
<div class="case-container">
<?php the_title( '<h2 class="entry-title">', '</h2>' ); ?>
<p><?php the_field('subtitle') ?></p>
<p><?php the_field('address') ?></p>
<p><strong>Latitud:</strong> <?php the_field('lat') ?></p>
<p><strong>Longitud:</strong> <?php the_field('lon') ?></p>
</div>
</div>
<?php $counter++; ?>
<?php endwhile; wp_reset_postdata(); ?>
</div>
</div>
</section>
<style>
#map,
#acf-map {
height: 500px;
}
</style>
<div id="map" style="width: 600px;">
</div>
<div class="marker" data-lat="<?php echo the_field('lat') ?>" data-lng="<?php the_field('lon'); ?>"
data-title="<?php the_field('subtitle') ?>" data-url="<?php echo 'link'; ?>"
data-category="<?php echo 'category'; ?>"></div>
<script>
$(document).ready(function () {
var map = L.map('map').setView([39.8410802, -0.1191397], 8);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'pk.eyJ1IjoiamFtYWxkb2xzIiwiYSI6ImNrYmF2bGowOTBycGEyeG84b2F2NGlsYWkifQ.9rqymFnsW79aCkAFGCo0XQ'
}).addTo(map);
var marker = [];
$.each($('.marker'), function () {
var lat = $(this).attr('data-lat');
var lng = $(this).attr('data-lng');
var name = $(this).attr('data-title');
var link = $(this).attr('data-url');
console.log('Marker es: ' + marker);
marker = [name, lat, lng, link];
console.log('Y ahora es: ' + marker);
console.log(marker);
});
var markers = [marker];
console.log(markers);
console.log(markers.length);
for (var i = 0; i < markers.length; i++) {
marker = new L.marker([markers[i][1], markers[i][2]])
.bindPopup(markers[i][0])
.addTo(map);
}
});
</script>
Please make sure that you are echo-ing the custom field values.
Example: data-lat="<?php echo get_field('lat'); ?>" and data-lat="<?php echo get_field('lon'); ?>"
You need to put the div.marker into the loop to display multiple markers with the custom lat-long values.
<?php while( $query->have_posts() ) : $query->the_post() ?>
<div class="marker"
data-lat="<?php echo get_field( 'lat' ) ?>"
data-lng="<?php echo get_field( 'lon' ); ?>"
data-title="<?php echo get_field( 'subtitle' ) ?>"
data-url="<?php echo 'link'; ?>"
data-category="<?php echo 'category'; ?>" >
</div>
<?php endwhile; wp_reset_postdata(); ?>
Also, I would modify your javascript so it will look like this:
var markers = [];
$.each($('.marker'), function () {
var marker = [];
var lat = $(this).attr('data-lat');
var lng = $(this).attr('data-lng');
var name = $(this).attr('data-title');
var link = $(this).attr('data-url');
console.log('Marker es: ' + marker);
marker = [name, lat, lng, link];
console.log('Y ahora es: ' + marker);
console.log(marker);
markers.push( marker );
});
console.log(markers);
console.log(markers.length);
for (var i = 0; i < markers.length; i++) {
marker = new L.marker([markers[i][1], markers[i][2]])
.bindPopup(markers[i][0])
.addTo(map);
}

Unable to call search term in functions.php from search.php & searchfrom.php in wordpress

I am not able to call the search term in functions.php file from search.php file. I am trying to achieve this through the use of script.
$search_term should be called but it is not being called. If I replace it with certain keywords, posts shows perfectly. I want to call search term input by user using the search form.
search.php
<?php $search_query = get_search_query(); ?>
<div align="center">
<h2>Search Results For "<?php echo $search_query ?>"</h2>
</div>
<div class="entry-content" style="margin:2% 0 0 0;">
<?php if (have_posts()) : ?>
<div class="col-lg-12 col-md-12 col-sm-12 my-posts" style="padding:0 1% 1% 1%;">
<?php while (have_posts()) : the_post(); ?>
<?php
echo "<div>";
This Part Shows Content
echo "</div>";
?>
<?php endwhile ?>
</div>
<?php endif ?>
</div>
<div class="loadmore" style="text-align:center;font-size:1.4em;color:#4a235a;padding:1% 0 1% 0;font-weight:900;">
<button type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts</button>
</div>
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
$('body').on('click', '.loadmore', function() {
var data = {
'action': 'load_posts_by_ajax_search',
'page': page,
'searchTerm': $('#s').val(),
'security': '<?php echo wp_create_nonce("load_more_posts_search"); ?>'
};
$.post(ajaxurl, data, function(response) {
$('.my-posts').append(response);
page++;
});
});
});
</script>
functions.php
add_action('wp_ajax_load_posts_by_ajax_search', 'load_posts_by_ajax_callback_search');
add_action('wp_ajax_nopriv_load_posts_by_ajax_search', 'load_posts_by_ajax_callback_search');
function load_posts_by_ajax_callback_search() {
check_ajax_referer('load_more_posts_search', 'security');
$paged_search = $_POST['page'];
$search_term = esc_attr($_POST['searchTerm']);
$args_search = array(
'posts_per_page' => '20',
's' => $search_term,
'paged' => $paged_search,
);
$my_posts_search = new WP_Query( $args_search );
if ( $my_posts_search->have_posts() ) :
?>
<?php while ( $my_posts_search->have_posts() ) : $my_posts_search->the_post() ?>
<?php
echo "<div>";
This Part Shows Content
echo "</div>";
?>
<?php endwhile ?>
<?php endif; ?>
My searchform.php code
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>" target="_self">
<div>
<input style="text-align:center;width:100%;margin:0 0 12px; 0;border-color:#4a235a;color:#000000;" placeholder='Eg:Location,Skill,Company' class="text" type="text" value="" name="s" id="s" />
</div>
<div>
<input type="submit" style="text-align:center;margin:0 0 0 0;width:100%;border:1.5px solid;border-color:grey;background-color:#4a235a;color:#f4511e;" class="submit button" name="submit" value="<?php _e('Search');?>" />
</div>
</form>

Hide comment after deleting

I have tride to add function hide after deleting the comment. but it hide all comments. but i need to hide just deleted comment. there is my js.
$('.delete_p').click(function(){
var del_id = $(this).attr('id_p');
$.ajax({
type: 'POST',
url: 'delete_post.php',
data:'delete_id='+del_id,
success: function(data){
$('#status .holder'+del_id).fadeOut();
}
});
});
$( ".delete_p" ).click(function() {
$( "#status .holder").hide("slow");
});
i have tride to add thisbut it doesn't helped.
$( "#status .holder", $(this)).hide( "slow" );
here is html. it is too long. there is just used for comment:
<div id="status">
<div class='holder' id_p='<?php echo $post_id; ?>'>
<div class='holder_half'>
<?php
$default_s_pic = "href=/default_picture.png";
echo "<div id='picture'><a href='/$poster_name'>";
if($adder_pic === ""){
echo '<img src="', $default_s_pic, '" alt="', $poster_f_name,'\'s Profile image">';
}else{
echo '<img src="', $adder_pic, '" alt="', $poster_f_name,'\'s Profile image">';
}
echo "
</a>
</div>
<div class='ten'>
<div id='statusname'><a href='/$poster_name'>$poster_f_name</a></div>
<div class='date_time'>$data</div>
<span class='span' data-ft='{"tn":"K"}'>
";
if($posted_place === $deleter || $poster_name === $deleter){
echo "
<button class='delete_p' id_p='". $post_id ."'>x</button>
";
?><script src="delete_post.js"></script>
</div>
</div>
</div>
</div>
Change This code:
<div class='holder' id_p='<?php echo $post_id; ?>'>
to this:
<div class='holder<?php echo $post_id; ?>' id_p='<?php echo $post_id; ?>'>

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