PHP Code into Javascript - javascript

I am using fullcalendar.js and the calendar is working as it should right now. If a user clicks on an entry at the calendar, a modal appears with some information. What I need now is, that those information inside the modal are information from the database, so I would like to insert some PHP code but I have no idea how.
Let me show you which PHP code I would like to use so that the data from my database are displayed at the modal:
<?php
$dates=getPcalInfoOfHour($gl_userid,0,0);
for ($x=0;$x<count($dates["id"]);$x++) {
Title: '".$dates["title"][$x]."';
Selected Date: '".$dates["date"][$x]."';
Selected Time: '".$dates["start"][$x]."' '".$dates["end"][$x]."';
Topic: '".$dates["topic"][$x]."';
Location: '".$dates["location"][$x]."';
Address: '".$dates["address"][$x]."';
}
?>
Here is the part of my Javascript Code where I would like to enter my php code:
eventClick: function(calEvent, jsEvent, view) {
//display a modal
var modal =
'<div class="modal fade">\
<div class="modal-dialog">\
<div class="modal-content">\
<div class="modal-body">\
<button type="button" class="close" data-dismiss="modal" style="margin-top:-10px;">×</button>\
<label> <strong>Topic:</strong> Topic</label>\
<label> <strong>Selected Dated:</strong> Date</label>\
<label> <strong>Selected Time:</strong> Time</label>\
<label> <strong>Title:</strong> Title</label>\
<label> <strong>Location:</strong> Location</label>\
<label> <strong>Address:</strong> Address</label>\
<label> <strong>Phone:</strong> Phone</label>\
</div>\
<div class="modal-footer">\
<button type="button" class="btn btn-sm" data-dismiss="modal"><i class="ace-icon fa fa-times"></i> Close Window</button>\
</div>\
</div>\
</div>\
</div>';
var modal = $(modal).appendTo('body');
modal.modal('show').on('hidden', function(){
modal.remove();
});
console.log(calEvent.id);
console.log(jsEvent);
console.log(view);
}
I know that PHP is a server side language and JavaScript is client based language but there must be a way, that my data from the database will be shown inside the modal am I right? I know a little bit about PHP programming but I never wrote something in JavaScript.
I would really appreciate if someone can tell me what my code should look like so that I get my information from the database inside the modal window.
Thanks,
Chris

I believe this would do:
var js_string = "<?php echo $php_string; ?>";

You have to make request to server to php script what will fetch data from DB and generate html.
Example javascript to use with php generated html for modal:
$.post('/script_generating_html.php', params, function(response) {
var modal = $(response).appendTo('body');
modal.modal('show').on('hidden', function(){
modal.remove();
});
});

Think of it this way. PHP generates what the browser will read before sending anything. So if you had the following code
<?php
$data = "Super Important";
?>
<script>
alert("<?php print $data; ?>");
</script>
It would generate for the client
<script>
alert("Super Important");
</script>
If you're going to be working with modifying javascript with php, also look into json_encode()
as another way to acheive the same thing is
<?php
$data = "Super Important";
?>
<script>
alert(<?php print json_encode($data;) ?>);
</script>

Related

"javascript:void() just renders as "void()"

It use to work in the past and on other current websites but updating this site it no longer works. I had a pop up message with woocommerce notices, just saying the item has been added to cart, and with a close button using the javascript:void method. However it no longer works and when I look at the source code it's just out putting as "void(0)" instead of "javascript:void(0)"
I've tried other way such as just using # instead. Nothing works. Box won't close.
<div id="woocommerce-message">
<div class="close">
<a href="javascript:void(0)" class="closeEmbtn" onclick="closeEm()"
title="Close Notification"><i class="fa fa-times" aria-hidden="true"></i>
</a></div>
<div class="success-cart">
<div class="woocommerce-message">
<?php foreach ( $messages as $message ) : ?>
<?php echo wp_kses_post( $message ); ?>
<?php endforeach; ?>
</div>
</div>
<div class="message-cart-buttons">
<a class="button" href="/cart/">View Cart/Checkout</a>
Continue Shopping
</div>
</div>
<script type="text/javascript">
function closeEm() {
document.getElementById("woocommerce-message").style.display = "none";
}
</script>
I'm wanting just a way to close/hide the the "woocommerce-message" div when they click a close button.
--Edit --
I tried a different approach
<div class="close">
<a class="closeEmbtn" onclick="closeEm()" href="#" title="Close Notification"><i class="fa fa-times" aria-hidden="true"></i></a></div>
<script>
function closeEm() {
var x = document.getElementById("woocommerce-message");
x.style.display = "none";
}
</script>
But it's the "onclick=" isn't showing up in the source code either. Is there something in wordpress that could be blocking it?
I figured out a work around with a new script function
<script>
document.getElementById("close1").onclick = function() {
document.getElementById("woocommerce-message").style.display = "none";
}
</script>
which then doesn't have to rely on javscript:void(0) and onclick in the html.
But I am still curious to know why those elements suddenly disappeared from the output code

error on ajax while using in codeigniter

