Give PHP value into Javascript in same page - php

How can I give the ID value to Javascript in same page.
Example data :
<a href="" id="ctextarea<?php echo $uid; ?>"/>
JS :
function recountss()
{
var maxlen=280;
var current = maxlen-$('#ctextarea').val().length;
$('.counters').html(current);
if(current<0 || current==maxlen)
{
$('.counters').css('color','#D40D12');
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else if (!$.trim($("#ctextarea").val())) {
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else
$('input.comment_button').removeAttr('disabled').removeClass('inact');
if(current<10)
$('.counters').css('color','#D40D12');
else if(current<20)
$('.counters').css('color','#5C0002');
else
$('.counters').css('color','#C0C0C0');
}
I tried using get class, but it's effect for 1 data not for many data.
Have idea ?
Thanks.

This should work :
<script type="text/javascript">
var id = "ctextarea<?php echo $uid; ?>";
</script>
In your javascript, you can do :
var current = maxlen-$(id).val().length;
But you should use an other name for your variable.

Try data- attributes:
Link
In JS you can do the following:
document.getElementById('link').getAttribute('data-id');
This stuff is perfectly valid in HTML5 - but even older browsers just don't care.

Related

Trigger JQuery function based on value of variable

I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?
If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>
Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something
Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>
You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}
Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>
$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})
However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>

How to update the PHP current timestamp using jquery/javascript every second

I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.
You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.

How do I get a php value in Jquery?

Hey guys I have this populated search form that will bring a table of people based on search result. I need to be able to get the php variable that has the username I am trying to get, then that will get sent over to .php file using the JQuery UI which will open a notes window.
So here:
username, other, other , notes - this is a link and once clicked the following is called:
$(document).ready(function () {
$("#NotesAccessor").click(function () {
alert(notes_name);
run();
});
});
which leads to :
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
}
to a function that opens the Jquery Dialog.
I need to access the username of the based notes that was clicked....if there was 20 results of different names, david, joe, john, etc... I click the notes with david as username, I need that to be sent over to the file that is opening so I can display the based notes on the appropriate username.
Here is my php:
.........
<td>
$csvusername
</td>
.........
<td>
";
if ($checkNotes[1] == 'No')
{
echo "None";
}
if ($checkNotes[1] == 'Yes')
{
echo "<a href='#' id='NotesAccessor'>Click to access</a>";
}
echo "
</td>
........
Let me know if this makes sense to you. I am kinda stuck on this and could use a hand :)
David
I can't tell what PHP variable you are trying to get, but generally, you can do:
<!-- /myScript.php?myVar=helloWorld -->
<script type="text/javascript">
$(document).ready(function(){
var myPhpVar = <?php echo $_GET['myVar']; ?>;
alert(myPhpVar);
});
</script>
<script>
var x = '<?php echo $variable; ?>';
or
var x = '<?php echo my_function(); ?>';
</script>
<?php
function my_function()
{
return $variable;
}
?>
this should do what you like :)

Toggling divs in javascript

I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one
JavaScript Code
<script type="text/javascript">
function toggle(id){
var el = document.getElementById(id);
if(el != null && el.style["display"]== 'none'){
el.style["display"] = "block";
}
}
</script>
My divs code
<?php foreach($titles_data as $title){ ?>
<div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
<div id="left-ad"></div>
</div>
<?php } ?>
My links code
<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
<a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
</a>
</li>
<?php } ?>
How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?
Thanks
Using native JS:
function toggle(id){
var el = document.getElementById(id);
el.style.display = el.style.display == "none" ? "block" : "none";
}
toggle("myId");
Using jQuery:
function toggle(selector) {
$(selector).toggle();
}
toggle("#myId");
To toggle the display, you dont need to do that much
$("#elementid").toggle();
In reference to your question
$('a').click(function() { // however this is select all anchors, better use class
// selector like $(".mylinkclass")
var id= $(this).attr('id'); //get the id
var ids = id.splite("_"); //split the id on "_", to extract the idtitles
$("#content_"+ids[0]).toggle(); // use that to toggle
});
Assuming that there is always only one div that is displayed, you can check for it:
Alter your logic, to declare a global variable to hold the value of the currently visible div. And then update that variable whenever a link is clicked, to hold the id of the currently visible div. So, using your exisitng code, you can do this :
using core javascript:
var visibleDiv;
function toggle(id){
// hide the previous div using visibleDiv
if(document.getElementById(visibleDiv)!= null) document.getElementById(visibleDiv).style["display"] = "none";
var el = document.getElementById(id);
if ( el.style["display"] == "" || el.style["display"] == 'none' ){
el.style["display"] = 'block';
}
visibleDiv = id; // update the current visible div name
}
using jquery like this :
var visibleDiv;
$("[id^=content_]").each(function() {
if($(this).is(':visible')){
visibleDiv = $(this).attr('id');
}
});
Check my new answer. I just created the sample html page, with 3 divs. Initially all are shown. When you click on one of them, it is hidden. When you click on some other div. The old one is made visible again and the current one is hidden. Modify the logic as per your requirements.
<html>
<head>
<title>asdsa</title>
<script type="text/javascript">
var visibleDiv;
function toggled(id){
//$('#div_2').html($('#div_1').html());
if(document.getElementById(visibleDiv) != null){ document.getElementById(visibleDiv).style["display"] = "block";}
var el = document.getElementById(id);
document.getElementById(id).style["display"] = "none";
visibleDiv = id;
}
</script>
</head>
<body>
<div id="div_1" onclick="toggled('div_1')">div1</div>
<div id="div_2" onclick="toggled('div_2')">div2</div>
<div id="div_3" onclick="toggled('div_3')">div3</div>
<hr/>
</body>
</html>
Thanks.

