Marcus Marcus - 4 months ago 10
PHP Question

Live update php variable and simultaneously, show the value in a textbox

This is my table row click function in the file, 'BAConsult.php'. On click, showconsultationdata function will run.

$(document).ready(function(){ //table row click
}).on('click','.consultclick tr',function(e){
if(e.target.tagName === "TD"){
$(".consultclick tr").removeClass("highlight");
$(e.target).parent().addClass("highlight");
}
var dateconsulted = $(this).attr('value');
alert(dateconsulted);
showconsultationdata(dateconsulted);
});


This is my ajax script

function showconsultationdata(str) {
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
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("txtHint2").innerHTML = xmlhttp.responseText;

}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}


Here is another php file called 'BAConsultRecordsAJAX.php' where i placed the ajax of the showconsultationdata.

session_start();
require('Config/Setup.php');
$q = $_GET['q'];
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";

$consultresult = mysqli_query($dbconn,$consult);

while($row = mysqli_fetch_array($consultresult)) {
$skincareremarks=$row['skincareremarks'];
$skinconditionremarks=$row['skinconditionremarks'];
}


On table row click, $skincareremarks and $skinconditionremarks should be updated. And these values will show up in the textboxes in the 'BAConsult.php' page. How can i do this?

Answer

So, i followed @Jeff's method by using JSON. However, I realised that the xmlhttp.responseText wasn't only showing my JSON encoded code, but also my javascript which was why the JSON.parse method was unable run properly. I then did the following:

In my BAConsultRecordsAJAX.php file, i did this.

echo "<div id='test1'>";
echo json_encode(array('first'=>$skincareremarks,'second'=>$skinconditionremarks));
echo "</div>";

I gave this output a div called 'test1'.

Then, in my main file's AJAX script, i did this.

var a = JSON.parse($(xmlhttp.responseText).filter('#test1').html());    
document.getElementById("test").value=a.first;

So basically, it filters out the rest of the xhtmlhttp.responseText outputs, and selects only the contents in the div where id='test1'.

Hope this helps those who have this problem too..

Comments