php post content in a popup div - javascript

I have several elements within a website that are linked to separate php posts. The site also has one popup div('it's a custom modal window').
The popup div has two sections, title and content.
When the elements are clicked, the popup window will appear. I want the associated php post title and content to appear in the popup div in its proper section.
NOTE: I have tried for a week to figure this out using, php, ajax/jquery, combinations. I have scoured google and stackoverflow and can't seem to find the missing link.
Below is my code structure.
FIRST: This is the closest I've got to a working model. The php post_title and post_content is added to the popup window in the appropriate place. But adding code for the next element overrides the first elements data.
HTML
<div class="hexagon">
<p class="verticalcenter center" data-toggle="popWindow" data-target="#popUp">
<!-- ATTACH LATEST POST TITLE -->
<?php $the_query = new WP_Query( 'cat=4' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<?php the_title(); ?>
<?php endwhile;?>
</p>
</div>
<div class="hexagon">
<p class="verticalcenter center" data-toggle="popWindow" data-target="#popUp">
<!-- ATTACH LATEST POST TITLE -->
<?php $the_query = new WP_Query( 'cat=5' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<?php the_title(); ?>
<?php endwhile;?>
</p>
</div>
JS
Note: The 'overlay' is a background with opacity that covers the main content to help focus on the 'popUp' div.
$(document).ready(function() {
...//other code pertaining to website operation
//Click on Hexagons && Launch Modal
$('.hexagon,.hexagonz,#mapToken,.mobileNav li').on('click', function() {
$('.overlay').removeClass('hidden');
$('#popUp')
.addClass('animated fadeInUp')
.css( {
'bottom': '25%'
} )
}); //end Modal Launch
...//other code pertaining to website operation
});// end $(document).ready
The popup window(Modal) html code is located in my footer.php file along with a single.php file containing duplicate popup window code.
IDEALLY: I'd like to accomplish this without resorting to using an (a href=''). This website has a splash page that loads in front of the main page on first load. When I have tried fix this using an (a href='') link, it triggers the splash page(not what I want).
Hope the structure and end goal are clear.

You should first create a PHP script to send each popup the correct info.
Then you could attach a $.post on click, to the button that triggers the popup open, with a 'data-contents' or something similar
Then do the post like this:
$(document).on('click', '.myPopupButton', function(e) {
e.preventDefault();
data = { content : $(this).attr('data-contents') };
$.post('yourScript.php', data, function(json) {
// Handle the data that comes from your script
// i.e. :
$('.myPopup .title').text(json['title']);
$('.myPopup .body').text(json['body']);
}
});
Your PHP should be expecting a value like content => xxx
So you could get it like this:
if ($_POST['content'] == 'xxx') {
}
else if ( /*etc..*/ ) {}
Now the content of the popup should change dinamically

Related

How would I dynamically generate a page title based on the active navigation tab?

I'm using php includes to call in different sections to pages but some of these need to have some different content.
I am trying to set the text that is within an h tag to be the same as the currently clicked navigation item.
Im currently just setting the current page in the navigation section and then again at the top of the page I want to name, defining a variable then calling it within the title.
Navigation Include:
<div>
<ul class="menu">
<li><?php ($currentPage =='about')?>About .
</li>
</ul>
</div>
About us page:
<?php ($currentPage =='about');
$title ='About Us'
?>
which has the
<?php include("includes/titles/page-title.php"); ?> within it, this is also called on different pages and within this include I have
<h2 class="title-center"><?php echo $title ?></h2>
I also have a contact page where I have the same include but need a different title:
<?php ($currentPage =='contact');
$title ='Contact'
?>
Your requirement:
Need respective page headers for every page
Solution:
1) Take an array of page headers
2) Key should be $currentPage from url.
3) Value should be required Page Title.
4) Check if page title is set for $currentPage, if set, print it.
Simple...
And Code:
<?php
$pageHeaders = [];
$pageHeaders['about'] = 'About Us';
$pageHeaders['contact'] = 'Contact Us';
...
?>
Now, print your page header:
<h2 class="title-center">
<?php
$title = 'Your Default Page Title';
if (isset($pageHeaders[$currentPage])) {
echo $pageHeaders[$currentPage];
}
else {
echo $title;
}
?>
</h2>
Note: You can also, create dynamic page navigation with the same kind of array.
The key should be url and the value should be the text.
Loop over it and print navigation menu.

I want to change the main content dynamically with javascript instead of individual pages

