jquery hasClass does't work when checking dynamically added class - php

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

Related

how to insert php code inside javascript code

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");
});

Run PHP on button click

I am learning jQuery and PHP. I am making a simple yes or no oracle. Its working but I need to refresh the page if i want to ask something new. I would like to fire the PHP when someone clicks the button. My code is pretty simple. <div class="ask"> Is the button. I know i could do it with jQuery but i would like to learn a little PHP.
My Code:
PHP:
$answer = array("Yes", "No", "I could not decide ask again later");
$randKey = array_rand($answer);
jQuery:
$(document).ready(function() {
$( ".ask" ).click(function( event ) {
event.preventDefault();
});
$('input').bind("enterKey",function(e){
$('.ask a').click();
});
$('input').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
$('.ask a').click(function(){
if($('input').val() == ''){
$('h2 span').remove();
$('h2').append("<span>It's a secret? You need to ask someting.</span>");
}
else{
$('.answer span').fadeIn(2000);
$('h2').css({'border-bottom' : '1px solid black', 'padding-bottom' : '20px'});
var kysymys = $('input').val();
$( "h2" ).html( "<b>You asked: </b> " + "<span>" + kysymys + "?</span>");
// $('input').val("");
}
});
});
HTML:
<body>
<?php require_once("inc/yes-or-no.php"); ?>
<h2></h2>
<h1 class="answer"> Your answer: <span><?php echo $answer[$randKey]; ?></span></h1>
<p class="input"><input type="text" autofocus> <span>?</span></p>
<div class="ask"> Ask your question!</div>
</body>
You would need to use AJAX to send a request to the web server. You can't just run PHP in javascript (unless someone built a interpreter): javascript generally runs on the client side, while PHP runs on the server side. To get PHP to do stuff, you must ask the server the right questions (i.e. HTTP requests).
EDIT: oh, I misread and missed the require_once(). Just make PHP echo a javascript or hidden HTML section, then pull the relevant info out using javascript.
e.g.
echo <script>var foo = "bar"; </script>
Of course, you should then first make the server actually run the served pages using the PHP interpreter.
i think you need to understand php runs in server while jquery runs on client-side. so whenever someone clicks a button, you need to notify your server-side php code to do something. you can do this using ajax. this will not cause page-refresh.
PHP is a server-side language whereas JavaScript (which jQuery is built on) is a client-side language. This means that if you want execute a PHP file, you need to submit a request to the server, have the server execute it, then reply to the client with the result. You can do this (as you're doing it now) by refreshing the page. Alternatively, you can make an AJAX (JavaScript) call.
You cannot have the client execute PHP code — the client only executes JavaScript.
HTML:
<body>
<h2></h2>
<h1 class="answer"> Your answer: <span><?php echo $answer[$arrayKeys[0]]; ?></span></h1>
<p class="input"><input type="text" autofocus> <span>?</span></p>
<div class="ask"> <a type="submit" href="#"> Ask your question!</a></div>
</body>
jQuery:
$('.ask a').click(function(){
if($('input').val() == ''){
$('h2 span').remove();
$('h2').append("<span>It's a secret? You need to ask someting.</span>");
}
else{
$(".answer span").load("inc/yes-or-no.php");
}
});
PHP:
header("Cache-Control: no-cache");
// Ideally, you'd put these in a text file or a database.
// Put an entry on each line of 'a.txt' and use $prefixes = file("a.txt");
// You can do the same with a separate file for $suffixes.
$prefixes = array("Yes", "No", "I couldn't decide, ask again later.");
// This selects a random element of each array on the fly
echo $prefixes[rand(0,count($prefixes)-1)];
// Example output: Tagging is the new Media
You can read more on Sitepoint
Thanks To http://www.sitepoint.com/ajax-jquery/

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

php in javascript?

i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?

Categories