I just want to use the id for getting description I might have many rows fetched so I am going to make onclick event but till now, why it doesnot work? where am I wrong? Thank you for your interest

<?php  while( $row = mysql_fetch_array($res))  { ?>
<strong><?php echo $row["heading"]?></strong>
    <br />
<script>
    display(<?php echo $row["id"]?>);
</script>

<script>
function display(a)
{
        <?php $temp = "select description from newsfeed where id="?>+a+<? ";";
        header("location: index.php?msg = $temp ");?>
}
</script>

Dani AI

Generated

Short, practical fix and why it failed (for )

You hit the usual server/client mismatch: PHP runs on the server and outputs HTML/JS before the browser sees it. You cannot "call PHP" later from a click without the browser making a request (XHR/fetch or a normal link submit). and were right — the correct pattern is: render an ID into the page, then have JavaScript send that ID back to the server when the user clicks. Also, putting a PHP header("Location: ...") inside code that you expect to run on click doesn’t work the way you think — that header() runs when PHP generates the page, not at the later click.

Suggested modern approach (event delegation + fetch + prepared query)

  • Render each row with a safe fallback link (so the page still works without JS).
  • Add a single click handler that reads a data-id and calls a small endpoint that returns JSON.
  • Server validates the id and uses a prepared statement (PDO or mysqli) to fetch the description.

Example JavaScript (client)

document.addEventListener('click', e => {
  const btn = e.target.closest('.show-desc');
  if (!btn) return;
  const id = btn.dataset.id;
  fetch('get-description.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id })
  })
  .then(r => r.ok ? r.json() : Promise.reject(r.statusText))
  .then(data => document.getElementById('descriptionBox').textContent = data.description || 'No description')
  .catch(err => { console.error(err); document.getElementById('descriptionBox').textContent = 'Error loading'; });
});

Example server-side hints (get-description.php)

// decode JSON input, cast/validate id, use PDO prepared statement:
// SELECT description FROM newsfeed WHERE id = ? LIMIT 1
// send JSON response and appropriate HTTP status codes

Practical tips and cautions

  • Use json_encode() to safely pass PHP arrays to JS if you need to preload data.
  • Protect against SQL injection with prepared statements (PDO/mysqli) — avoid old mysql_* functions.
  • Use textContent (or sanitize) when inserting text into the DOM to avoid XSS.
  • Debug with the browser DevTools Network tab and Console to see the request/response and server errors.

’s AJAX example is a good base; the above just modernizes it (fetch + JSON), adds server-side validation and safer DB access, and gives a simple progressive-enhancement fallback so the page still works without JavaScript.

Recommended Answers

All 4 Replies

Member Avatar for Member #120589

This is a mess - no offence. You can pass php data to js, but not the other way around unless you use ajax.

Heres an old ajax file i found and edited for you:

daniweb_basic_ajax_example.php

<html>
<head>
<script type='text/javascript'>
function getXMLHTTPRequest() {
   var req =  false;
   try {
      /* for Firefox */
      req = new XMLHttpRequest(); 
   } catch (err) {
      try {
         /* for some versions of IE */
         req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (err) {
         try {
            /* for some other versions of IE */
            req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (err) {
            req = false;
         }
     }
   }

   return req;
}

function ajaxRequest(rowid){
    var url = 'daniweb_ajaxData.php';
    var vars = 'id='+rowid;
    Req = getXMLHTTPRequest();
    Req.open('POST', url, true);
    Req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    Req.onreadystatechange = function() {//Call a function when the state changes.
        if(Req.readyState == 4 && Req.status == 200) {
            document.getElementById('descriptionBox').innerHTML = Req.responseText;
            //alert(Req.responseText);
        }else{
            document.getElementById('descriptionBox').innerHTML = 'Loading...';
        }
    }
    Req.send(vars);
}
</script>
</head>
<body>
<?php  
$data = array(
            '1'=>array('heading'=>'item 1','id'=>'1','description'=>'desc 1'),
            '2'=>array('heading'=>'item 2','id'=>'2','description'=>'desc 2'),
            '3'=>array('heading'=>'item 3','id'=>'3','description'=>'desc 3'),
            '4'=>array('heading'=>'item 4','id'=>'4','description'=>'desc 4'),
            '5'=>array('heading'=>'item 5','id'=>'5','description'=>'desc 5')
        );
//while($row = mysql_fetch_array($res)){
foreach($data as $row){
    echo "<strong>{$row["heading"]}</strong>\r\n";
    echo "<a href='javascript:' onclick='ajaxRequest({$row['id']});'>open descripton</a>\r\n";
    echo "<br />\r\n";
}
?>
<div id='descriptionBox'></div>
</body>
</html>

and a second page for ajax to get the data with:

daniweb_ajaxData.php

<?php

if(ISSET($_POST['id']) && (ctype_digit($_POST['id']) || is_int($_POST['id']))){
    //mysql_connect(...);
    //$query = "SELECT description FROM tablename WHERE id = {$_POST['id']}";
    //$result = mysql_query($query);
    //$data = mysql_fetch_assoc($result);
    //echo $data['description'];

    $data = array(
            '1'=>array('heading'=>'item 1','id'=>'1','description'=>'desc 1'),
            '2'=>array('heading'=>'item 2','id'=>'2','description'=>'desc 2'),
            '3'=>array('heading'=>'item 3','id'=>'3','description'=>'desc 3'),
            '4'=>array('heading'=>'item 4','id'=>'4','description'=>'desc 4'),
            '5'=>array('heading'=>'item 5','id'=>'5','description'=>'desc 5')
        );
    echo $data[$_POST['id']]['description'];
}else{
    echo "ID did not pass: {$_POST['id']}";
}
?>

PHP is a server side language, php runs before the web page has loaded and generates the text to show the web browser(javascript is not running yet), so php can write and change javascript code before the page has loaded.

once the page has loaded php and its vars no longer exist, but javascript does. AJAX is javascript code that sends a request to another page for data so you can use php to get data for javascript to use without a page refresh using ajax.

Thank You guys, specially BIIIM, :) though it took 3 days to understand your property. Thank you so much!

haha no problem, i hated the first steps of javascript the debugging in it is awful.

Dont forget to mark as solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.