refresh only div on form submit - javascript

I have a form:
<form method="get" action="/category/news/?newsSearch=" id="searchForm">
<input id="newsSearch" type="text" name="newsSearch" placeholder="Напишіть щось">
</form>
And I want to not refresh all page and just change this div
<div class="news" id="newsList">
<?php
global $post;
$postslist = get_posts( array( 'posts_per_page' => 200, 'category'=>'news' ) );
foreach ( $postslist as $post ){
setup_postdata($post);
?>
<div class="bl">
<div class="date">
<?php the_date(); ?>
</div>
<div class="tik">
<?php the_field('tiker'); ?>
</div>
<div class="price">
<?php the_field('price'); ?>
</div>
<div class="nnw">
<h5>
<a onclick="$('.hrs<?php the_ID(); ?>').slideToggle('slow');"><?php the_title(); ?> </a>
</h5>
<div class="src hrs<?php the_ID(); ?>">
<?php the_content(); ?>
<?php the_field('link'); ?>
</div>
</div>
<div class="site">
Сайт
</div>
</div>
<?php
}
wp_reset_postdata(); ?>
</div>
I find that solution Want to refresh a div after submit the form? but it didn't change anything (no console errors).
This is my variation of this script:
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
term = $form.find( "input[name='newsSearch']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { s: term } );
// Put the results in a div
posting.done(function( data ) {
var content = $( data ).find( "#content" );
$( "#newsList" ).empty().append( content );
});
});
Form is changing URL to .../?newsSearch='query'and js is hiding posts that doesn't have query in their titles.

Related

Show post description outside while loop

I've a list of team members (custom post type) that I'm calling using WP_Query class. This part is working, however I'm trying to show the description (the_content()) of a team member outside the while loop when clicked on their name. This container (#team-info) is outside the while loop as you can see in the code. Page would ideally scroll to the description container after clicking on the name.
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="team-info"></div>
</div>
</div>
<div class="container mt-15">
<div class="row">
<div class="col-md-12">
<?php
// The Query
$the_query = new WP_Query( array (
'post_type' => 'my_team_sp',
) );
if( $the_query->have_posts() ): $i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
<div class="col-md-4 <?php echo $i ;?>">
<h4><?php the_title() ;?></h4>
</div>
<?php endwhile;
else :
endif;
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
</div>
You can Try this with jQuery. See the below Code.
<div class="container mt-15">
<div class="row">
<div class="col-md-12">
<?php
// The Query
$the_query = new WP_Query( array (
'post_type' => 'my_team_sp',
) );
if( $the_query->have_posts() ): $i = 0;
while ( $the_query->have_posts() ) : $the_query->the_post(); $i++; ?>
<div class="col-md-4 <?php echo $i ;?>">
<h4><?php the_title() ;?></h4>
<div style="display: none;"><?php the_content(); ?></div>
</div>
<?php endwhile;
else :
endif;
/* Restore original Post Data */
wp_reset_postdata();
?>
</div>
</div>
jQuery
Add this code in your Js file.
jQuery(document).ready(function($){
$( '.team-name' ).on('click', function(){
var teamInfo = $(this).next().html();
$( '#team-info' ).html( teamInfo );
});
});

Dynamically add and remove post title