Ajax is not working while using in CodeIgniter. The alert message inside the script is working well but the controller function is not getting the call to perform.
View part
<div class="col-md-6 col-sm-6 col-xs-12">
<a class="buttons" onclick="updateExpress(<?php echo $lp->User_Id; ?>)" id="<?php echo $lp->User_Id; ?>" href="javascript:;">
<span class="button-icon"><i class="far fa-heart"></i>
</span>Express your interest</a>
</div>
script added in the view part is:
<script>
function updateExpress(partnerId){\
$.ajax({
url:"<?php echo base_url() ?>index.php/Home/add_express"+partnerId
});
alert("Expressed interest at Profile ID M"+partnerId);
}
</script>
The controller part is mentioned below:
public function add_express()
{
$partnerExp=$this->uri->segment(3);
$user=$_SESSION['userID'];
$datetoday=date("d-m-Y");
$data=array(
'NotificationTo' => $partnerExp,
'NotificationFrom' => $user,
'Notification_Id' => '6',
'date' => $datetoday,
'Is_read' => '0'
);
$data['addresult']=$this->action_data->add_express($data);
}
This function is working while calling this controller function separately. But when it is trying to call using ajax it doesn't work.
Missing ‘/‘ in the url.
add_express”+partnerId
To
add_express/“+partnerId

Ajax Tabs for Wordpress that loads and runs different shortcodes when user changes the tab

How does one execute a shortcode, which is placed in a tab, only when the user clicks on the Tab's Title. How do we do this for five tabs? MY objective is to reduce load time of me website. So, only that content which the user wants must load when he clicks on the tab.
I'm fairly certain the best way to do this is by utilizing Wordpress's admin-ajax.php. I've searched a great deal. And I've found most of the code (I think) to create the AJAX tabs. But, when I fire the code it doesn't show up. Rather the HTML shows us, the AJAX doesn't.
$(document).ready(function() {
$('.my_tabs a').click(function(e) {
e.preventDefault();
var tab_id = $('this').attr('id');
$.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({
action: 'my_tab_menu',
id: tab_id
}),
success: function(data) {
$('#my_tab' + tab_id).html(data);
},
error: function(data) {
alert("Error!");
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_tabs">
Tab 1
Tab 2
Tab 3
Tab 4
Tab 5
</div>
<div class="my_section" id="my_tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my_section" id="my_tab2">
<?php echo do_shortcode ('[shortcode-2]'); ?>
</div>
<div class="my_section" id="my_tab3">
<?php echo do_shortcode ('[shortcode-3]'); ?>
</div>
<div class="my_section" id="my_tab4">
<?php echo do_shortcode ('[shortcode-4]'); ?>
</div>
<div class="my_section" id="my_tab5">
<?php echo do_shortcode ('[shortcode-5]'); ?>
</div>
I add all the code directly into the page using a page-builder. So, I'm not using functions.php to add_action for this particular tab that I'm trying to implement.
I found all the code from a similar post on stackover:
Ajax tabs (wordpress)
They call template_parts into the tabs. Where as I want to execute a shortcode.
I'm what you'd call a coding bimbo. All help shall be much appreciated.
Thank you. And if you've managed to read till here, you deserve to have a pleasant day. :D
Okay, so you can't achieve it the way you have laid your template. As soon as you echo the shortcode and the browser renders the page, the shortcode contents must have printed. You need to create a custom-page-template.php, create a page and on that page you need to send the shortcode handler as soon as you click on the tab through GET or POST method using ajax.
In your Custom Template you receive the [shortcode-1]. An example code would be like you see below:
<?php
/*
Template Name: Shortcode Processor
*/
$current_shortcode = $_POST['shortcode_name'];
?>
<div id="shortcode-contents">
<?php echo do_shortcode($current_shortcode); ?>
</div>
Now you have the response in your Ajax Call. You can now inject the success html inside your desired tab.
Try
<button class="tabs" id="my-tabid1" data-target=".my-section1.box">Tab 1</button>
<button class="tabs" id="my-tabid2" data-target=".my-section2.box">Tab 2</button>
<button class="tabs" id="my-tabid3" data-target=".my-section3.box">Tab 3</button>
<div class="my_section1 box active" id="my-tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section2 box" id="my-tab2">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section3 box" id="my_tab3">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<style>
.box {
display: none;
}
.box.active {
display: block;
}
</style>
<script>
$('.tabs').on('click', function(){
var $target = $($(this).data('target'));
$target.siblings().removeClass('active');
$target.addClass('active');
});
</script>

How to get script variable value in php

I am using popup for showing message based on the id of click function.so i want get the id when popup is open in php. thanks in advance
<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>
<p> </p>
<div class="modal hide" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>some content</p>
<?php //here i want to getting script variable value for database purpose?>
</div>
</div>
and my script is
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
});
in ajax call i am getting the id from the next page but i want value in same page
function viwpost(id) {
var pid=id;
$.ajax({
type: "POST",
url: "view_more.php",
data: "pid=" + pid ,
success: function(data)
{
$("#myModal21").html(data);
}
});
}
Since you're already using jQuery framework/API:
you can simply use the
$.get('phpfile.php' { id: myBookId }).done(function (response) { alert(response); });
your PHP file can pick the request up like this:
$_GET['id'];
If you're trying to make a live pop-up to load the data, this is an incorrect method of doing so. PHP script is only loaded once on server running and sending a request will only give you a response so ensure you research.
I'd suggest you create your PHP file to echo out the data you want to pop-up.
Demonstration of PHP file to send a response back to the request (as requested):
if(isset($_GET['id']))
{
echo 'what ever is outputted to the client will be received in the response';
}
Hey there is mistake in getting id of the link. You can use like this -
first create input type hidden and set its id bookId in model body like this:
<input type="hidden" id="bookId" />
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).attr('data-id');
$(".modal-body #bookId").val( myBookId );
});

