Jquery post causes apache to hang - php

I'm filling in element values in YUI panel (DOMInserted) via jquery
This is the php
<?php
$con = mysql_connect('sql', 'admin', '123');
mysql_select_db('sql');
$data_parent_type0 = mysql_real_escape_string($_POST['data_parent_type0']);
$result = mysql_query('SELECT id,name FROM email_templates WHERE description = "'.$data_parent_type0.'" AND deleted = 0');
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>' . "\n";
}
mysql_close($con);
?>
This is the JQUERY
$(document).bind('DOMNodeInserted', '#composeHeaderTable0', function(event) {
$("#data_parent_type0").click(function() {
var data_parent_type0 = $('#data_parent_type0').val();
//alert(data_parent_type0);
$.post("dbcall.php", { data_parent_type0: data_parent_type0},
function(result){
//alert(result);
$("#email_template0").html(result);
});
});
});
It works but causes Apache to hang.

Related

How to use a div id as a php var

I have the following function that pass to the div with id = "window", the value dbdata from the database.
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php');
)};
)};
How can I get the id value and use it in the php code below?
without refresh the page?
if ($id = $row["dbdata"]) { do something }
I added the rest of the code:
index.html
`<div id = "window"></div>`
`if ($id = $row["dbdata"]) {do something}`
`<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php')
}, 3000);
});
</script>`
crt.php
`<?php
$conn = new mysqli('localhost', 'root', '', 'user');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT id FROM data");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['dbdata'] . '<br>';
}
}
?>`
Thank you in advance.
You can pass values in URL parameters.:
$('#window').load('crt.php?id=window')
Then in your php code you can retrieve the parameter using:
$id = $_GET["id"];
a simple way could be assign the GET param in your jquery load url and use it in your php code
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php?id=window')
.
if ($_GET['id'] = $row["dbdata"]) { do something }
or you instead of load could use ajax get eg :
$.get( "crt.php?id=window", function( data ) {
alert( "Data Loaded: " + data );
});
in your crt.php
if ($_GET['id'] = $row["dbdata"]) {
return "hello!";
}

Ajax and PHP with a while loop issue

I have a ajax that needs to return some values, but if I use a while() to get all the result from my db, the return is "nothing". Where am I making mistake?
My Ajax script is posted below:
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg) {
var obj = jQuery.parseJSON(msg);
// Your count variable
var count = obj.count;
// Your not variable
var not = obj.not;
$('#msg_count').html(count);
$('#notification').html(not);
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "notification/select.php",
cache: false,
timeout: 50000,
success: function(data) {
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function() {
waitForMsg();
});
</script>
My php script is posted below:
$result = mysqli_query($con, "SELECT * from notification where tousername='$tousername' and isread = 0");
while ($row = mysqli_fetch_array($result)) {
$count = $result - > num_rows;
$not = $row['notification_msg'];
$res = [];
$res['count'] = $count;
$res['not'] = $not;
}
echo json_encode($res);
You are overwriting your results variable in the loop:
while (...) {
...
$res=[];
...
}
You probably want something like:
$res['count'] = $result->num_rows;
while($row = mysqli_fetch_array($result)) {
$res[]['not'] = $row['notification_msg'];
}
echo json_encode($res);
Overwrite your value with same index. you can write this.
while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
$res=[];
$res['count'][] = $count;
$res['not'][] = $not;
}
Or
while($row = mysqli_fetch_array($result)) {
$count = $result->num_rows;
$not=$row['notification_msg'];
$res=[];
$res[]['count'] = $count;
$res[]['not'] = $not;
}
echo json_encode($res);
die();
Write your js addmsg() function.
function addmsg(type, msg) {
var obj = jQuery.parseJSON(msg);
// Your count variable
for(prop in obj){
var count = obj[prop][count];
var not = obj[prop][not];
$('#msg_count').html(count);
$('#notification').html(not);
}
}
re-write your script
function waitForMsg(){
$.get("notification/select.php",function(callback){
console.log(callback); // here is your data in callback variabel you can in in console log
})
}
Replce this code with your php script.
$result = mysqli_query($con, "SELECT * from notification where tousername='$tousername' and isread = 0");
$res['count'] = $result->num_rows;
while($row = mysqli_fetch_array($result)) {
$res[]['not'] = $row['notification_msg'];
}
echo json_encode($res);

