Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8520323
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T06:30:09+00:00 2026-06-11T06:30:09+00:00

i have already posted a similar question here, but failed to get a response

  • 0

i have already posted a similar question here, but failed to get a response that will fix my problem, also the problem has changed a bit so i’m re-posting and desperate to get some help!

link to previous question:

ajax long polling with mysql

CURRENT CODE:

JS(I run it from php):

$oldIDq = mysql_query("SELECT * FROM messages ORDER BY id DESC LIMIT 1");
while($oldrow = mysql_fetch_array($oldIDq)){
$oldID = $oldrow['id'];    
}

$func = '
var oldID = '.$oldID.';

function wait() {
$.ajax({
    type: "GET",
    url: "../scripts/msg_scripts/msg.php?oldid=" + oldID,
    async: true,
    cache: false,

    success: function (data){

        if(data != \'1\'){
            var json = eval(\'(\' + data + \')\');
             if (json[\'msg_content\'] != "") {
                  alert("new meassage added"); 
                  } 
                  oldID = json[\'oldID\']; 
                  setTimeout(\'wait()\',1000); }

    },

    disconnect: function()
    {
        return false;
        setTimeout(\'wait()\',1000);
    },

    error: function(XMLHttpRequest, textStatus, errorThrown){
      alert("error: " + textStatus + "(" + errorThrown + ")");  
      setTimeout(\'wait()\',1000);
    }

});
}

$(document).ready(function(){

    wait();
});
';

SERVER:

    $connect = mysql_connect ("localhost", "root", "")

or die ("couldnt connect");
mysql_select_db ("***") or die ("not found"); //if db was not found die
mysql_query("SET NAMES 'utf8'");

$oldID = $_GET['oldid']; 

if($oldID == "") {

die('timeout');
}
else{

$result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
    $last_msg_id = $row['id']; 
}
while($last_msg_id <= $oldID)
{
    usleep(10000);
    clearstatcache();
    $result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
    while($row = mysql_fetch_array($result))
    {
        $last_msg_id = $row['id'];
    }
}



$response = array();
$response['msg_content'] = 'new';
$response['oldID'] = $last_msg_id;
echo json_encode($response);
}

now, i had a session running on the server side of the process and i removed it for now because i understood that long polling has a problem with sessions i also have sessions running on the page which sends the ajax request, since i removed the session my problem has improved in a way, what happens now is that i can basically click on a link on my website and exit the page and get an error, but if i do it more than 4-5 times, the browser freezes an every click on any link just reruns the ajax function and i get a different error. if i refresh the page of the request i imidetly get the second error and the browser freezes. also if that’s helpful information if i close the browser and try to reopen any page of my site it doesn’t load at all unless i rerun my server(working on localhost right now) also tried it with chrome and ff.

can some one please point me towards the solution?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T06:30:11+00:00Added an answer on June 11, 2026 at 6:30 am

    — Updated again to retrieve all new messages

    Reading your code, you only wish to return the last message, if so then the while loops are in this case pretty useless. Do keep in mind that there might be more ‘new’ messages between the oldID and the last ID inserted into your database which you skip, so does this code I provide

    $connect = mysql_connect ("localhost", "root", "")
    or die ("couldnt connect");
    mysql_select_db ("***") or die ("not found"); //if db was not found die
    mysql_query("SET NAMES 'utf8'");
    
    $oldID = trim($_GET['oldid']);
    
    // empty response, you may fill it with a default msg
    $response = array(
      'msg_content' => 'none',
      'oldID' => $oldID
    );
    
    // this if statement will prevent to return a valid 
    // JSON string to the ajax request
    if(empty($oldID)) {
     die('timeout');
    }
    else {
      $result = mysql_query("SELECT id FROM messages WHERE id > ".addslashes($oldID)." ORDER BY id DESC");
      $index = 1;
      // check if results have new messages
      if(($num_rows = mysql_num_rows($result) > 0) {
        $response['msg_content'] = 'new';
        while($row = mysql_fetch_array($result)) {
          $response['new_msgs'][] = $row['id']
          if($index == $num_rows)
            $response['oldID'] = $row['id']; // set oldID to last record
      }
    }
    echo json_encode($response);  
    

    —

    To your comment on how to use session_write_close properly.

    session_start(); 
      $var_id = $_SESSION['id']; 
      $var_fn = $_SESSION['firstname']; 
      $var_ln = $_SESSION['lastname']; 
      $var_mail = $_SESSION['email']; 
    // close write to session here to release it for other sources 
    session_write_close();
    
    if (!loggedin()){
      header ("Location: index.php");} 
      if ($_GET['id']) {
        $id = mysql_real_escape_string($_GET['id']);} 
      // you are using session here, use the localized $var_id
      else if (isset($var_id)) {
        $id = mysql_real_escape_string($var_id);
    }
    

    When session_start() is called, the session at that point is locked for writing to any other source, except the current scope (.php file of execution) it’s in. This is to make sure that no values can be changed during the readout of session values.

    From the documentation

    Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

    To the getting stuck problem, I think the while loop is endless, request the page from your browser http://example.com/pathto/scripts/msg_scripts/msg.php and see what happens

    $counter = 0;
    while($last_msg_id <= $oldID)
    {
        usleep(10); // changing to be a bit faster
        clearstatcache();
        $result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
        $row = mysql_fetch_array($result);
        $last_msg_id = $row['id'];
        $counter++;
    
        if($counter > 100)
          break;
    }
    echo "counted: {$counter}";
    exit();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have already posted something similar here but I would like to ask the
I already posted a question regarding it, but at that time I haven't have
I have already posted a question about this, but the situation has changed sufficiently
I already posted a similar problem and it was resolved, but now I'm trying
I noticed prior to posting this question that there have been similar questions posted
I already posted a similar question but i got told to try and solve
Sorry if something similar has been posted here already, but I couldn't really find
I have a similar situation to this question , which was already posted. Koraktor
i already posted this question.Sorry that i failed to add any code.That thread is
I have already read some posts, but no one helped me with my problem.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.