How can i add this script in php - php

am trying to find out how to add this script to my php file , as i try echo it ,its not working.
am sure there is a way to add this, its my first time adding these scripts to php file ,maybe il learn something today and remmeber it thanks.
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
and the html div this is not needed to add to php as i have own div in php file
<div id="divID"></div>

Close the php tags, open a script tag, paste your script there, close your script tag, re-open your php tag. ;)
I recommend putting your js at the end of the file tho.
<?php
// your php here
?>
<div id="divID"></div>
<?php
// some php if you want to
?>
<script type="text/javascript">
//Your javascript here
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
</script>

Normally, you won't put javascript in your php file... But if there's no other solution:
<?php
echo"
<script type=\"text/javascript\">
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
</script>
";

In PHP pass js code into variable
<?php
$script = "<script type='text/javascript'>
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000); </script>";
?>
In HTML where you want to show/add
<html>
<head>
<?php echo $script; ?>
</head>
</html>

You can put it like this or you can put <script> part in the head of your page or in js file and include in page.
<?php
// code
?>
<script>
$( document ).ready(function() {
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
});
</script>
<div id="divID"></div>
Note: you also need jquery. If you don't use one you can include this in your page also
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
I just tested it and it's working perfectly. Currently my counter is
Refresh nr:51

Related

why getElementById dosn't work with <script>... tag but work with php echo '<script>

i have an select option on my page & to load syslogout.php according to selected option i wrote this code :
echo '<script type="text/javascript">$("#divSys").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
window.location="sysLogout.php?sysid="+document.getElementById("divSys").value;
}
$(this).data("isopen", !open); });
</script>';
it's work fine. but this code :
<script type="text/javascript">$("#divSys").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
window.location="sysLogout.php?sysid="+document.getElementById("divSys").value;
}
$(this).data("isopen", !open); });
</script>
it isn't work and return value for sysid is fix (1 or 2 for instance) for all option.
why?
Wrap your code in $(document).ready(). This should resolve your issue:
<script type="text/javascript">
$(document).ready(function () {
$("#divSys").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
window.location="sysLogout.php?sysid="+document.getElementById("divSys").value;
}
$(this).data("isopen", !open);
});
});
</script>
Try this:
<script type="text/javascript">
$(document).ready(function () {
$("#divSys").mouseup(function() {
var open = $(this).data("isopen");
if(open) {
window.location="sysLogout.php?sysid="+$(this).val();
}
$(this).data("isopen", !open);
});
});
</script>

Is it possible to insert php variables into your js code? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
passing variables from php to javascript
I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.
Basically:
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!
Yes, if you include the <script> section in your PHP code, you can do something similar to the following:
<script>
var foo = <?php echo $foo; ?>;
</script>
In your case, you would be looking into the following code structure:
<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid with the one you have included.
Enjoy and good luck!
EDIT:
<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>
You can do it like this :
$(location).attr('href','<?php echo $cid ?>');
The javascript code doesn't know it comes from php, it appears as a constant (a literal) for it.
Yes it is possible. All you have to do is put your <?PHP echo $cid; ?> in where you need it
<script>
$(function ()
{
$('#rc_desc<?PHP echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?<?PHP echo $cid; ?>');
});
});
This is possible because by the time the scrip is put into the page the cid has already been replaced by the string on the server. Since PHP is server driven, before it spits back the html/script it will be just like you put it in yourself.
There is almost no way to actually communicate PHP and JavaScript. However, the best and simplest way is to set the ID within an attribute. The new HTML5 data attributes would be perfect.
For example, have a anchor tag with
<span data-id="22">some event</a>
and then:
$(this).attr('href','student.php?'+$(this).attr('data-id'));
Or just use
<?php echo $id; ?>
if it is not external JS file
Try this code
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
$(location).attr('href','student.php?' + $(this).attr("data-id"));
// if you want to redirect the page do this
// window.location.href = 'student.php?' + $(this).attr("data-id");
});
});
</script>
I think you block should be :
<script>
$(function ()
{
<?php foreach($courses as $cid=>cinfo) : ?>
$('#rc_desc<?php echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid; ?>').click(function ()
{
$(location).attr('href','student.php?<?php echo $cid; ?>');
});
";?>
<?php endforeach; ?>
});
</script>
UPDATE
But you don't really need to do this, you have
"<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
You can try this
$(function (){
$('.rc_desc').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
attrId = $(this).attr("data-id");
$(location).attr('href','student.php?'+id);
});
});

Ajax Auto Refresh php file in html