Issues with long polling and sessions (chat)

I made a friends chat that uses textfiles to store data and it all works more or less except when I sign in and write something to someone, nothing pops up (but the text is stored in the appropriate text file), then when I refresh the page it is ok from THEN ON, but on the other browser as the other user I have to also refresh the page in order for it to work normally both ways.
Basically, every time I log in I have to click the name of the person I want to chat with, then a window pops out and THEN i have to refresh or else it doen\sn't work.
I guess I have to kind of refresh the page whenever I click on a friend and want to chat with him and that it is a session problem.
here is home.php (users are redirected here when they log in on index.php page)
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">#import 'custom_chat.css';</style>
</head>
<body>
<h2>Hello, <?php echo $_SESSION['user']; ?></h2>
<hr>
<p><b>CONTACTS:</b></p>
<?php
require_once 'dbc.php';
$u = $_SESSION['user'];
$q = "SELECT user_id FROM users WHERE username='$u'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
// current user id
$uid = $row[0];
$q = "SELECT u.username FROM users AS u, friends AS f
WHERE (f.f1 = '$uid' OR f.f2 = '$uid') AND (f.f1 = u.user_id OR f.f2 = u.user_id) AND (u.username != '$u')";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($r)) {
echo '<div class=chat_contacts>';
echo '<div class='.$row['username'].'>';
echo '<div class=inner>';
echo '<div class=inner_chat></div>';
echo '<form>
<textarea class=chat_text></textarea>
</form>
';
echo '</div>'; // end .inner
echo '<a href="#" class='. $row['username'] .'>'.$row['username'] .'</a>
</div>';
echo '</div>'; // end .chat_contacts
}
?>
<p>HOME</p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
var nc = '<?php echo $u ?>';
// toggle chat window
$('.chat_contacts a').click(function() {
$(this).prev('div.inner').toggle();
var tc = $(this).attr('class');
$(this).parent().parent().addClass(nc+tc);
$('textarea').focus(); // MD maybe
return false;
});
// call main chat function
$(function () {
updateChat();
}); // end ready
//update on enter
$('textarea.chat_text').keypress(function(e) {
$this = $(this); // textarea
if (e.which == '13') {
insertChat();
return false;
}
});
function insertChat() {
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
alert(data)
}
});
}
var timestamp = 0;
function updateChat() {
$.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
async: true,
cache: false,
success:function(data) {
// alert(data);
var json = eval('('+data+')');
// if (json['msg'] != null) {
$('.chat_contacts.'+nc+json['nru']+' .inner_chat').append('<p>'+json['msg']+'</p>'); // MD
// }
timestamp = json['timestamp'];
setTimeout('updateChat()', 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('error '+textStatus+'('+errorThrown+')');
setTimeout('updateChat()', 1000);
}
});
}
</script>
</body>
</html>
update.php
<?php
session_start();
require_once('dbc.php');
error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(0);
$ou = $_SESSION['user'];
$ru = $_SESSION['ru'];
session_write_close();
$q = "SELECT * FROM chats WHERE
(chats.f1='$ru' AND chats.f2='$ou') OR (chats.f1='$ou' AND chats.f2='$ru') ORDER BY time DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
// $filename = 'vojaolja.txt';
$q = "SELECT user_id FROM users WHERE username='$ou'
ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$fu = $row[0];
$q = "SELECT user_id FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$su = $row[0];
$q = "SELECT username FROM users WHERE username='$ru' ORDER BY user_id DESC LIMIT 1";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_row($r);
$nru = $row[0];
if ($fu < $su) {
$filename = $fu.$su.'.txt';
} else {
$filename = $su.$fu.'.txt';
}
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$data = file($filename);
$line = $data[count($data)-1];
$response['msg'] = $line;
$response['nru'] = $nru;
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
Also, if someone wants to reproduce this on their own computer, I can post all the code here, it is just a few pages, it can be setup together with the database in literally 2 minutes.
EDIT:
as soon as I login, i see the following in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509358392 (plus the rolling thingy, it is waiting)
Then i click on a friend's name, window pops up, I write something and i get this in the console:
http://localhost/x_super_chat/insert.php
AND THEN WHEN I REFRESH AGAIN (when it actually starts working) I get the following in the console.
http://localhost/x_super_chat/update.php?timestamp=0&_=1374509491493
http://localhost/x_super_chat/update.php?timestamp=1374509435&_=1374509493231 + the waiting thingy icon, it is waiting
So it changes after refresh, I need what I get after refresh to be there as soon as I log in.
EDIT 2: (after Pitchinnate's answer)
As soon as I login, I see this in the console:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185 (plus the waiting animation)
Then I write something to the other person (say John), and I get the following:
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566749185
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566817682
http://localhost/x_super_chat/update.php?timestamp=1374565160&_=1374566817740
http://localhost/x_super_chat/update.php?timestamp=1374566817&_=1374566817801 (plus waiting animation)
THEN when I write something on the other side as John, I get the following: (this is from chrome so it is not the same as the console in firebug):
http://localhost/x_super_chat/update.php?timestamp=0&_=1374566987051
http://localhost/x_super_chat/insert.php
http://localhost/x_super_chat/update.php?timestamp=1374566995&_=1374567004175
http://localhost/x_super_chat/update.php?timestamp=1374567004&_=1374567004215
One thing you can try is cancelling your long poll upon insert, create a global javascript variable outside your update function var myajax;
myajax = $.ajax({
type: 'GET',
url: 'update.php?timestamp=' + timestamp,
Then on insert:
function insertChat() {
myajax.abort();
var text = $this.val();
$this.val('');
var ru = $this.parent().parent().parent().attr('class');
$.post('insert.php',{text:text, ru:ru}, function(data) {
if (data) {
updateChat();
}
});
}

workout with the php returned array to jquery

my this php code is working for the $.ajax call which is below this code
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
//$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[]=$row['imgurl'];
}
}
echo $imgurl;
jquery code
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#main-content').html(data);
}
});
});
});
it outputs just Array written at the #main-content div how to work with that array which are basically image paths
Why you create array from mysql result ? your code can be simpler like this:
<?php
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
if(mysql_num_rows($result) > 0)
{
//Fetch rows
while($row = mysql_fetch_array($result))
{
echo $row['imgurl'];
}
}
?>
Try you page from the browser directly. Using JSON can help here:
echo json_encode($imgurl);
and using getJSON instead of plain ajax:
$.getJSON('thegamer.php', {send_text:text}, function(data) { … });

JSON callback function only works with a text file

Does any one know why the call back only works with a text file
PHP
<?php include("alan.php"); ?>
<?php
$rows=array();
mysql_select_db('news') or die(mysql_error());
//echo "Connected to Database";<?php
$result = mysql_query("SELECT * FROM photos")
or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_assoc( $result )) {
$rows[]=$row;
}
echo json_encode($rows);
?>
This outputs:
[{"name":"photo1.jpg","id":"1"},{"name":"photo2.jpg","id":"2"},{"name":"photo3.jpg","id":"3"},{"name":"photo4.jpg","id":"4"}]
JavaScript:
$(document).ready(function() {
$('#photos').click(function(){
$.getJSON('photo_get.php',function(data){ /**Changing this to a text file works ????**/
$.each(data, function(key, val) {
alert("Data" + val.name);
});
});
});
});
have you tried setting the content type in the php page?
<?php
header("Content-Type: application/json");
?>

Categories