PHP messaging system is slow - php

I am building a simple messaging system for my website and it seems to be slow and sometimes crashes the browser. Below is the code.
First i wrote an ajax request to get all user chat from database
setInterval(function () {
$.ajax({
type: "GET",
url: "get_chat.php",
dataType: "html",
success: function (response) {
$(".msgView").html(response);
if (response !== lastResponse) {
var audio = new Audio('audio/solemn.mp3')
audio.play()
}
lastResponse = response
}
});
}, 2000);
here is get-chat.php
<?php
$us_id = $_SESSION['log_id'];
//echo empty($_SESSION['hash']) ? 'not set' : $_SESSION['hash'];
$hasher = $_SESSION['hash'];
$mesql =<<<EOF
SELECT from_id, message FROM messager WHERE group_hash = '$hasher';
EOF;
$meret = $db->query($mesql);
while ($merow = $meret->fetchArray(SQLITE3_ASSOC))
{
$from_id = $merow['from_id'];
$messages = $merow['message'];
$usql =<<<EOF
SELECT * FROM users WHERE userid = '$from_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urow['fname'];
$from_img = $urow['profimages'];
if ($from_id != $_SESSION['log_id']) {
echo '
<div class="recMsgBubble">
<div class="recBubbleImg"><img src="'.$from_img.'"></div>
<div class="recBubbleMsg">'.$messages.'</div>
</div>';
//<div class='from_bubble'><div class='from_img'><img src='$from_img'></div><p>$messages</p></div><br>
} else {
echo '
<div class="userMsgBubble">
<div class="userBubbleImg"><img src="'.$from_img.'"></div>
<div class="userBubbleMsg">'.$messages.'</div>
</div>';
//<div class='rep_bubble'><div class='rep_img'><img src='$from_img'></div><p>$messages</p></div><br>
}
}
$csql =<<<EOF
SELECT * FROM banks WHERE bname = '$from_id';
EOF;
$cret = $db->query($csql);
while ($crow = $cret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $crow['bname'];
$from_img = $crow['banklogo'];
if ($from_id = $from_fname) {
echo '<div class="recMsgBubble">
<div class="recBubbleImg"><img src="'.$from_img.'">
</div>
<div class="recBubbleMsg">'.$messages.'</div>
</div>';
} else {
echo '<div class="userMsgBubble">
<div class="userBubbleImg"><img src="'.$from_img.'">
</div>
<div class="userBubbleMsg">'.$messages.'</div>
</div>';
}
}
}
?>
Also to send the chat, an ajax request is used as below
$("#msgSender").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "send_chat.php",
data: $(this).serializeArray(),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
}
});
$('#userMsgField').val("");
});
Here is send_chat.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['userMsgField']) && !empty($_POST['userMsgField']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['userMsgField'];
$hash = $_SESSION['hash'];
$flag = 0;
$sql =<<<EOF
SELECT * FROM connect WHERE (user_one = '$my_id' AND hash = '$hash') OR (user_two = '$my_id' AND hash = '$hash');
EOF;
$ret = $db->query($sql);
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$user_one = $row['user_one'];
$user_two = $row['user_two'];
if ($user_one == $my_id)
{
$to_id = $user_two;
}
else
{
$to_id = $user_one;
}
$isql =<<<EOF
INSERT INTO messager (message, group_hash, from_id, flag, to_id) VALUES (:message, :group_hash, :from_id, :flag, :to_id);
EOF;
$bsql =<<<EOF
INSERT INTO chatportal (message, group_hash, from_id, flag, to_id)
VALUES (:message, :group_hash, :from_id, :flag, :to_id);
EOF;
$stmt = $db->prepare($isql);
$bstmt = $db->prepare($bsql);
$stmt->bindValue(':message', $rep_msg, SQLITE3_TEXT);
$stmt->bindValue(':group_hash', $hash, SQLITE3_INTEGER);
$stmt->bindValue(':from_id', $my_id, SQLITE3_INTEGER);
$stmt->bindValue(':flag', $flag, SQLITE3_INTEGER);
$stmt->bindValue(':to_id', $to_id, SQLITE3_TEXT);
$bstmt->bindValue(':message', $rep_msg, SQLITE3_TEXT);
$bstmt->bindValue(':group_hash', $hash, SQLITE3_INTEGER);
$bstmt->bindValue(':from_id', $my_id, SQLITE3_INTEGER);
$bstmt->bindValue(':flag', $flag, SQLITE3_INTEGER);
$bstmt->bindValue(':to_id', $to_id, SQLITE3_TEXT);
$result = $stmt->execute();
$bresult = $bstmt->execute();
if ($reuslt && $bresult)
{
echo "GHood";
}
}
}
I think the reason for it being slow is that it tries to get the messages every 2 seconds. If this is the issue, please how do i fix?
If not what is the solution to this problem? Thanks in advance.

