0

Edit

I've changed my approach based on some research, and I'm getting a partial result.

Database:

+--------------------------------------------------+
|  id  |  date      |  objet  |  contenu     | lu  |
+--------------------------------------------------+
|  1   | 2013-01-20 | msg1    | msg1_content | 0   |
|  2   | 2013-01-20 | msg2    | msg2_content | 0   |
|  3   | 2013-01-20 | msg3    | msg3_content | 0   |
+--------------------------------------------------+

Link:

<a href="javascript:void(0);" onclick="markAsRead('.$message['id'].');">View'</a>

JS/AJAX:

function markAsRead(id)
{
    $.ajax(
    {
        type: "GET",
        url: 'php/messagerie.php',
        data: "id=" + id, // appears as $_GET['id'] @ ur backend side
        success: function(data)
        {
            // data is ur summary
            $('#contenu').html(data);
        }
    });
}

PHP (php/messagerie.php)

$q = intval($_GET['id']);

// connect to db (of course not shown here)
if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}

$sql="SELECT * FROM coq_messagerie WHERE id = '".$q."'";

$lu = mysqli_query($mysqli, "UPDATE ".DB_PREFIX."messagerie SET lu='1' WHERE id='$q' LIMIT 1");
$result = mysqli_query($con,$sql);

    echo "<table border='1' width='100%'>
        <tr>
            <th>id</th>
            <th>date</th>
            <th>objet</th>
            <th>contenu</th>
            <th>lu</th>
        </tr>";

        while($row = mysqli_fetch_array($result))
        {
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['date'] . "</td>";
                echo "<td>" . $row['objet'] . "</td>";
                echo "<td>" . $row['contenu'] . "</td>";
                echo "<td>" . $row['lu'] . "</td>";
            echo "</tr>";
        }

    echo "</table>";

mysqli_close($con);

I'm currently only retrieving only the <th>'s and not information when I'm looking up for id 2 or 3, but am getting information for id 1. How can this be only partially working?


Introduction

In an attempt to show dynamic information on my page, I'm using a mix of a few bits and pieces of code which should collect data from a basic HTML link which parses and returns data on the current page. Of course, this seems very basic, but being my first AJAX script, I would greatly appreciate some help.

Code

HTML Link:

$output .= '<a onclick="markAsRead('.$message['id'].'); return false;">'.View.'</a>';

Note: The link collects the id field as expected.

JS/AJAX Code:

function markAsRead(str) {
    console.log("starting");
    if (str=="")
    {
        console.log("string empty");
        document.getElementById("contenu").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        console.log("on ready state change");
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("contenu").innerHTML=xmlhttp.responseText;
        }
        else
        {
            console.log("seems to returning information");
            var abc = "<h1>Huh.</h1>";
            document.getElementById("contenu").innerHTML=abc;
        }
    }
    xmlhttp.open("GET","php/messagerie.php?q="+str);
    xmlhttp.send();
}

Note: The console.log('###_'+str) is used to see where the code crashes. All logged properly (105, 107, 109).

PHP (php/read.php)

// connect to db (of course not shown here)
$message = $GET["messageid"];

$lu = mysqli_query($mysqli, "UPDATE messages SET lu='1' WHERE id='$message' LIMIT 1");
if(!$lu)
{
    echo "Update error"; 
    exit;
}
else
{    
    $data = mysqli_query($mysqli, "SELECT * FROM messages WHERE id='$message' LIMIT 1");
    while($row = mysqli_fetch_array($data))
    {
        echo $row["contenu"];
    }
}

Note: $lu is updated, which makes me believe the problem is either in the while/echo area or in my AJAX return.

Current console logs

starting
on ready state change
seems to returning information
-> GET ***/php/messagerie.php?q=3
   ** params -> q 3 **
   ** empty response **
   ** empty HTML **
on ready state change
seems to returning information
on ready state change

Where am I going wrong?

4
  • You could add a lot more output to the response returned from the PHP script to get feedback even it 0 rows are returned. add an echo before the while loop to say "results found: "; for example. Also could debug further adding extra onreadystatechange output. Currently you only capture when a result has completed and is successful. Add an } else { to the ready state callback that could populate another element with ALL response text. Commented Mar 13, 2014 at 2:07
  • @ArtofThem I've used your suggestion, I've added an else statement to the readyState condition and I do see some content flicker. I've edited the code above to reflect the new code with the flickr. Commented Mar 13, 2014 at 2:21
  • If it's showing then disappearing quickly it's likely the innerHTML is being set again AFTER the "Huh.". I would now add console logs to the beginning of the click handler; ie. above if (str=="") and check to see if the function is being triggered twice. Even add an additional log within the str=="" condition to check if the innerHTML is being set to empty. Commented Mar 13, 2014 at 2:50
  • Indeed, some elements are repeating. I've added newest code and current console logs. Commented Mar 13, 2014 at 2:59

2 Answers 2

1
$message = $GET["messageid"];

should be

$message = $_GET["messageid"];
Sign up to request clarification or add additional context in comments.

2 Comments

I've done the change in my file, but this has not corrected the issue. Good point, though.
in your js conolse.log() the whole xhr response to give you some clues as to what your php is doing.
0

Solution found! This updates the field value to mark message as read and shows the message in the proper div.

Solution

In the AJAX request, the missing parameter of true has been added with the query.

Complete code

AJAX

function markAsRead(str)
{    
    if (str=="")
    {
        document.getElementById("contenu").innerHTML="";
        return;
    }
    if (window.XMLHttpRequest)
    {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("contenu").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","php/messagerie.php?q="+str,true);  // added ",true"
    xmlhttp.send();
}

PHP

$q = intval($_GET['q']);

$con = mysqli_connect('','','',''); // values hidden here for obvious reasons
mysql_set_charset('utf8',$con);

if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}

$sql="SELECT * FROM messages WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

$update = mysqli_query($con, "UPDATE messages SET lu='1' WHERE id='$q'");

if(mysqli_num_rows($result) > 0)
{
    echo "<table border='1'>
            <tr>
                <th>id</th>
                <th>date</th>
                <th>objet</th>
                <th>contenu</th>
                <th>lu</th>
            </tr>";

    while($row = mysqli_fetch_array($result))
    {
        echo "<tr>";
            echo "<td>" . $row['id'] . "</td>";
            echo "<td>" . $row['date'] . "</td>";
            echo "<td>" . $row['objet'] . "</td>";
            echo "<td>" . $row['contenu'] . "</td>";
            echo "<td>" . $row['lu'] . "</td>";
        echo "</tr>";
    }

    echo "</table>";
}

mysqli_close($con);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.