How do I call a javascript function in a PHP generated script? - php

I have one problem. I have a popup and after a user creates a room in the popup, I want to close that popup and then redirect the opener window to a new url. I have the function and everything, except for I do not know how to call the function. (Below I have written where I want the function to load).
Thanks
<?php session_start(); ?>
<script type="text/javascript">
function CloseAndRefresh()
{
opener.location.href = "<?php echo $website_url; ?>/livechat.php?idim=<?php echo $perdorusi2; ?>&room=<?php echo $emri; ?>";
opener.focus();
self.close();
}
</script>
<?php
include_once('db.php');
$perdoruesi = $_GET['perdoruesi'];
if( strlen($_SESSION['id']) > '0' ) { $perdorusi2 = $_SESSION['id']; } else { $perdorusi2 = $perdoruesi; }
function makeRandomString($max=8) {
$i = 0;
$possible_keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$keys_length = strlen($possible_keys);
$str = "";
while($i<$max) {
$rand = mt_rand(1,$keys_length-1);
$str.= $possible_keys[$rand];
$i++;
}
return $str;
}
$emri = makeRandomString();
$hidhnedb = mysql_query("INSERT INTO dbname(`row1`, `row2`) VALUES(NULL, '$emri')");
if($hidhnedb) {
$max=count($_SESSION['mysession']);
$i = $max + 1;
$_SESSION['mysession'][$i][$emri] = $emri;
?>
***Here is the the place where I want to call the javascript function but I do not know how to do that.***
<?php
} else { echo "Error!"; }
?>

What you named "popup" is not really clear: is it another browser window ? An window.confirm or window.alert dialog ? a popup like in jQueryUI or Twitter Bootstrap ?
Let's assume it's a browser window.
You have two possibilities:
1 - Make a single button to close your popup:
<button onClick="CloseAndRefresh()">Close</button>
2 - Trigger it automatically after N seconds:
<script type="application/javascript">
var n = 5;
setTimeout(CloseAndRefresh, 1000*n);
</script>

Try
<script type="text/javascript">
CloseAndRefresh();
</script>
Although a PHP redirect would probably fit your purpose better.
Here is an article on PHP redirects:
http://php.about.com/od/learnphp/ht/phpredirection.htm

You can't invoke Javascript functions from PHP as PHP is running on the server, whereas Javascript is downloaded and run on the client, long after the PHP code has executed. You can however print a <script> tag where you, in this case, invoke the Javascript function you want:
<?php
echo '<script>(function () { CloseAndRefresh(); } ());</script>';

Related

Automatically updating chatbox

So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.

Php Sessions and Ajax

Within my index.php file I have an AJAX function that will call a function within another php file which should increment a number and return it whenever i call the AJAX function.
The problem is that the number never changes. I have tried lots of different things. Too many to list them all unfortunately.
My index.php file.
<?php
session_start();
$_SESSION['views'] = 0;
?>
<?php include 'blogFunction.php';?>
<script type="text/javascript">
function doSomething()
{
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
}
</script>
<div class ="blog" id = "blog"></div>
my blogFunction.php
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Right now the output is always '1' whenever i hit the button that calls the AJAX function.
Any help appreciated.
Live Code:here
Thank you all for the help so far. One problem down, a new problem appears.
Extended Functionality:
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$request_url = "http://retrovate.tumblr.com/api/read?type=posts";
$xml = simplexml_load_file($request_url);
$a = $_SESSION['views'];
$b = $_SESSION['views'] +4;
echo "A = ".$a;
echo "B = ".$b;
$_SESSION['views'] = $_SESSION['views']+ 1;
for ($i = $a; $i <= $b; $i=$i+1) {
echo '<h2>'.$xml->posts->post[$i]->{'regular-title'}.'</h2>';
echo '<br>';
echo $xml->posts->post[$i]->{'regular-body'};
echo '<br>';
echo '<br>';
}
}
The problem that lies here, is, I click my button once at my site
and it increments and shows the new content. I click again and it reverts back to 0. If I click the button numerous times fast, it seems to work. It seems that chrome is having this problem whereas Firefox is not.
Add session_start(); to blogFunction.php
Here's the properly working code...
index.php
<?php
session_start();
$_SESSION['views'] = 0;
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js" />
<body>
<div class ="blog" id = "blog"></div>
<input type="button" value="Add to the count!" id="call_ajax"/>
<script type="text/javascript">
$('#call_ajax').click(function () {
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
});
</script>
</body>
blogFunction.php
<?php
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Notice that I'm not including blogFunction.php in the index.php file! That's important.
The other way you had it, you were setting the variable to 0 each time the page loaded, which was how the function was called (if you used the console to call it).
I added a button for you to click to call the function via Ajax (per your conditions in the original question).
Hope that helps!
You need to call session_start () in your blogFunction.php file. It has to be called before any output to the brower. Probably best case would be to call it first in the script.
I think that you should first unset $_SESSION['views'] and than write again.
function blogreturn(){
$temp = $_SESSION['views'];
unset($_SESSION['views']);
$_SESSION['views'] = $temp + 1;
echo "THIS number is:" .$_SESSION['views'];
}

Endless Pagination Help Jquery/PHP