PHP messaging system is slow if you build it from scratch. I use JQuery before but after ES7 and ES8 I starting using the native javascript and it was faster than jquery. There are 3 things you can do to at-least speed it up:
Do not use the jQuery Ajax use the native Ajax, since jQuery is a very large library to load and risky, to begin with.
Buy or use a faster server.
Prevent retrieving the entire message conversation every time the user inputs a message. Use a script that would only get the values that were added during the conversation and limit the message history per view.
You can search the ajax syntax from here https://blog.garstasio.com/you-dont-need-jquery/ajax/

Related

PHP not returning any data when sent an ajax request

When I send an ajax post request to my getMessages.php file it doesn't return anything.
I've tried manually setting the array values and printing them in the console and that seems to work.
getMessages.php
<?php
require_once "mysqli.php";
$data = array();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$data['startuser'] = $row['msg_startuser'];
$data['msg'] = $row['msg'];
}
}
echo json_encode($data);
exit;
?>
js ajax
function getChat() {
$.ajax({
url: 'getMessages.php',
type: 'POST',
data: {getChat: 'yes'},
dataType: 'JSON',
success: function(data) {
// testing
console.log(data.startuser, data.msg);
}
})
}
I want it to print out in the console for testing.
Hi you can try this way:
The php script :
<?php
require_once "mysqli.php";
session_start();// start the session
$data = array();
if (isset($_SESSION["username"])) {
if (isset($_POST["endUser"]) && isset($_POST["action"])) {
$case = $_POST["action"];
$endUser = $_POST["endUser"];
$username = $_SESSION["username"];
switch (case) {
case 'getChat':
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = '{$endUser}'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = '{$endUser}' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_assoc($resultado)) {
if (isset($row['msg_startuser']) && isset($row['msg'])) {
$temp = array(
"user"=>$row['msg_startuser'],
"msg"=>$row['msg']
);
}
$data[] = $temp;
}
echo json_encode($data);
break;
}
}
}else {
echo "error-403";
}
?>
The javascript :
function getChat() {
return $.ajax({
url: 'getMessages.php',
type: 'POST',
data: {action: 'getChat',endUser:'mariokiller470'},
dataType: 'JSON'
})
}
getChat()
.done(function(response){
console.log(response);
})
Hope it Helps
data is overwritten in the loop again and again, I guess you would like to do something like this:
$x = 0;
while ($row = mysqli_fetch_array ($result)) {
$data[$x]['startuser'] = $row['msg_startuser'];
$data[$x]['msg'] = $ row['msg'];
$x++;
}
Ooops!
I forgot to start the session!
Thanks PatrickQ!
This will solve the problem since you are returning response as objects
An Updates:
You will need to initialize session
and data parameters for an array should be inside the the if statements
Try code below
<?php
require_once "mysqli.php";
session_start();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$data = array();
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$startuser = $row['msg_startuser'];
$msg = $row['msg'];
$data = array("startuser" =>$startuser, "msg" =>$msg);
}
echo json_encode($data);
exit;
}
?>
so in ajax console. this line of code will work fine
console.log(data.startuser, data.msg);

PHP no results message still showing when posting data via ajax

I'm creating a comment facility for a blog post using PHP and ajax to post the comment so the page does not refresh after a comment is posted.
This is the code that displays the comments when the page is visited. If there are no comments for the post it displays a notice. This all works.
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $row["comment"];
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
}
}else{
$comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}
When the comment form is submitted it calls this function.
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
success: function (response) {
document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
$("#summernote").summernote("reset");
},
});
}else {
alert('Please enter a comment');
}
return false;
});
This is the post_comment.php page
if(isset($_POST['comment'])){
$comments = "";
$comment=$_POST['comment'];
$member_id =$_POST['member_id'];
$post_id =$_POST['post_id'];
if(isset($comment)) {
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = $entry_id
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $comment;
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
echo $comments ;
};
exit;
}
}
}else {
header("location: /blog");
exit;
}
If you are the first to comment on a post the comment displays but the "Be the first to comment" notice is still displaying until the page is refreshed.
Try return the response from the server as json. Plus remove the exit and header on your server side.
<script type="text/javascript">
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
dataType : "json",
encode : true,
success: function (data) {
$.each(data, function(index, element){
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>");
});
$("#summernote").summernote("reset");
$('.alert').empty();
},
});
}else {
alert('Please enter a comment');
}
return false;
});
</script>
Then your server side.
<?php
if (isset($_POST['comment'])) {
$comment = $_POST['comment'];
$member_id = $_POST['member_id'];
$post_id = $_POST['post_id'];
$commentsArray = array();
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = ?
ORDER BY comm.comment_date DESC");
$sql->bind_param("ii", $post_id, $entry_id);
$sql->execute();
$sql_result = $sql->get_result();
if ($stmt_result->num_rows > 0) {
while ($row = $stmt_result->fetch_assoc()) {
$comment_date = date_create($row['comment_date']);
$commentsArray[] = array(
'comment' => $comment,
'post_date' = date_format($comment_date, ' l jS F Y H:i');
'comment_author' => $row['member_screen_name']
);
}
}
echo json_encode($commentsArray);
}
Also use the network tab on your browser console to see the response coming from the server.
it is normal for him to behave like this, and at no time will you ask the notification not to appear after the comment.
update your code after the success
$('.alert-primary').hide()