How to pass PHP variables to JavaScript onclick and then insert them into Bootstrap Modal

I want to create a bootstrap modal for social sharing buttons in my wordpress blog. For the modal to be visible, I have to place it outside the post (loop) but its trigger (button) inside the post. I want to pass the URL and Title of the post to the Sharing Buttons inside the modal.
I have created two variables inside the post to get its URL and title:
<?php
// Get current post URL
$URL = get_permalink();
// Get current post title
$Title = str_replace( ' ', '%20', get_the_title()); ?>
Then, I created the trigger inside the post to display the modal
<button class="btn btn-link btn-lg" id="socialbtn" data-toggle="modal" data-target="#myModal">Share</button>
And in the modal body, I have many buttons, like
<a class="ssk ssk-text ssk-facebook" href="https://www.facebook.com/sharer.php?u=***URL of the post***">Facebook</a>
<a class="ssk ssk-text ssk-twitter" href="https://twitter.com/share?url=$URL&text=$Title$" >Twitter</a>
What I want to do is to replace the $URL in href of Facebook and Twitter with the URL of the post and likewise the title.
I know that I have to use JavaScript, but I'm unable to figure out the correct syntax.
Will be thankful for help. :)
I did it like this:
In the trigger button, I set the data attributes as follows:
<button class="btn btn-link btn-lg" id="socialbtn" data-url="<?php echo $URL; ?>" data-title="<?php echo $Title; ?>">Share</button>
then got the facebook and twitter URLs in separate variables and then set the href attributes as follows:
<script>
$(document).on("click", "#socialbtn", function () {
var url = $(this).data('url');
var title = $(this).data('title');
var fburl = "https://www.facebook.com/sharer.php?u="+url;
var twurl = "https://twitter.com/share?url="+url+"&text="+title;
$("#facebook").attr("href", fburl);
$("#twitter").attr("href", twurl);
</script>
And in the modal body, used the anchor tags as follows:
<a class="ssk ssk-text ssk-facebook" id="facebook" href="#">Facebook</a>
<a class="ssk ssk-text ssk-twitter" id="twitter" href="#">Twitter</a>
You have to output them using PHP:
<a class="ssk ssk-text ssk-facebook" href="https://www.facebook.com/sharer.php?u=<?php echo $URL; ?>">Facebook</a>
<a class="ssk ssk-text ssk-twitter" href="https://twitter.com/share?url=<?php echo $URL; ?>&text=<?php echo $Title; ?>" >Twitter</a>
$(".ssk-facebook").attr("href", "YourNewURL");
$(".ssk-twitter").attr("href", "YourNewURL");
$( "#socialbtn" ).click(function() {
$(".ssk-facebook").attr("href", "https://www.facebook.com/sharer.php?u=<?= $URL ?>");
$(".ssk-twitter").attr("href", "https://twitter.com/share?url=<?= $URL ?>&text=<?= $Title ?>");
});
You have to identify which button the user have clicked on.
You can archive that by using unique IDs OR by adding hidden inputs or divs containing the correct hrefs for each post.
Then select those "href-container" relatively to the button and change the modal. ("closest(), parent(), nextAll() etc.)
Do you need code examples?
Use data attribute to add link with every post's share button:-
HTML
<!-- Share button (PLACE IT INSIDE YOUR LOOP) -->
<a data-url="<?php echo url; ?>" data-title="<?php echo $title;?>" class="open-share btn btn-primary" href="#">share</a>
<!-- Model popup (PLACE IT AFTER LOOP) -->
<div class="modal hide" id="sharepopup">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Share </h3>
</div>
<div class="modal-body">
<a id="facebook" class="ssk ssk-text ssk-facebook">Facebook</a>
<a id="twitter" class="ssk ssk-text ssk-twitter" >Twitter</a>
</div>
</div>
JS
<script>
$(document).on("click", ".open-share", function () {
var url = $(this).data('url');
var title = $(this).data('title');
$('#facebook').attr("href", "http://facebook.com?share="+url);
$('#facebook').attr("title", "http://twitter.com?share"+title);
$('#twitter').attr("href", url);
$('#twitter').attr("title", title);
// Initialize popup with Javascript.
$('#sharepopup').modal('show');
});
</script>

Categories

Resources