In my wordpress website i create an Ajax search and search post_title. The code is here...
Function and script:
<?php
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: ajaxwpse.ajaxurl,
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('mobile','tablet') ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<li><?php the_title();?></li>
</div>
<?php endwhile;
wp_reset_postdata();
endif;
die();
}
After sucessfully search with Ajax Now i need to add post_title from search to div id="post-container" dynamically.
HTML
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search to add"></input>
<div id="datafetch"></div> // successfuly ajax Search Result Here
<div id="post-container"> </div> // Trying to add post title here
I create a ADD button in search result to add post_title into div.
How dynamically add post_title from search field to div with button?
You've to attach click event to your button the get the post_title and append it to the div :
$(function(){
$('body').on('click', '.post-link', function(){
var post_title = $(this).closest('div').find('a').text();
$('#post-container').append( post_title );
});
});
Hope this helps.
$(function(){
$('body').on('click', '.post-link', function(){
var post_title = $(this).closest('div').find('a').text();
if( $('#post-container p').length < 4 )
$('#post-container').append( '<p>' + post_title + ' ------ REMOVE</p>' );
else
alert('You could add max 4 titles');
});
$('body').on('click', '.remove-title', function(){
$(this).closest('p').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="post-link"> ADD </button>
<li>
The title 1 HERE
</li>
</div>
<div>
<button class="post-link"> ADD </button>
<li>
The title 2 HERE
</li>
</div>
<div>
<button class="post-link"> ADD </button>
<li>
The title 3 HERE
</li>
</div>
<hr>
<div id="post-container"> </div>
Compose both divs in your PHP function, then put them in a single <div>, like this:
PHP:
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
if ( esc_attr( $_POST['keyword'] ) == null ) { die(); }
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => array('mobile','tablet') ) );
if( $the_query->have_posts() ) :
// compose $post_title
$post_title = "...";
echo "<div id=\"datafetch\">";
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<div>
<button class="post-link" rel="<?php the_ID(); ?>"> ADD </button>
<li><?php the_title();?></li>
</div>
<?php endwhile;
echo "</div><div id=\"post-container\">" . $post_title . "</div>";
wp_reset_postdata();
endif;
die();
}
HTML:
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="Search to add"></input>
<div id="result"></div>
JS:
// in your ajax call
success: function(data) {
jQuery('#result').html( data );
}

how to reload a div in jQuery

I have a div in which I have used submit button as follow :
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">
<div class="logininput">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
<button id="sendmail3" class="btn btn-info">Submit</button>
</div>
</div>
</div>
in this when I click on button sendmail3 then a jquery is triggered as follow :
jQuery("#sendmail3").click(function(){
var country = jQuery("#billing_country").val();
var address = jQuery("#billing_address_1").val();
var city = jQuery("#billing_city").val();
var state = jQuery("#billing_state").val();
//alert(state);
var pincode = jQuery("#billing_postcode").val();
var SecondData = "country="+country+"&address="+address+"&city="+city+"&state="+state+"&pincode="+pincode;
var currenturl = jQuery(location).attr('href');
var url = currenturl;
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : SecondData,
complete : function() { },
success: function(data)
{
jQuery("#collapse2").hide();
jQuery("#collapse3").show();
}
});
});
I have one more div collapse3 as follow :
<div id="collapse3" class="panel-collapse collapse">
<div class="panel-body">
<form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( $get_checkout_url ); ?>" enctype="multipart/form-data">
<div id="hideform">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
</div>
<h3 id="order_review_heading"><?php _e( 'Your order', 'woocommerce' ); ?></h3>
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
<?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_order_review' ); ?></div>
</form>
<?php do_action( 'woocommerce_after_checkout_form', $checkout ); ?>
</div>
In this div data is loaded dynamically
What I want is that when I click on sendmail3 button then only the div collapse3 should be reloaded. How can I reload this div only without refreshing the page
I think this will work.
success: function(data)
{
jQuery("#collapse2").hide();
jQuery("#collapse3").append(data); //I change this to .append() or try .html(data);
}
Hope this works.
You can use the load() method:
Load data from the server and place the returned HTML into the matched element.
$('.myDiv').load('urlToGetUpdatedContent');
A very clean way with built-in jQuery logic. See full documentation: http://api.jquery.com/load/
The idea is to fetch your page in specific div , like what you mentioned in your question by ajax call and then return the data to same div .
for example :
$("#sendmail3").click(function(){ var getdata= $("#collapse3").html(); ...
then make ajax call and put in the :
success: function(whatever-result) { $("#collapse3").html(getdata);...
that will only refresh the div with id
UPDATE
I think you are looking to send your form through this mentioned div then reload the div to show the form again , here is another solution :
$("yourform").submit(function(event){
var target =$(this).attr('action');
event.preventDefault();
$.post( target, $(this).serialize(), function(data){
$("#supposed-div").html(data);// this will force submitting this form only through this div
});
});
Then you can use JavaScript , JQuery or AJAX call ,it could be through the above code ,to let form come into div as it is .
At the beginning of this answer i used to suggest to get the $("div").html(); and put it as var getdata to be easy to put again into div.html after submission.

Loading more posts on WP site using AJAX

I have site on WP. And I'm trying to load posts with AJAX. The difference from other such problems is that I have no pagination, the post section is very simple: two posts near and button below. On click on this button to two posts append previous two posts. I tried to write the solution by myself, but I have little expirience in PHP and maybe in it is the problem.
Post structure:
<div class="row">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
<div class="news-date">
<?php the_time($format = 'j F Y'); ?>
</div>
<div>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
<div class="more-link">Read more>
</div>
JS
$(function () {
var posts = 2;
var posts_offset = 0;
$("#load-post").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/wp-content/themes/1cka/load-posts.php",
dataType: 'html',
data: {
posts_offset: posts_offset
},
success: function (data) {
$('.news').append(data);
posts_offset += 2;
}
});
})
});
PHP
<?php require_once("header.php"); ?>
<?php
if (isset($_GET['posts_offset']))
{
$posts_offset = $_GET['posts_offset'];
}
global $post;
// записываем $post во временную переменную $tmp_post
$tmp_post = $post;
$args = array( 'posts_per_page' => 2, 'offset'=> $posts_offset );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
echo '<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
<div class="news-date">
<?php the_time($format = 'j F Y'); ?>
</div>
<div>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
</div>
</div>'
<?php endwhile; ?>
<?php endif; ?>
<?php endforeach;
$post = $tmp_post;
?>
Sorry I don't have an immediate solution but have you seen https://github.com/WP-API/WP-API ? It implements a rest api for most of your wordpress content, you would be able to fetch any additional posts with a simple ajax call