Retrieving Database Data during LogIn

I'm currently using Slim and Ajax to develop a mobile application. In my database I have a column which stores session codes for logins. I need to be able to once logged in, compare the username entered to the database and retrieve the sessionCode based on that.
My current PHP is this:
$app->post('/logIn/', 'logIn');
function logIn()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where username=:username AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $q->username);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
$row=$stmt->fetch(PDO::FETCH_OBJ);
//$verify = password_verify($q->password, $row['password']);
$db = null;
echo json_encode($row);
} catch (PDOException $e) {
echo $e->getMessage();
}
} //PHP 5.4 LogIn
$app->get('/getSessionCode/:username','getSessionCode');
function getSessionCode($username)
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "SELECT * FROM users WHERE username=:username";
try{
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $username);
$stmt->execute();
$row=$stmt->fetchALL(PDO::FETCH_OBJ);
$dbh=null;
echo json_encode($row);
}
catch(PDOException $e){
if(db != null) $db = null;
echo $e->getMessage();
}
}
Ajax Code:
$("#checkLogIn").click(function()
{
username = $("#enterUser").val();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
success: function(data)
{
if(data != false)
{
$.ajax({
type: 'GET',
url: rootURL + "/getSessionCode/" + username,
dataType: "json",
success: sessionData
});
}
else
{
alert("Username and/or Password was incorrect");
}
}
})
});
function checkLogIn(data)
{
return JSON.stringify({
"username": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
function sessionData(data){
session = data.sessionCode;
alert(username);
alert(session);
$.mobile.changePage("#mainMenu");
}
When I run the application and log in. It runs though no problem but when it reaches alert(session) it returns undefined. I have both session and username set globally as variables so that isn't an issue and when it reaches alert(username), it returns the username I entered.
I was able to solve my issue by adding in a for loop into the sessionData function
function sessionData(data){
for(var i = 0; i < 1; i++)
{
sessionStorage.code = data[i].sessionCode;
}
$.mobile.changePage("#mainMenu");
}

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

Ajax post success function returning both success and error

Okay so I am trying to get ajax to post to my php file, lookup a mysql field and if it exists echo 'clientsuccess' otherwise echo 'Client already exists'
but on success function it returns both values despite the fact that they're in an php if statement.
I am quite possibly missing something incredibly simply, but any help is greatly appreciated.
PHP:
<?php
session_start();
$clientArray = $_POST['clientArray'];
$clientArray = explode(',', $clientArray);
$count = 0;
foreach($clientArray as $clientField)
{
trim($clientField);
if(empty($clientField)) {
$clientField = '-';
}
}
$con = mysql_connect("localhost",$_SESSION['MysqlUser'],$_SESSION['MysqlPass']);
if (!$con)
{
die('Could not connect with '.$_SESSION['MysqlUser'].mysql_error());
}
mysql_select_db("smeinsti_SPW_Inventory", $con);
$checkclient = mysql_query("SELECT ClientName FROM Clients WHERE ClientName = '".$clientArray[0]."'", $con);
if(mysql_num_rows($checkclient)==0)
{
$sql="INSERT INTO Clients (`ClientName`, `PhoneNumber`, `Email`, `Address`, `OrderDate`)
VALUES
('$clientArray[0]', '$clientArray[1]', '$clientArray[2]', '$clientArray[3]', CURDATE())";
$clientArray[0] = $_SESSION['ClientName'];
echo "clientsuccess";
} else {
echo 'Client already exists';
}
?>
JS:
function NextPage()
{
var ClientData = [];
$('form#order-form.create input[type=text]').each(function() {
ClientData += $(this).val() + ',';
})
alert(ClientData);
var parameters = {
clientArray: ClientData
};
$.ajax({
type: "POST",
async:false,
url: "write_client.php",
data: parameters,
success: function(result){
var res=result;
if(res = 'clientsuccess') {
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
}
});
}
Your condition Equal symbol is not correct! Put '=='
if(res == 'clientsuccess') { //Double Equal to
window.location = 'admin.php?id=7';
} else {
alert('Client already exists');
}
mysql_num_rows returns the number of selected rows and not the fields of a certain row. Use mysql_fetch_row to fetch the row you have selected with your query:
You could also use mysql_result to fetch a row and get a certain field:
$client exist = mysql_result($checkclient, 0, 0);
This fetches the first row (zero based) and returns the first field (zero based).

Categories