PHP and Javascript integration

I would like to use the following script to display dynamic breaking news on the home page of my site, this dynamic code is run via mysql
<script language="JavaScript1.2">
//Specify the marquee's width (in pixels)
var marqueewidth="780px"
//Specify the marquee's height
var marqueeheight="50px"
//Specify the marquee's marquee speed (larger is faster 1-10)
var marqueespeed=2
//configure background color:
var marqueebgcolor=""
//Pause marquee onMousever (0=no. 1=yes)?
var pauseit=1
//Specify the marquee's content (don't delete <nobr> tag)
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):
var marqueecontent='<nobr><font face="Arial"><h3>Example Scrolling Breaking News</h3></font></nobr>'
////NO NEED TO EDIT BELOW THIS LINE////////////
marqueespeed=(document.all)? marqueespeed : Math.max(1, marqueespeed-1) //slow speed down by 1 for NS
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var iedom=document.all||document.getElementById
if (iedom)
document.write('<span id="temp" style="visibility:hidden;position:absolute;top:-100px;left:-9000px">'+marqueecontent+'</span>')
var actualwidth=''
var cross_marquee, ns_marquee
function populate(){
if (iedom){
cross_marquee=document.getElementById? document.getElementById("iemarquee") : document.all.iemarquee
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
cross_marquee.innerHTML=marqueecontent
actualwidth=document.all? temp.offsetWidth : document.getElementById("temp").offsetWidth
}
else if (document.layers){
ns_marquee=document.ns_marquee.document.ns_marquee2
ns_marquee.left=parseInt(marqueewidth)+8
ns_marquee.document.write(marqueecontent)
ns_marquee.document.close()
actualwidth=ns_marquee.document.width
}
lefttime=setInterval("scrollmarquee()",20)
}
window.onload=populate
function scrollmarquee(){
if (iedom){
if (parseInt(cross_marquee.style.left)>(actualwidth*(-1)+8))
cross_marquee.style.left=parseInt(cross_marquee.style.left)-copyspeed+"px"
else
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
}
else if (document.layers){
if (ns_marquee.left>(actualwidth*(-1)+8))
ns_marquee.left-=copyspeed
else
ns_marquee.left=parseInt(marqueewidth)+8
}
}
if (iedom||document.layers){
with (document){
document.write('<table border="0" cellspacing="0" cellpadding="0"><td>')
if (iedom){
write('<div style="position:relative;width:'+marqueewidth+';height:'+marqueeheight+';overflow:hidden">')
write('<div style="position:absolute;width:'+marqueewidth+';height:'+marqueeheight+';background-color:'+marqueebgcolor+'" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">')
write('<div id="iemarquee" style="position:absolute;left:0px;top:0px"></div>')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+marqueewidth+' height='+marqueeheight+' name="ns_marquee" bgColor='+marqueebgcolor+'>')
write('<layer name="ns_marquee2" left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed"></layer>')
write('</ilayer>')
}
document.write('</td></table>')
}
}
</script>
However when i try to put my php code in and it doesn't work. Ok some of you will say that PHP and Javascript are not compatible, but i'm interested in either a direct solution or a work around.
Or if you can get javascript to access mysql database even better (not too sure on that)
Is there any chance that one of you can find some way of putting php into this var marqueecontent='<nobr><font face="Arial"><h3>PHP HERE</h3></font></nobr>' because if tried all different types of this and none of them work with my mootols version and even mootools ones dont work.
Any help would be greatly and warmly welcomed.
Thanks
UPDATE
I have tried echoing inside the javascipt and it is just blank, the one thing as you have said i haven't tried using php to echo the whole javascript
Your own solution isn't very clean, and it has several bugs. You should do this instead:
<?php
$newsContent = '';
while ($row = mysql_fetch_assoc($query))
{
if ($newsContent != '')
$newsContent .= ', ';
$newsContent .= htmlspecialchars($row['news_content']);
}
?>
<script language="JavaScript1.2">
var marqueewidth="780px"
var marqueeheight="50px"
var marqueespeed=2
var marqueebgcolor=""
var pauseit=1
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):'
var marqueecontent='<nobr><font face="Arial"><h3><?php echo addslashes($newsContent); ?></h3></font></nobr>'
////NO NEED TO EDIT BELOW THIS LINE////////////
...
Using your example: marqueecontent='<nobr><font face="Arial"><h3>PHP HERE</h3></font></nobr>' it should look something like this
marqueecontent='<nobr><font face="Arial"><h3><?php echo "Hello From PHP"; ?></h3></font></nobr>'
Keep in mind that for PHP to pass any data o JavaScipr it must be echoed from PHP.
Thank you for your helpful comments as a result this is the solution i have found myself:
Using php to echo the javascript:
<?php echo'<script language="JavaScript1.2">
var marqueewidth="780px"
var marqueeheight="50px"
var marqueespeed=2
var marqueebgcolor=""
var pauseit=1
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):'
?>
var marqueecontent='<nobr><font face="Arial"><h3><?php while($row = mysql_fetch_assoc($query)){ echo $row['news_content'];}?></h3></font></nobr>'
////NO NEED TO EDIT BELOW THIS LINE////////////
marqueespeed=(document.all)? marqueespeed : Math.max(1, marqueespeed-1) //slow speed down by 1 for NS
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var iedom=document.all||document.getElementById
if (iedom)
document.write('<span id="temp" style="visibility:hidden;position:absolute;top:-100px;left:-9000px">'+marqueecontent+'</span>')
var actualwidth=''
var cross_marquee, ns_marquee
function populate(){
if (iedom){
cross_marquee=document.getElementById? document.getElementById("iemarquee") : document.all.iemarquee
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
cross_marquee.innerHTML=marqueecontent
actualwidth=document.all? temp.offsetWidth : document.getElementById("temp").offsetWidth
}
else if (document.layers){
ns_marquee=document.ns_marquee.document.ns_marquee2
ns_marquee.left=parseInt(marqueewidth)+8
ns_marquee.document.write(marqueecontent)
ns_marquee.document.close()
actualwidth=ns_marquee.document.width
}
lefttime=setInterval("scrollmarquee()",20)
}
window.onload=populate
function scrollmarquee(){
if (iedom){
if (parseInt(cross_marquee.style.left)>(actualwidth*(-1)+8))
cross_marquee.style.left=parseInt(cross_marquee.style.left)-copyspeed+"px"
else
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
}
else if (document.layers){
if (ns_marquee.left>(actualwidth*(-1)+8))
ns_marquee.left-=copyspeed
else
ns_marquee.left=parseInt(marqueewidth)+8
}
}
if (iedom||document.layers){
with (document){
document.write('<table border="0" cellspacing="0" cellpadding="0"><td>')
if (iedom){
write('<div style="position:relative;width:'+marqueewidth+';height:'+marqueeheight+';overflow:hidden">')
write('<div style="position:absolute;width:'+marqueewidth+';height:'+marqueeheight+';background-color:'+marqueebgcolor+'" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">')
write('<div id="iemarquee" style="position:absolute;left:0px;top:0px"></div>')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+marqueewidth+' height='+marqueeheight+' name="ns_marquee" bgColor='+marqueebgcolor+'>')
write('<layer name="ns_marquee2" left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed"></layer>')
write('</ilayer>')
}
document.write('</td></table>')
}
}
</script>
Thanks Again!!

Categories