I'm a bit new to Ajax.
I've got a Ajax file which includes a php file and refreshes it every X seconds. That code for AJAX.PHP is:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script language="JavaScript">
setInterval( "SANAjax();", 10000 ); ///////// 10 seconds
$(function() {
SANAjax = function(){
$('#dataDisplay').fadeOut("slow").load('rand.php').fadeIn("slow");
}
});
</script>
<div id="dataDisplay"></div>
This code is working fine.
Bbut the html of AJAX.PHP page shows as it is code, while I want the output html of rand.php not javascript code given above. How can i do it?
suppost "rand.php" html out put (source) is: < html >< body >this is body <\ body ><\ html >.
I want this html to be shown on the html source of AJAX.PHP.
How can i do it?
If I mess any thing let me know, I'll try to make it more clear.
You need to run it. Not insert only as file.
$.post("rand.php", { },
function(data) { $('#dataDisplay').html(data) });
updated:
SANAjax = function(){
$.post("rand.php", { },
function(data) { $('#dataDisplay').fadeOut("slow").html(data).fadeIn("slow"); });
}
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_rand').load('rand.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<div id="load_rand"> </div>
Don't forget to add the jquery library

PHP Script with Arguements to AJAX Auto Refresh

I would like to create a PHP page which accepts an arguement like so:
http://localhost/page.php?topic=Foo
and then pulls data from an SQL Database where topic=Foo but then automatically checks for new data every 10 seconds and refreshes a DIV tag using Ajax. I've tried and nothing works. Any help?
EDIT: here is the code I've used:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
ext = <?php $_GET[feedtitle] ?>
$(document).ready(function() {
$("#responsecontainer").load("response.php?ext=" + ext);
var refreshId = setInterval(function() {
$("#responsecontainer").load('response.php?ext=' + ext);
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
EDIT: I can do the SQL bit, it's just the getting the arguement to the response.php im having issues with.
EDIT: I have new code, but its still not working:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function gup( name )
{ name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
var feed = gup('f');
$(document).ready(function() {
$("#responsecontainer").load("response.php?ext=" + feed);
var refreshId = setInterval(function() { $("#responsecontainer").load('response.php? ext=' + feed); }, 9000);
$.ajaxSetup({ cache: false });
});
</script>
</head>
<body>
<div id="responsecontainer">
</div>
</body>
So, you need to
Get escaped URL parameter
,
output the jquery $.post function's result data and then you just need to know
How to refresh page with jQuery Ajax? and do an
AJAX Div Retrieval every 60 seconds?
I hope that helps :)

jquery load not reading string as variable (php hybrid)

I'm writing out a javascript string to be parsed by jquery - it works fine as an alert but not in the jquery load function
PHP:
$imgData = 'http://www.domain.com/_image.php/_MG_4156.jpg' ;
which is a php script to generate a thumbnail on the fly
<script type='text/javascript' language='javascript' charset='utf-8'>
<!--
var chart1img_".$i_gall." = new Image();
var imgData = '".$imgData."';
$(chart1img_".$i_gall.").load(function () {
$(this).hide();
$('#thumb_img_div_".$i_gall."').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
//}).attr('src', 'http://www.domain.com/_image.php/_MG_4156.jpg');
//-->
</script>";
If I hardcore the string it works.
If I use it as the imgData variable it fails, but the alert works using imgData
Tried string combos all ways. Defeated. Any ideas?
you need add php tags in your code
<script type='text/javascript' language='javascript' charset='utf-8'>
<!--
var chart1img_"<?php echo $i_gall;?>" = new Image();
var imgData = '<?php echo $imgData?>';
$("chart1img_<?php echo $i_gall;?>").load(function () {
$(this).hide();
$('#thumb_img_div_<?php echo $i_gall;?>').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
//}).attr('src', 'http://clients.flatearth.co.uk/benhopper/project/_image.php/_MG_4156.jpg');
//-->
</script>";
Using closures will give you a cleaner code.
Also, use json_encode to send values to JavaScript.
For example,
echo "
<script type='text/javascript'>
(function() {
var image = new Image(),
imgData = " . json_encode($imgData) . ",
i_gall = " . json_encode($i_gall) . ";
$(image).load(function () {
$(this).hide();
$('#thumb_img_div_' + i_gall).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
})();
</script>";
This minimizes the number of embedded PHP value be defining them as JavaScript variables.
You can also put them in functions:
<script type='text/javascript'>
function loadAndShowImage(imgData, i_gall) {
var image = new Image()
$(image).load(function () {
$(this).hide();
$('#thumb_img_div_' + i_gall).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
}
</script>
and then output just the dynamic parts:
echo "
<script type='text/javascript'>
loadAndShowImage(" . json_encode($imgData) . ", " . json_encode($i_gall) . ");
</script>";
Not sure what the problem is other than it's one of the characters in the full variable?:
var imgData = 'http://www.domain.com/_image.php/".$r_gall['image']."?width=145&height=205&cropratio=145:205&image=/images_cms/".$r_gall['image']."';
But I kept as much of the string in JS and just replaced the dynamic parts with PHP

Categories