i am trying to code endless pagination and having a trouble
$(document).ready(function(){
function lastPostFunc()
{
$('div#lastPostsLoader').html('<div class="load"><div class="label"><font color="black"><b>Loading more...</b></font></div></div>');
$.post("cr/sc/scr.php?lastID="+$(".comment:last").attr("id"),
function(data){
if (data != "") {
$(".comment:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
});
here goes my php
$result = mysql_query('SELECT * FROM xyz ORDER BY sy DESC LIMIT 15');
while($row = mysql_fetch_object($result)) {
$i++;
echo "<div class='comment' id='" . $i. "'>";
}
and other page to grab data
$pg = $_GET['lastID'];
$i=$pg;
$result = mysql_query('SELECT * FROM xyz ORDER BY sy DESC LIMIT '.$pg.',15');
while($row = mysql_fetch_object($result)) {
$i++;
echo "<div class='comment' id='" . $i . "'>";
}
Im getting a problem in getting value of comment:last
i get 15 value of comment:last after 1st time event loads
i get 15 value of comment:last after 2nd time event loads
which is problem im expecting 30
and on 3rd time event occures it gives 30
and same proccess again 30,30,40,40,50,50
instead of 30,40,50,60,70,80
i tried jquery live(), and i used $_GET cause im fetching from URL
Check to see if you are loading the function somewhere else, because the function loads and stops on mine, and the only way I can get it to mimic what you say is if I load the function again on page load, which will create two calls at the same time. Causing 1-15 and 1-15 and the last number off the page. Then on scroll it loads the function as it's supposed to and keeps on loading, just as you tell it too.
Plus, make sure you are checking that get (or even if you use a post) that goes directly into your database. That is asking for an injection.
EDIT: You should probably load full page (and past) first if you have the data. Then load the scroll function, which won't load if the page isn't full. Which is why it stopped for me.
EDIT2: This is the code I was using in case you want to see. I made a mock database, so I didn't have to match a db to test.
<?php
$scroller = 30;
if ( isset($_GET['hold']) && $_GET['hold'] == '1' ) {
$i = isset($_GET['lastID'])?(int)$_GET['lastID']:0;
$j = $i + $scroller;
//sleep(10);
while( $i < $j ) { // mimic a mysql call and spit it out.
++$i;
echo "<div class='comment' id='${i}'>${i}</div>";
}
exit;
}
?>
<html>
<head>
<script src="jquery-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
// I was doing something else with this, but stripped out the code
var scroller = <?php echo $scroller;?>;
$(document).ready(function(){
function lastPostFunc()
{
// this assumes there are already comments on the page, so put a dummy comment
var last = $(".comment:last").attr("id");
$('div#lastPostsLoader').html('<div class="load"><div class="label"><font color="black"><b>Loading more...</b></font></div></div>');
$.post("<?php echo $_SERVER['PHP_SELF']; ?>?hold=1&lastID="+last,
function(data){
if ( data != "" ) {
$(".comment:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
lastPostFunc();
});
</script>
</head>
<body>
<div class="comment_container">
<div class="comment" id="0"></div>
<div id="lastPostsLoader"></div>
</div>
</body>
</html>

Dynamic loading JavaScript from AJAX - fails?

I have a problem with dynamic loading of javascript function from Ajax.
I want to update some part of HTML with Ajax. Let's say I want to place a button and to attach a javascript function to that button dynamically.
For example:
...
<head>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function f_OnLoadMain()
{
fParseBrowserInfo();
getJSFromServer();
getHTMLFromServer();
}
</script>
</head>
<body onload="f_OnLoadMain()">
<div id="AjaxArea" width="100%" height="100%" align="left" valign="top" >
<!-- Updated with ajax -->
</div>
</body>
</html>
----- getJSFromServer() - calls to php code:
<?php
$somesource = '
function Clicked(){
alert("Clicked");
}
';
class TestObject{
public $source = "";
function TestObject()
{
$this->source = "";
}
function setSource($source){
$this->source = $source;
}
}
$ti = new TestObject();
$ti->setSource($somesource);
echo(json_encode($ti));
?>
the script is inserted with:
var oHead = document.getElementsByTagName('HEAD').item(0);
if (oScript){
oHead.removeChild(oScript);
}
oScript = document.createElement("SCRIPT");
oScript.type = 'text/javascript';
oScript.text = oScript.source;
oHead.appendChild( oScript);
And getHTMLFromServer() - call php :
<?php
$error = 0;
$someText = '
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
';
class TestObject{
public $src = "";
public $error = 0;
function TestObject()
{
$this->error = 0;
$this->src = "";
}
function setSrcString($sample){
$this->src = $sample;
}
}
$ti = new TestObject();
$ti->error = $error;
$ti->setSrcString($someText);
echo(json_encode($ti));
?>
Then the content is updated with:
var dynamicArea = document.getElementById("AjaxArea");
if(dynamicArea != null)
{
dynamicArea.innerHTML = obj.src;
}
And that works fine!
So, when the page loads the button is displayed ok, BUT pressing button doesn't call function Clicked().
Someone knows how to fix it?
Regards!
i guess you have to escape your apostrophe:
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
you see: onclick="Clicked()"
Together with: function Clicked(){ alert("Clicked"); }
It renders to: onclick="alert("clicked")"
Try to escape your apostrophe :)
Regards

jQuery/PHP Hide Div, Update Information from MySQL, Show Div New Information

jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});

Categories