By using Stringify, I can retrieve the data but I do not know how to pass it to javascript variable. It passes [{"0":"1","ItemNumberFK":"1"},{"0":"2","ItemNumberFK":"2"},{"0":"3","ItemNumberFK":"3"}] I dont know but I want to fetch the numbers 1,2,3 only how can i do that
JQUERY:
$(document).ready(function() {
$("#OrderPackageNumber").change(function(event){
// You just get the value of selected input
// You don't need to find anything because you've already selected it
var selectedd = $(this).val();
alert(selectedd);
//id_numbers = new Array();
var displayString = new Array();
$.ajax({
url:'getitemsofpackage.php',
dataType:'json',
type:'post',
data:{ namee: selectedd },
success: function(data) {
console.log(data);
alert(JSON.stringify(data));
},error: function(stats, exception){
var msg = '';
if (stats.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (stats.status == 404) {
msg = 'Requested page not found. [404]';
} else if (stats.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + stats.responseText;
}
alert(msg);
// return false;
}
});
});
});
</script>
PHP:
$result = $conn->query("SELECT ItemNumberFK FROM tblpackageitem WHERE PackageNumberFK = '".$namee."' ;");
while($row = mysqli_fetch_array($result)){
//echo '<option value ="' . $row['PackageNumber'] . '" '. $selected .'>' . $row[1] . '</option>';
//echo '<input type="checkbox" value= "' . $row['ItemNumber'] . '" >' . $row['ItemName'];
//echo $row['ItemPrice'];
//echo "<br>";
$arrayOfItems[] = $row;
// $strTry = $row;
}
// play with return result array
//while($row = mysql_fetch_array($result1)){
//$selectBoxOption1 .="<option value = '".$row['bike_type']."'>".$row['bike_type']."</option>";
//}
// return options
echo json_encode($arrayOfItems);
I hope this code can help , the first for will get the rows , the second for will get what you want , in this case you will log all the values in the row.
for(var key in data){
var row= data[key];
for(var sub_key in row){
console.log(val[sub_key]);
}
}
Related
I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>
Is there a way to only show [reason] from the array and not everything inside data? somebody said that I need to use JSON but I tried contentType: "application/json" with stringify() but then success: function(data) returns my whole HTML instead of the array.
My question is how can I show only [reason] in $('#testajax').html(data); instead of everything inside data?
console.log
script.js
$(document).ready(function(){
var date = "";
var begin = "";
var tijdsduur = "";
var aantal = "";
$('#datum').change(function() {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function(){
begin =( $(this).val() );
console.log(begin);
});
$('#Tijdsduur').change(function(){
tijdsduur =( $(this).val() );
console.log(tijdsduur);
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {
date: date,
begin: begin,
eind: tijdsduur,
quantity: aantal
},
success: function(data) {
$('#testajax').html(data);
console.log(data);
}
});
});
});
UPDATED index.php
<?php
$date = "";
$begin = "";
$tijdsduur = "";
$aantal = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
print_r($_POST);
echo "Yes, mail is set";
$date = $_POST['date'];
$begin = $_POST['begin'];
$tijdsduur = $_POST['eind'];
$aantal = $_POST['quantity'];
$eind = $begin + $tijdsduur;
$startTijd = "$date " . $begin;
$eindTijd = "$date " . $eind . ":00";
echo $date . "<br>";
echo "$startTijd". "<br>";
echo "$eindTijd". "<br>";
echo $aantal. "<br>";
$canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=$startTijd&end_time=$eindTijd&quantity=$aantal";
$cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
$reservationavailable = file_get_contents("$cleancanmakereservation");
$reservationAvailable = json_decode($reservationavailable, true);
echo "$cleancanmakereservation";
echo json_encode($reservationAvailable);
}
else {
echo "No, mail is not set";
}
exit;
}
?>
console.log(date[0].reason);
console.log(date);
Return data in json_encode from your index.php
Then in your ajax success function just get it by
success: function(data) {
console.log(data.reason); //if its comming then add it to your html.
$('#testajax').html(data.reason);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to call PHP script that change some content of HTML file.
First, I have HTML with a button. When I click this button, it call a javascript function which will post some parameters to PHP script. This script will take the parameters and generate the content that will be displayed in the HTML.
1) First, I were have form tag that send post action to the php. I delete this form tag from the HTML.
2) Then, I call jsFunction() "javascript function" when clicking "Run" button in the HTML.
onclick="jsFunction();"
3) I create javascript function:
jsFunction(){
var url = "calculateResult.php";
var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// change the content of the div in second tab
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url+"?"+params, true);
xhttp.send();
}
4) PHP file send replay to the javascript via echo statement.
Now, I think PHP does not receive any parameters from the javascript function!
Is there something wrong in my code?
Edit 1:
One of the steps in the php is generate text file and put one of the parameters "querySeq" in that file. When I open the file, it is empty.
The PHP file:
<?php
include("C:/inetpub/wwwroot/webclient/js-i2b2/cells/plugins/examples/BLAST/assets/include/path.inc");
$jobid = (empty($_GET['jobid'])) ? '' : $_GET['jobid'];
$blastdb = (empty($_POST['blastdb'])) ? '' : $_POST['blastdb'];
$blastpath = (empty($_POST['blastpath'])) ? '' : $_POST['blastpath'];
$patientIDarray = (empty($_POST['patientIDarray'])) ? '' : $_POST['patientIDarray'];
$opt = (empty($_GET['opt'])) ? '' : $_GET['opt'];
$blast_flag = (empty($_POST['blast_flag'])) ? 1 : $_POST['blast_flag'];
$filter_flag = (empty($_POST['filter_flag'])) ? '' : $_POST['filter_flag'];
$filt_val = (empty($_POST['filt_val'])) ? '' : $_POST['filt_val'];
$cutoffType = (empty($_POST['cutoffType'])) ? '' : $_POST['cutoffType'];
$pct_cutoff = (empty($_POST['pct_cutoff'])) ? '' : $_POST['pct_cutoff'];
$blst_cutoff = (empty($_POST['blst_cutoff'])) ? '' : $_POST['blst_cutoff'];
$searchType = (empty($_POST['searchType'])) ? '' : $_POST['searchType'];
$program = (empty($_POST['program'])) ? '' : $_POST['program'];
$dot = (empty($_GET['dot'])) ? '' : $_GET['dot'];
$querySeq = (empty($_POST['querySeq'])) ? '' : $_POST['querySeq'];
$blastagainstfile = (empty($_FILES['blastagainstfile']['name'])) ? '' : $_FILES['blastagainstfile']['name'];
$alignmentView = (empty($_GET['alignmentView'])) ? '' : $_GET['alignmentView'];
if ($blast_flag == 1) {
$jobid = time().rand(10, 99);
}
if (!$blast_flag && !$jobid) {
echo "<p>Error: No job submitted.</p>";
footer();
exit;
}
if ($searchType == 'advanced') {
$expect=(empty($_POST['expect'])) ? 10 : $_POST['expect'];
$wordSize = (empty($_POST['wordSize'])) ? '' : $_POST['wordSize'];
$targetSeqs = (empty($_POST['targetSeqs'])) ? '' : $_POST['targetSeqs'];
$mmScore = (empty($_POST['mmScore'])) ? '' : $_POST['mmScore'];
$matrix = (empty($_POST['matrix'])) ? '' : $_POST['matrix'];
$gapCost = (empty($_POST['gapCost'])) ? '' : $_POST['gapCost'];
$filter = (empty($_POST['filter'])) ? 'F' : $_POST['filter'];
$softMask = (empty($_POST['softMask'])) ? 'F' : $_POST['softMask'];
$lowerCaseMask = (empty($_POST['lowerCaseMask'])) ? 'F' : $_POST['lowerCaseMask'];
$ungapAlign = (empty($_POST['ungapAlign'])) ? 'F' : $_POST['ungapAlign'];
$alignmentView = (empty($_POST['outFmt'])) ? 0 : $_POST['outFmt'];
$geneticCode = (empty($_POST['qCode'])) ? '' : $_POST['qCode'];
$dbGeneticCode = (empty($_POST['dbCode'])) ? '' : $_POST['dbCode'];
$otherParam = (empty($_POST['OTHER_ADVANCED'])) ? '' : $_POST['OTHER_ADVANCED'];
if ($otherParam) {
if (!preg_match("/^\s+$/", $otherParam) && !preg_match("/^\s*\-[A-Za-z]/", $otherParam)) {
echo "Error: The other advanced options must start with \"-\"";
exit;
}
}
$advanceParam = "$expect!#%$wordSize!#%$targetSeqs!#%$mmScore!#%$matrix!#%$gapCost!#%$filter!#%$softMask!#%$lowerCaseMask!#%$ungapAlign!#%$alignmentView!#%$geneticCode!#%$dbGeneticCode!#%$otherParam";
}else {
$advanceParam = "";
}
if (!$alignmentView) {
$alignmentView = 0;
}
if($blast_flag == 1) {
$nlstr = chr(10);
$crstr = chr(13);
if($querySeq || !preg_match("/^\s+$/", $querySeq)) {
# $fp1=fopen("$dataPath/$jobid.blastinput.txt", "w",1);
if (!$fp1)
{
echo "<p><strong> Error: couldn't open $dataPath/$jobid.blastinput.txt </strong></p></body></html>";
exit;
}
fwrite($fp1, $querySeq);
fclose($fp1);
}else {
echo "<p style='color: red'>Error: please enter your query sequence or upload your fasta sequence file.</p><br>";
exit;
}
}
if($cutoffType == 'pct') {
$criterion = $pct_cutoff;
}
if($cutoffType == 'blst') {
$criterion = $blst_cutoff;
}
if(!$opt || $opt == 'wait') {
$progressdot = "image/progressdot.png";
echo "<p><strong>Your job is being processed ";
for($i = 0; $i <= ($dot%6); $i++) {
echo "<img src='$progressdot'>";
}
echo "</strong></p>";
$dot += 1;
echo "<p>Your job id is $jobid.</p>";
echo "<p>Please wait here to watch the progress of your job.</p>";
echo "<p>This page will update itself automatically until search is done.</p>";
}
if(!$opt || $opt == 'wait') {
echo "<META HTTP-EQUIV=\"refresh\"
content=\"10;URL=blastresult.php?jobid=$jobid&alignmentView=$alignmentView&opt=wait&dot=$dot\">";
echo "<META HTTP-EQUIV=\"expires\"
CONTENT=\"now\">";
}
if($blast_flag == 1) {
$blastagainst = "";
if ($program == "blastn" || $program == "tblastn" || $program == "tblastx") {
$dbPath = "C:/inetpub/wwwroot/webclient/db/nucleotide";
}else {
$dbPath = "C:/inetpub/wwwroot/webclient/db/protein";
}
if($blastagainstfile) {
$blastagainst = "$dataPath/$jobid.blastagainst.txt";
}
if ($patientIDarray) {
for ($i = 0; $i < sizeof($patientIDarray); $i++) {
$blastagainst .= " $dbPath/$patientIDarray[$i]";
}
}
$blastpath = "C:/inetpub/wwwroot/webclient/blast/bin";
$basicParam = "$jobid\t$searchType\t$blastagainst\t$program\t$blastpath";
/*create child process to run perl script which do the blast search and write output data to apropriate files*/
/* For windows */
pclose(popen("start /b perl blast.pl \"$basicParam\" \"$advanceParam\"", "r"));
}
/* error log if there is error in BLAST */
$errFile = "$dataPath/$jobid.err";
/* parent process continue here to check child process done or not */
$filename = "$dataPath/$jobid.blaststring.txt";
if (file_exists($errFile) && filesize($errFile) > 0) {
if(!$opt || $opt == 'wait') {
echo "<script LANGUAGE=JavaScript>";
echo "location.replace('blastresult.php?jobid=$jobid&opt=none')";
echo "</script>";
}else {
echo "<p>There is error in executing BLAST. Following is the error message:<p>";
$fperr = fopen("$dataPath/$jobid.err", "r");
if(!$fperr) {
echo "<p><strong> $jobid.err error: $errors </strong></p></body></html>";
exit;
}
while (!feof($fperr))
{
$line = rtrim(fgets($fperr));
echo "$line<br>";
}
fclose($fperr);
}
}elseif(file_exists($filename)) {
if ($alignmentView) {
echo "<script LANGUAGE=JavaScript>";
echo "location.replace('data/$jobid.blast')";
echo "</script>";
}else {
if($blast_flag == 'Parse again') {
$print_flag = 0;
$cutoff_count = 0;
# $fpout=fopen("$dataPath/$jobid.par", "r");
if (!$fpout)
{
echo "<p><strong> $jobid.par error: $phperrormsg </strong></p></body></html>";
exit;
}
# $fpout3 = fopen("$dataPath/$jobid.out.par", "w", 1);
if(!$fpout3) {
echo "<p><strong> $jobid.out.par error: $errors </strong></p></body></html>";
exit;
}
while (!feof($fpout))
{
$fpout2_str = '';
$line = rtrim(fgets($fpout));
if (!$line) {
continue;
}
list($page, $query_name, $match_name, $score, $identities, $percentage, $e_value, $link) = preg_split("/\t/", $line);
if($cutoffType == 'pct') {
$subject = $percentage;
}else {
$subject = $score;
}
if($subject >= $criterion) {
fwrite($fpout3, "$page\t$query_name\t$match_name\t$score\t$identities\t$percentage\t$e_value\t$link\n");
$cutoff_count++;
}
}
fclose ($fpout);
fclose($fpout3);
# $fp = fopen("$dataPath/$jobid.blastcount.txt", "w", 1);
if(!$fp) {
echo "<p><strong> error: $php_errormsg </strong></p></body></html>";
exit;
}else {
fwrite($fp, "$cutoff_count\n");
}
fclose($fp);
}
$filename = "$dataPath/$jobid.blastcount.txt";
while(!file_exists($filename)) {}
if(!$opt || $opt == 'wait') {
echo "<script LANGUAGE=JavaScript>";
echo "location.replace('blastresult.php?jobid=$jobid&opt=none')";
echo "</script>";
}else {
# $fp = fopen("$dataPath/$jobid.blastcount.txt", "r");
if(!$fp) {
echo "<p><strong> error: $php_errormsg </strong></p></body></html>";
exit;
}
if(!feof($fp)) {
$cutoff_count = fgets($fp);
}
fclose($fp);
# $fp = fopen("$dataPath/$jobid.blaststring.txt", "r");
if(!$fp) {
echo "<p><strong> error: $php_errormsg </strong></p></body></html>";
exit;
}
if(!feof($fp)) {
$blastagainststring = rtrim(fgets($fp));
}
fclose($fp);
if($cutoff_count == 0) {
echo "<p>No comparison meets cutoff criterion. Please change expect value to blast again.</p>";
}else {
echo "<p><a href=data/$jobid.blast1.html target='_blank'>Inspect BLAST output</a><br>";
echo "<form action='blastresult.php?jobid=$jobid&opt=$opt' method='post'>";
echo "<p>Filter current page by score:</p>";
echo "<p> Show <select name='filt_val'>";
echo "<option value='0' selected>- All -";
echo "<option value='1'>Top score";
echo "<option value='5'>Top 5 scores";
echo "<option value='10'>Top 10 scores";
echo "</select> for each query sequence <input type='submit' name='filter_flag' value='Filter'></font></p>";
echo "<p>Re-parse current blast results (please select cutoff criterion):</p>";
echo "<p><table style='font-size: 12px'>";
echo "<tr><td><input type='radio' checked name='cutoffType' value='pct'>Similarity percentage</td><td></td>";
echo "<td>Cutoff %: </td><td><input type='text' name='pct_cutoff' value=95 size=6 maxlength=6></td></tr>";
echo "<tr><td><input type='radio' name='cutoffType' value='blst'>Blast score</td><td></td>";
echo "<td>Cutoff score: </td><td><input type='text' name='blst_cutoff' value=1000 size=6 maxlength=6></td>";
echo "<td><input type='submit' name='blast_flag' value='Parse again'>";
echo "</td></tr></table></p>";
echo "</form>";
echo "<form action='sequence.php?jobid=$jobid' method='post' target='_blank' onsubmit=\"return checkform(this);\">";
echo "<p>Retrieve and download subject sequences in FASTA format:</p>";
echo "<p><input type='checkbox' name='dldseq' value='all'> Check here to download All sequences... ";
echo "OR select particular sequences of interest below</p>";
echo "<p><input type='submit' value='Submit'> your selection of sequences to download</p>";
echo "<p><table border = 1 style='font-size:10px' width=100% class='sortable'>";
echo "<thead><tr align='center'><th>Query</th><th>Subject</th><th>Score</th><th>Identities (Query length)</th><th>Percentage</th><th>Expect</th></tr></thead>";
echo "<tbody>";
# $fp = fopen("$dataPath/$jobid.download.txt", "w", 1) or die("Cannot open file: $jobid.download.txt");
if($blast_flag == 'Parse again' || ($opt == 'none' && !$filter_flag)) {
# $fpout3=fopen("$dataPath/$jobid.out.par", "r");
if(!$fpout3) {
echo "<p><strong> error: $php_errormsg </strong></p></body></html>";
exit;
}
$i = 0;
$queryName = $preQueryName = "";
while(!feof($fpout3)) {
$row = fgets($fpout3);
if (!$row) {
continue;
}
$element = preg_split("/\t/", $row);
$page = $element[0];
$queryName = $element[1];
$target_name = $element[7];
$var_target = $page."\t".$element[1]."\t".$element[2];
if(count($element) != 1) {
if($queryName == $preQueryName) {
$i++;
}else {
$i = 0;
}
if($i < 10) {
echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
fwrite($fp, "$var_target\n");
}
}
$preQueryName = $queryName;
}
fclose($fpout3);
}
if($filter_flag == 'Filter')
{
# $fpout3=fopen("$dataPath/$jobid.out.par", "r");
if(!$fpout3) {
echo "<p><strong> error: $php_errormsg </strong></p></body></html>";
exit;
}
$i = 0;
while(!feof($fpout3)) {
$row = fgets($fpout3);
if (!$row) {
continue;
}
$element = preg_split("/\t/", $row);
$page = $element[0];
$target_name = $element[7];
$var_target = $page."\t".$element[1]."\t".$element[2];
if(count($element) != 1) {
if($filt_val != 0) {
if($i == 0) {
$query_name = $element[1];
echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
fwrite($fp, "$var_target\n");
$i++;
}elseif($query_name == $element[1] && $i < $filt_val) {
echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
fwrite($fp, "$var_target\n");
$i++;
}elseif($query_name != $element[1]) {
echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
$query_name = $element[1];
fwrite($fp, "$var_target\n");
$i=1;
}
}else {
echo "<tr align='center'><td>$element[1]</td><td align=left><input type='checkbox' id='checkedSeq' name='target[]' value='$var_target'>$target_name</td><td><a href=data/$jobid.blast$page.html#$element[1]$element[2] target='_blank'>$element[3]</a></td><td>$element[4]</td><td>$element[5]</td><td>$element[6]</td></tr>";
fwrite($fp, "$var_target\n");
}
}
}
fclose($fpout3);
}
fclose($fp);
echo "</tbody></table></form>";
echo "<p>Top";
}
}
}
}
?>
Edit 2:
I try the following for var params:
var params = 'querySeq='+querySeq+'&program='+program+'&patientIDarray='+patientIDarray+'&blast_flag='+blast_flag;
OR
var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
with
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
But, it does not works! The content in HTML does not changed.
It works only if I assign:
var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
with
xhttp.open("POST", url+"?"+params, true);
xhttp.send();
But, the received parameters are empty.
Any help please.
Thanks,
Edit 3:
It's working now. I did not pass parameters from HTML to JS file. Just by pass the parameters with onclick function
onclick=jsFunction(document.getElementById('some parameters').value)
Also I use:
var params = "querySeq="+querySeq+"&program="+program+"&patientIDarray="+patientIDarray
with
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
And it works!
Thanks everyone.
xhttp.open("POST", url+"?"+params, true);
xhttp.send();
You are making a POST request, implying that you are looking for the data in $_POST, but you have put all the data in the query string. It needs to go in the request body.
xhttp.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
PHP puts data from the query string in $_GET and data (with a recognised encoding) from the request body in $_POST. Unfortunately, it names the superglobal variables are the request methods where those places are commonly used to store data and not based on where the data actually is.
Working GET example:
<script>
function jsFunction() {
var url = "receive.php";
var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// change the content of the div in second tab
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url+"?"+params, true);
xhttp.send();
}
</script>
Working POST example:
<script>
function jsFunction() {
var url = "receive.php";
var params = "querySeq=querySeq&program=program&patientIDarray=patientIDarray&blast_flag=blast_flag";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// change the content of the div in second tab
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
}
</script>
I'm attempting to call a PHP file and have it return a result (a single record's 'pageLocation') from a database table ('page'). I then want to get that result into a variable, so I can use it while creating an image in html.
Currently, the image is being created but the source is not feeding into it, leaving a default empty image at the correct size.
Javascript:
// Loads a list of comics created by the user from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Non-relevant code affecting layout if no comics are found.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
// Gets image source from database.
imgSrc = "";
tempID = arr[i].comicID;
$.post("getCover.php", {'comicID':tempID}, function(result)
{
imgSrc += ("" + result);
}
);
// Creates image item and associated radio button.
out += "<hr><br><img name = '" + ('com' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + imgSrc + "'><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT FIRST (pageLocation) FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$conn->close();
echo ($result);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
Thanks for any help provided.
You need to get he data from the result, like:
$row = $result->fetch_assoc()
Also, yes, Jim G is right, you need to escape that POST variable.
Hi I have used a code snippet from a tutorial for a chat application all of its scripts are working fine but after I tweak it to make the code work based on my requirements almost all of the scripts are working except for retrieving the conversation
The error I'm having is it doesn't retrieve the conversation from my database
here is the modified script
//Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$json .= '"message":[ {';
$json .= '"id": "0",
"user": "Admin",
"text": "You are not currently in a chat session. <a href="">Enter a chat session here</a>",
"time": "' . date('h:i') . '"
}]';
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$json .= '"message":[ ';
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json .= '{';
$json .= '"id": "' . $message_array['msgid'] . '",
"user": "' . htmlspecialchars($message_array['username']) . '",
"text": "' . htmlspecialchars($message_array['message_content']) . '",
"time": "' . $message_array['message_time'] . '"
},';
}
$json .= ']';
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$json .= '"message":[]';
}
}
//Close our response
$json .= '}}';
echo $json;
Here is the code for calling this script
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
getChatText();
}
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
//Get a reference to our chat container div for easy access
var chat_div = document.getElementById('clog');
var response = eval("(" + receiveReq.responseText + ")");
for(i=0;i < response.messages.message.length; i++) {
chat_div.innerHTML += response.messages.message[i].user;
chat_div.innerHTML += ' <font class="chat_time">' + response.messages.message[i].time + '</font><br />';
chat_div.innerHTML += response.messages.message[i].text + '<br />';
chat_div.scrollTop = chat_div.scrollHeight;
lastMessage = response.messages.message[i].id;
}
mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
}
}
Am I missing something here or doing something wrong?
You should rewrite using json_encode:
$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$message_object = (object) array(
"id"=>"0",
"user"=>"Admin",
"text"=>"You are not currently in a chat session. <a href=\"\">Enter a chat session here</a>",
"time"=>date('h:i')
);
$messages[] = (object) array("message"=>$message_object);
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$message_object = (object) array(
"id"=>$message_array['msgid'],
"user"=>htmlspecialchars($message_array['username']),
"text"=>htmlspecialchars($message_array['message_content']),
"time"=>$message_array['message_time'
);
$messages[] = (object) array("message"=>$message_object);
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$messages[] = (object) array("message"=>array());
}
}
//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;