My website is currently using .tpl template files to load different pages dynamically. That will load an entire page again, so header, sidebar (chat), main content and the footer.
In my index.php file there is a switch case which loads the page 'home' when you click on 'home' in the menu. (example)
But I don't want that. Because their is also a chat in the sidebar, and that reloads/resets eveytime you load a different page. So all previous messages will be gone. So what I do want is changing only the main content part. So header, sidebar and footer will stay and won't reload.
I tried to do it with javascript but that didn't work...
Can someone help me or atleast put me on the right path?
(And yes, I have been searching for the last hour on stackoverflow and google but couldn't find anything...)
What you need is called AJAX(With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.)
To use ajax u need Javascript to send the request to a PHP file that loads the smarty template that contains your main content and insert the html code back into the page:
<?php
//some-php-file.php
include("Smarty.class.php");
$smarty = new Smarty;
$smarty->display("main_content_part.tpl");
?>
//link on 'home' site
Home
//javascript(jquery) ajax request
$('#ajaxHomeBtn').click(function(e){
e.preventDefault();
$.get("some-php-file.php", function(smarty_html_data) {
$(".main-content").html(smarty_html_data);
});
});
Please follow following instruction :
Create separate .tpl file for header,footer,sidebar and contents files.
In main file include header,footer,sidebar and left one section for content.
3.Replace your .tpl (using id or class) file content using ajax call.
bind your url with function.
Sample code as below:
// sidebar.php
<ul>
<li><a onclick="changePage(this)" data-page="home.tpl">Home</a></li>
<li><a onclick="changePage(this)" data-page="aboutus.tpl">About Us</a></li>
</ul>
// master.php
<?php
include("header.php");
include("sidebar.php");
?>
<section id="fileContent">
</section>
<?php include("footer.php");
?>
<script href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function changePage(obj)
{
var Filename=$(obj).data('page')
$.get(Filename, function( data ) {
$( "#fileContent" ).html(data);
});
}
</script>

Yii2 Captcha refresh or reload image

I'm using the default Captcha implementation of advanced application template shipped with yii2. I tried many time to find any api property that allows me to add Refresh image link that allows user to generate new Captcha image but I could not figure out how to do that. I tried the following client-side solution depending on Jquery:
<!-- This code is placed just before the closing </body> tag at the end of
"frontend/views/layouts/main.php" -->
<script>
$("#fox").click(function(event){
event.preventDefault();
$("img[id$='-verifycode-image']").click();
})
</script>
While in the contact.php the view of contactAction I added a link with an id fox to the widget of captcha as the following:
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}Refresh</div><div class="col-lg-6">{input}</div></div>',
]) ?>
The described solution above, works fine, but It make a must to add unusable code for all application's views except contactAction view or any other view that uses Captcha! because I could not insert the code before including Jquery library. i.e in the view, so I inserted it at the end of the layout.
The question here: Is there any solution directly from the yii2 api? or there is any better suggestion to make this jquery code works in the view? i.e turning it into pure JavaScript.
The below code worked for me -
form code on view file to generate captcha image -
<?= $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::classname(), [
'template' => '<div class="col-lg-3">{image} Refresh</div><div class="col-lg-3">{input}</div>',
])?>
model code to validate captcha code -
public function rules()
{
return [
[['name', 'city', 'description','email'], 'required'],
[['captcha'], 'captcha']
];
}
and js code to refresh captcha image in layouts/main.php file -
<script>
$("#fox").on('click',function(e){
//#testimonials-captcha-image is my captcha image id
$("img[id$='-captcha-image']").trigger('click');
e.preventDefault();
})
</script>
This will solve the issue, we can create a central view as template for captcha and call it everywhere.
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model \frontend\models\ContactForm */
?>
<div class="row">
<div class="col-lg-3">{image} <br /><a id="refresh_captcha" href="javascript:;">Refresh Captcha</a></div>
<div class="col-lg-6">{input}</div>
</div>
<?php
$this->registerJs('
$(document).ready(function () {
$("#refresh_captcha").click(function (event) {
event.preventDefault();
$(this).parent().children(\'img\').click();
})
});
');
?>
For Calling, you can use:
<?= $form->field($model, 'verificationCode')->widget(yii\captcha\Captcha::className(),[
'template' => $this->render("/_partials/captcha_template"),
]); ?>
this will allow you run it on all views, as names and ids can be different for each view.
$(this).parent().children(\'img\').click();
Move that to an external file and you should be fine.
Other solution would be to create a widget with the captcha, create a file with the code and when calling the widget register the javascript file.
Or just create a file with the javascript and remember to register it every time you show the captcha.
Go for the first solution, easier, you do not have to build anything, etc. On websites that do not have thousands of concurrent users it will work just fine.

Temporarily changing HTML structure on the same page in PHP when submit button is clicked?

I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});

WordPress: how to open the_content() in a lightbox or new window?

I´m trying to open the_content (just pictures) in a lightbox.
I´d like a page like a Christmas-calendar so that you can see the posts (and the planned too) and if you click the published post, the image (the_content) should be shown in a shadowbox, lightbox or whatever, I think you´ll know what I mean. Right now my code looks like:
<header class="entry-header" rel="shadowbox" onclick="location.href='<?php the_permalink();?>';" style="cursor:pointer;">
<?php if ( ! post_password_required() && ! is_attachment() ) :
the_post_thumbnail();
endif; ?>
<?php if ( is_single() ) : ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php else : ?>
<?php endif; // is_single() ?>
<?php if ( comments_open() ) : ?>
<div class="kalender">
<p1> <?php the_field('nummer'); ?> </p1>
<br>
<p2><?php the_time('j. F Y'); ?> </p2>
<p3><?php the_title(); ?></p3>
</div>
<!-- .comments-link -->
<?php endif; // comments_open() ?>
</header>
I think the easiest way would be to handle the_content like a read_more link and just say onclick show in an shadowbox. But right now I just don't know how to. You can have a look here (right now just in Firefox or Safari, don't know why Chrome hates me:-))
Consider using the Fancybox plugin: http://fancybox.net/howto
Then include an anchor tag in each of your posts, like 'read more', with the content's unique ID:
<a class="fancybox" href="#content">Read More - This shows content of element who has id="content"</a>
Just ensure that each post's #content DIV has a unique ID, increment a variable in your loop and append it to read something along the lines of:
#content-01, content-02, etc.
Then just hide the content DIV's with CSS.
.fancybox { display: none; }
P.S. seems fine in Chrome 34.0.1847.131
Here's a useful pattern to pass server-side data to the client-side:
1. Use wp_localize_script to output a script fragment to the DOM.
2. Inside that script fragment, assign the value of the_content to a
JavaScript global string variable.
3. Use this JavaScript global from
inside your JavaScript to read the value of the_content

Categories