how to insert php code inside javascript code - php

I need to store the content of story inside mysql table.
This content will later be normally loaded on another page using php.
piano.php is a third, separate file and I don't want it on the current page, but only on the target page.
So I'm trying to insert php code inside story content but it is automatically commented (see in console);
How to do this?
$('button').on('click', function() {
var a = "<div class='part partpiano'><?php include('piano.php');?></div>";
$(a).insertBefore($('.title'));
console.log($('.story').html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='story'>
<div class='title'>lorem</div>
</div><br>
<button>CLICK</button>

It's a much better practice to avoid mixing PHP with JavaScript. PHP is a server-side language and as a result, executes differently from the browser. It can work but usually leads to unexpected behaviour and for the most part, it's much cleaner to keep everything separate.
You can achieve passing data between PHP and JS using hidden inputs or DOM elements with data-* attributes, e.g.
<div id="php-data" data-id="<?php echo $foo; ?>"></div>
then in your jQuery
let id = $('#php-data').attr('data-id');
However, for your problem in particular (as it's an include). It's much much better to simply include the file on load using a class of hidden:
css:
.hidden {
display: none
}
html/php:
<div class="title">
<div class="part partpiano hidden">
<?php include_once 'piano.php'; ?>
</div>
</div>
Then in your JS:
$('button').click(function()
{
$('.part').removeClass('hidden')
})

You can't include PHP in your page in the way you've tried, as you've found. PHP is executed on the server and the results are returned to your browser, so if you add PHP with Javascript then it's not executed/parsed and is just added as text (your browser cannot execute PHP).
What you can do is add the container element to the page and then load the contents afterwards, like this...
$('button').on('click', function() {
var a = "<div class='part partpiano'>Loading...</div>";
$(a).insertBefore($('.title'));
$(a).load("piano.php");
});

Related

jquery hasClass does't work when checking dynamically added class

I have a problam that I dynalically add a class to div through php, and then checking if id "checkLang" has spacific class, but it desn't work :(
Maybe someone knows the problem?
My html:
<div id="checkLang" class ="<?php echo $valoda ?>"><div>
and that div I check with
if ($('#checkLang').hasClass('RU')){
<?php include("lan/ru.php"); ?>
};
if ($('#checkLang').hasClass('LV')){
<?php include("lan/lv.php"); ?>
};
I don't know why, but both ifs include language php file.
But maybe the reason is because this script is in php file with header <?php header('Content-type: text/javascript'); ?> I attach file like javascript file in index page like <script type="text/javascript" src="php/FormuValidacija.php" /></script>
I tried
if($_GET['lang']=="latviesu"){
include("php/lan/lv.php");
}
else($_GET['lang']=="krievu"){
include("php/lan/ru.php");
}
But doesn't work as well :(
P.S. Sorry if this is stupid question, i'm new whit this stuff, but willing to learn! :)
Looks like your script is not added in a dom ready handler like
jQuery(function($){
alert($('#checkLang').length)//it should alert 1 not 0
if ($('#checkLang').hasClass('RU')){
<?php include("lan/ru.php"); ?>
};
})
Current language:
<div id="checkLang" class ="<?php echo $valoda ?>"><div>
Including your localization files:
<div class="ru" style="display:none;">
<?php include("lan/ru.php"); ?>
</div>
<div class="lv" style="display:none;">
<?php include("lan/lv.php"); ?>
</div>
Getting current language and showing corresponding div
<script type="text/javascript">
$(document).ready(function(){
var currLng = $('#checkLang').attr('class'); // get current language, i.e class of #checkLang
$('div.' + currLng).show(); // show div with corresponding class, i.e lang
});
</script>
However, its better to get language at server side and not to load unused files to client(i.e HTML)
P.S un labāk visus variablus, script failus etc saukt anglū valodā :)
Given my jsfiddle example here, you can clearly see that javascript is able to check that the given class is set on the div.
http://jsfiddle.net/n5e9a/
Both of the php files will be rendered no matter what, because the if check here is done on the client side javascript. if you wish to only render data from the php files once the check has been done on the client side. Then you have to fetch the data from the client side instead of serving it from the server side.
One way of doing this is through ajax. for example. you could create a php script that returns html contents based on a query, something like:
checklang.php?lang=RU
and in the javascript code you would have a request set up like this:
$.get('checklang.php?lang=RU', function(data) { //switch RU with a js variable so you can change between RU and LV programatically
$('#some-content-div').html(data);
});
it includes your content because its generated server side already, so when the html site is transfered the php script is already rendnered while the javascript is handled client side, you would have need to adapt your try
you see this would work
<div id="checkLang" class ="<?php echo $valoda ?>"><div>
<div class="ru" style="display:none;">
<?php include("lan/ru.php"); ?>
</div>
<div class="lv" style="display:none;">
<?php include("lan/lv.php"); ?>
</div>
$(document).ready(function()
{
if ($('#checkLang').hasClass('RU')){
$('.ru').show();
}
if ($('#checkLang').hasClass('LV')){
$('.lv').show();
};
});
example here:
http://jsfiddle.net/yVpf4/
tough it would rendner all language content; you should consider doing the language selection within the php code to avoid extra traffic unless you want to switch language via javascript only without any server interaction.
regards jan
also as Arun P Johny stated
...your script is not added in a dom ready handler...
regards jan

How to use a jQuery .load() call from anchor tag in dynamic content

I have a search page that takes user input from a form, then sends that information to a PHP file which sends a cURL call to an outside server. The PHP file then takes the returned array from the server and echoes some HTML to a "results" div in the original search page.
What I'd like to do is set it up so when a user clicks on one of the line items in the "results" div, a modal window appears with more information about the individual item clicked.
I know how to create a jQuery script that will process a click on a single, unique link and generate the modal window by querying the server again (through a separate PHP file that formats the modal box with the additional information and sized correctly). What I don't know how to do is handle all of this with dynamically-created content.
Here's what the first PHP file echoes:
[removed at edit; see below]
It does that for each "listing" in the array returned by the server.
Here's what I've figured out for creating the modal window when the anchor tag in the #modalLaunch div is clicked (this comes from a test page I've been using to figure out how to manipulate the modal window and its content):
[removed at edit, see below]
I'm starting to suspect that I need to abandon this method entirely and try to use an "onClick" strategy, but again I have no idea how to pass the relevant pieces of information between all the functions. Help!
EDIT:
I did a really terrible job of asking this question. I'm sorry. Here's a better representation of the code I'm using:
PHP File:
($data is the array pulled from the outside server. I've removed a bunch of the extraneous variables, so just assume they map to something sensible.)
$data = unserialize($data);
$listings = $data["listings"];
echo "<ul id='listings_grid'>";
for($i=0;$i<$data["count"];$i++)
{
$url = "/listings/".$listing_id;
echo "<li>
<a href='' target='_blank' data-listing-id='".$listing_id."'>
<div class='listing_thumb_image_container'>
<img class='listing_thumb_image' src='".$mainPhoto."'/>
</div>
<div class='listing_thumb_content'>
<br>Rent: $".$rent."
<br>Bedrooms: ".($bedrooms_count==0 ? "Studio" : ($bedrooms_count=='0.5' ? "Convertible" : $bedrooms_count))."
<br>Listing ID: ".$listing_id."
</div>
</a>
</li>";
}
echo "</ul>";
The Search Page:
(Again, pulling out a lot of excess.)
<?php
<script>
$(document).ready(function(){
$.post($("#html-form").attr("action"),$("#html-form").serialize(),function(data){
$("#search_results").html(data);
});
});
$(document).ready(function(){
$("#html-form").on('change submit',function(){
$.post($("#html-form").attr("action"),$("#html-form").serialize(),function(data){
$("#search_results").html(data);
});
return false;
});
});
$(document).on('click','#search_results li',function(){
$('.modalDialog').css('display','block','opacity','1','pointer-events','auto');
var href = $(this).children('a').attr('href');
$('#openModalContent').load(href);
return false;
});
</script>
<div id="openModal" class="modalDialog">
<div>
X
<div id="openModalContent"></div>
</div>
</div>
<div id="content">
<div id="search_form"><form></form></div>
<div id="search_results" style="margin:0 auto;"></div>
</div>
<?php include ('footer.php'); ?>
So where do I go from here? For some reason, when I plug in the options presented by the answers so far, I'm not seeing the modal box appear. It might have to do with the CSS: currently, the modal window only becomes opaque when subjected to the :target pseudo-class. Suggestions?
If you want your dynamically generated content to be able to do stuff try this if your using JQuery 1.9 and above:
$(document).on('click','#openModalContent li',function(){
var href = $(this).children('a').attr('href');
$('#yourModalBox').load(href).show(888);
return false;
});
Add a data-listing-id attribute to the anchor in your generated HTML:
<a href='".$url."' target='_blank' data-listing-id='".$listing_id."'>
and use that attribute inside your click handler like:
$('#modalLaunch a').click(function(){
$('#openModalContent').load('/listings.php', {id:$(this).data("listing-id")});
});

Can I store the whole content of a required file in a JavaScript variable?

This seems like an odd problem. Maybe it's also the wrong approach. But I have to do this:
there are a few menu items on a page
the content for each page is stored in some .phtml files
when the page loads the default content is displayed (using require)
all other content should be loaded too and should be stored in a JavaScript-array
when a user clicks a link, the content is swapped
The problem is:
AJAX should not be used
all content can't be appended in the beginning, for the good old SEO
All parts are easy, except for: How do I get the content into a JavaScript array. Something like content.push('<?php print require 'page.phtml'; ?>'); won't work of course, because it will return a multi line string, which does not work with JavaScript. All ideas are welcome. Maybe I'm overlooking something very simple.
<script>
<?php
ob_start();
require 'page.phtml';
$contents = ob_get_clean();
echo "var content = ".json_encode($contents);
?>
</script>
if there is no php code in your page.phtml file you can make it even easier
<script>
<?php
echo "var content = ".json_encode(file_get_contents('page.phtml'));
?>
</script>
obviously you can use it in this way too:
echo "content.push(".json_encode($contents).");";
why not function
<?php
function json_require($filepath) {
ob_start();
require($filepath);
return json_encode(ob_get_clean());
}
?>
...
content.push(<?=json_require('page_1.phtml');?>);
content.push(<?=json_require('page_2.phtml');?>);
content.push(<?=json_require('page_3.phtml');?>);
content.push(<?=json_require('page_4.phtml');?>);
you can use hidden divs than using js array, At the end of the your page so they wont effect the seo. Then use these divs id to swap your content.
I hope you are using jQuery if not this can be done even with simple js.
let me elaborate
<script>
function shouldBeCalledAtSomeEvent(page_id)
{
var html = $('#'+page_id+').html();
$('#idOfYourTargetElem').html(html)
}
</script>
<!-- end of your main file -->
<div style="display:none" id="page_1">
include('page_1.phtml');
</div>
<div style="display:none" id="page_2">
include('page_2.phtml');
</div>
<div style="display:none" id="page_3">
include('page_3.phtml');
</div>
If you can't use ajax and you're worried about seo, I recommend you use a modified version of #rupesh answer: store the html in script tags so that they can be accessed by js and not be read by crawlers :
<script type="text/hidden-menu" class="hidden_menu" >
include('page_1.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
include('page_2.phtml');
</script>
<script type="text/hidden-menu" class="hidden_menu" >
include('page_3.phtml');
</script>
And then you can easily build your array in js :
var content = [],
contentNodes = document.getElementsByClassName('hidden_menu'),
i=0;
for(;i<contentNodes.length;i++)
content.push(contentNodes[i].innerHTML);
And voila: you have your content array that holds the html sent from php without using ajax and without affecting seo.

Issues since moving javascript to its own file

Alright, if you look at the code below, I am trying to make it more "flexible", moving the JavaScript code to its own file, instead of keeping it in the php file.
The code below is not gonna work anymore, since i cant transfer $yadayada['id'] to the JS file, well okay I dont know how to, and thats where my problem lies.
How can I use the code below, or some variant of it thats gonna work?
Whats gonna happen is that when you press a specific image(button), a modal will open for the specific post in the while statement.
I have skipped out the post part, since thats not the problem here, it is opening a modal window for the correct post.
Thanks in advance!
$yadaya = mysql_query("blablabal")
while($yadayada = mysql_fetch_assoc($yadaya)
{
<div id="kommentera<?=$yadayada['id']?>" class="settingsBox" style="display: none; width:500px; font-size: 14px;">
<textarea id="text<?=$yadayada['id']?>" class="textarea" style="width: 493px; height:80px;"></textarea><br />
<span class="buttons" style="float:left;">
<button id="kommenteraFilm" id1="<?=$yadayada['id']?>" uid1="<?=$yadayada['guid']?>" uid2="<?=$acc_info['id']?>" class="positive" type="submit" name="kommentera"><img src="<?=$static?>/img/bullet_go.png" alt="" />Kommentera</button>
</span>
<?php
?>
</div>
echo '
<div id="se-kommentera'.$yadayada['id'].'" class="testing" style="float:right; margin-top:-2px; cursor:pointer;">
<img src="'.$static.'/img/icon_kommentera.png" height="15px" width="15px" alt="" title="Kommentera" />
</div>'
;
}
footer:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="<?=$static?>/js/mylibs/dependency.js"></script
dependency.js:
$(function() {
$('#se-kommentera<?=$yadayada['id']?>').click(function (e) {
$('#kommentera<?=$yadayada['id']?>').modal();
return false;
});
});
UPDATE
To answer some of the responses, I think you are forgetting that I cannot access the while statement outside the statement itself, so making the js file a php file is kind of useless.
The JS file must be below the jQuery library file, which is in the footer.
You can generate Javascript through PHP (but it's not a good idea)
To directly answer your question: you can "generate" Javascript dynamically through PHP code. For example:
<!-- note that the source is .php so that the server processes it as such -->
<script type="text/javascript" src="dependency.php"></script
And dependency.php would look like:
<?php
// tell the browser how to interpret what we 'll be sending
header('Content-Type: text/javascript');
// get reference to any variables we need
$yadayada = /* ... */
?>
$(function() {
$('#se-kommentera<?=$yadayada['id']?>').click(function (e) {
$('#kommentera<?=$yadayada['id']?>').modal();
return false;
});
});
All of this is really the same thing you are doing when outputting HTML with PHP, only now you are outputting Javascript. But the problem is that you are doing the same work (what is required to get to $yadayada) two times once for your HTML, and once for your JS.
So what is a good idea?
Simply change your markup so that you do not need to know anything inside $yadayada when you write your JS; this way, the code can remain static. For example:
HTML:
<div class="se-kommentera testing">
<img src="..." height="15px" width="15px" alt="" title="Kommentera" />
<div class="settingsBox kommentera">
</div>
</div>
JS:
$(function() {
$('.se-kommentera').click(function (e) {
$(this).find(".kommentera").modal();
return false;
});
});
What I did here is provide a way of finding the appropriate .kommentera div not with an absolute identifier (the id) but in a manner relative to the .se-kommentera that was clicked.
For convenience, I chose to put one div inside the other and get a hold of it with .find; but this is not binding and you could really make dozens of different choices here. For example, you can give both divs an id like you did before and then do something like this:
$(function() {
$('.se-kommentera').click(function (e) {
var id = this.id.replace("se-", "");
$("#" + id).modal();
return false;
});
});
One simple way to do it would be to give the JavaScript-file a .php extension, instead of the regular .js. That way the PHP-code will be executed on the server, before the JavaScript is sent to the client. As you specify the type="text/javascript" on the script tag the browser won't mind the .php extension on your JS-file.
have you tried to echo $yadayada inside the js file?
This thread might help you Passing a PHP Variable in external JS file
If you want your javascript files to be able to output PHP variables, the best way I can think of is to add a mimetype to your htaccess file.
Something like the following would work for Apache...
AddType application/x-httpd-php .js

Load div from another page within an AJAX loaded page

I'm using jQuery address to enable loading specific content from other pages
and to change the URL in the address bar.
I'm working on a little Social Network alike website, so I'm reading out the IDs
of the posts table of my MySQL database via PHP. I want to use the possibilities of jQuery and AJAX to read everything out dynamically.
I found out, that I have to use live() (which turned out to be old), delegate() (which
also turned out to be old in 1.7.1) or on() (which turns out to be the best possibility
to make events work inside of dynamically loaded content via jQuery + AJAX).
I also read somewhere, that I can't use load() or get() to load new content from another
page inside of an already loaded content, because it doesn't "bubble" (I don't even know
what that means).
What do I have to do to load new content within an AJAX loaded page?
Here's a snippet I tried to work with (included on the loaded page):
<?php
if(exist('`posts`')) {
$load = mysql_query('SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 10');
while($row = mysql_fetch_object($load)) {
?>
<script type="text/javascript">
$('body').on('body', 'load', function() {
$.get('getpost.php', { pid: <?= $row->id ?> }, function (data) {
$('#posts').html($('#post_<?= $row->id ?>', data).html()).show();
});
$('#posts').off('load');
});
</script>
<?php
}
}
else {
?>
<div align="center">No posts yet.</div>
<?php
}
?>
getpost.php is my file from which I can get the div_$row->id so that it appears on the start page.
PLUS (Just adding for your knowledge) I want the content to load the content without
a mouseover, click or blur event.
Thanks.
You want to use ".live()" if you want a particular event mapping to be applied dynamically to any new DOM elements which match its selector. Alternatively, you can attach the behavior to each chunk of content loaded.
Write and develop your ajax load independently of your DB lookup to make things simpler. The following snippet triggers another ajax call after each element loads.
<?php
$id = 'div'.mt_rand();
$counter = isset($_REQUEST['counter']) ? $_REQUEST['counter'] : 0;
$next = $counter + 1;
echo <<<END
<div id="{$id}">{$counter}
<script>
$(function() {
$.ajax('/url?counter={$next}', function(html) {
$(html).appendTo($('#{$id}').parent()); // or whatever your favorite method is for adding a sibling
});
});
</script>
</div>
END;
?>
Am I the only one who thinks that this approach is completely wrong? You're making an ajax request for each post, this could end up in making way too much requests, heavily slowing down the loading time. I can't see any reason why you don't want to directly write the posts' HTML inside the PHP while loop.

Categories