Show posts and image in same div

I have featured images shown for different posts of same category in a page in a specific div. I need to show the whole post related to this image in the same page in another div. I know i must use JavaScript in this. But i need some reference which i can use for this. Can anyone help me with this? I am using the following code to show the images
<?php
/*
Template Name: Meet The Team Template
*/
?>
<?php get_header(); ?>
<div id = "meet_posts" class = "narrowcolumn">
<?php
$recent = new WP_Query("cat=6&orderby=title&order=ASC");
while( $recent->have_posts() ) : $recent->the_post();
$desc_values = get_post_custom_values("description");
?>
<div id="meetteam_featured_image">
<a href="<?php the_permalink() ?>" rel="title">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
</a>
</div>
<?php endwhile; ?>
</div>
<?php get_footer(); ?>
Thanks in advance.
Replace your above code with this following code :
<?php /*
Template Name: Meet The Team Template
*/
?>
<?php get_header(); ?>
<div id="meet_posts" class="narrowcolumn">
<?php
$recent = new WP_Query("cat=6&orderby=title&order=ASC");
while($recent->have_posts()):$recent->the_post();
$desc_values = get_post_custom_values("description");
?>
<div id="meetteam_featured_image" class="<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="title">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
</a>
</div>
<?php endwhile ?>
<div id="image-post-info"></div>
</div>
<?php get_footer(); ?>
Add this following code in functions.php file :
add_action( 'wp_ajax_ajaxified_function', 'ajaxified_function' );
add_action( 'wp_ajax_nopriv_ajaxified_function', 'ajaxified_function' );
function ajaxified_function() {
$temp = get_post($_POST['post_id']);
echo $temp->post_title.'<br/><br/>'.$temp->post_content;
die();
}
Add this following code in your custom js file :
jQuery(document).ready(function (){
jQuery('#meetteam_featured_image a').on('click',function(event){
event.preventDefault();
var post_id = jQuery(this).parent().attr('class');
jQuery.ajax({
type: "POST",
url: 'http://www.yoursitename.com/wp-admin/admin-ajax.php',
data: 'action=ajaxified_function&post_id='+post_id,
success: function (msg) {
jQuery('#image-post-info').html(msg);
},
error: function () {
alert('Error');
}
});
});
});
Add custom js file by including following code in functions.php file :
function add_custom_scripts() {
wp_enqueue_script( 'custom-scripts', get_stylesheet_directory_uri() .'/js/custom- scripts.js' );
}
add_action( 'wp_enqueue_scripts', 'add_custom_scripts' );
Hope this will help....!!!!!
<div id = "meet_posts" class = "narrowcolumn">
<?php
$recent = new WP_Query("cat=6&orderby=title&order=ASC");
while( $recent->have_posts() ) : $recent->the_post();
$desc_values = get_post_custom_values("description");
?>
</div><!--close first div-->
<div id="meetteam_featured_image">
<a href="<?php the_permalink() ?>" rel="title">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
</a>
</div><!--close second div-->
<?php endwhile; ?>

Categories