How to pass a PHP array to another PHP page with ajax - javascript

I have been looking for this answer without success.
I have three files: index.php, actions.js and devices.php
My index.php have this code:
<?php
$file = "canvas/interactiveWorkstations/".$roomData['id'].".json";
if(file_exists($file)){
$map = "interactiveWorkstation";
$lines = file($file);
$nPolygon = $lines[count($lines) - 4];
$counterPolygon = 0;
$pos = 4;
$areas = array();
while($counterPolygon !== $nPolygon && $pos < count($lines)){
$lines[$pos] = json_decode($lines[$pos], true);
if($counterPolygon !== 0)
$lines[$pos] = array_diff_assoc($lines[$pos], $lines[$pos-9]);
$coords = "";
foreach($lines[$pos] as $line)
foreach($line as $k => $v)
if($k !== "color" && $v !== -1)
$coords .= $v . ", ";
$coords = trim($coords, ', '); //Delete last space and last comma
$lines[$pos-3] = trim($lines[$pos-3], '#');
$areas[trim($lines[$pos-3])] = $coords;
$counterPolygon++;
$pos = $pos + 9;
}
?>
<script>
var img = document.getElementsByClassName('connection')[0];
img.setAttribute('usemap', '<?php echo "#".$map; ?>');
img.insertAdjacentHTML('afterend', '<map name="<?php echo $map; ?>" id="<?php echo $map; ?>"></map>');
var points = <?php echo json_encode($areas);?>;
</script>
<?php
}
if($bookingActive) {
echo '<script type="text/javascript">reloadDevices("'.$workstationName.'","'.$randomKey.'","'.$bookingData['ical_uid'].'",points); initCountdown('.$remainingTime.');</script>';
}
At this point I have passed my $areas variable to JS using json_encode, and my functions reloadDevices() and UpdateDevices() receive it correctly because I checked before.
In my actions.js file have this code:
function updateDevices(workstation,randomKey,z,points){
var parameters = {
"workstation" : workstation,
"randomKey" : randomKey,
"z" : z,
"points" : points
};
$.ajax({
data: parameters,
url: 'workstation/devices.php',
type: 'post',
success: function (response) {
$("#devices").html(response);
}
});
}
function reloadDevices(workstation,randomKey,z,points) {
updateDevices(workstation,randomKey,z, points);
setInterval(function () { updateDevices(workstation,randomKey,z, points); }, 6000);
}
I do an ajax call to devices.php, but when I wanna get my $_POST['points'] variable is empty.
The part of code from my devices.php where I use this variable:
<?php
$areas = json_decode($_POST['points'], true);
?>
<script>
var map = document.getElementById('interactiveWorkstation');
var area = document.getElementById('<?php echo $deviceName; ?>');
if(!area)
map.insertAdjacentHTML('beforeend', '<area id="<?php echo $deviceName; ?>" shape="polygon" coords="<?php echo $areas[$deviceName]; ?>" href=\'javascript:createTerminal(<?php echo "\"".$deviceName."\""; ?>, <?php echo "\"".$deviceIp; ?>-<?php echo $randomKey."\""; ?>, <?php echo "\"".$uid."\""; ?>, <?php echo "\"".$deviceName."\""; ?>);\'/>');
</script>
Honestly, I can't see the error. If someone helps me appreciate it.
Thanks so much.
Regards.

Related

How to send php value to javascript with script tag?

php code is
<?php
if (isset($_POST['search']))
{
$startDate = $_POST['start'];
$startDate = str_replace('/', '-', $startDate );
$startDate = date("Y-m-d", strtotime($startDate));
// echo $startDate;
$endDate = $_POST['end'];
$endDate = str_replace('/', '-', $endDate );
$endDate = date("Y-m-d", strtotime($endDate));
// echo $endDate;
$model = $_POST['model'];
// echo $model;
$dates = getDatesStartToLast($startDate, $endDate);
// echo $dates
for ($i=0; $i < count($dates); $i++){
echo "<form method = 'post'>";
echo "<tr>";
echo "<td><button type = 'submit' style = 'border-color : white; background-color : white; outline : 0; border : 0' name = 'datebutton' value = '$model,$dates[$i]'>$dates[$i]</td>";
echo "</form>";
$query = mysqli_query($conn, "SELECT * from elentec_count where Date = '$dates[$i]' and model = '$model'");
$row = mysqli_fetch_row($query);
echo "<td>$row[2]</td><td>$row[3]</td><td>$row[4]</td><td>$row[5]</td><td>$row[6]</td><td>$row[7]</td>";
}
$burrCordResult = updateChart($conn, $model, $dates);
$burrCordResult = ['mon', 'Tue'];
print_r($burrCordResult);
}
?>
<script>var BurrLoc = "<?= $burrCordResult ?>";</script>
javascript code is
console.log(BurrLoc)
The php code is in the middle of the html code. It makes the error
Uncaught ReferenceError: BurrLoc is not defined
I don't know why this matter comes out.
Just do an echo within your script with script tags enclosing it anywhere within your PHP code to send it.
echo "<script>var BurrLoc ='$Burrloc';</script>";

how to use rewrite url using htaccess for the following code

index to intermediate file is going well but it does not pass to statefinder file, please someone help me, its give error 'Object not found!' while the URL is right which are - 'bank-details/Abhyudaya-Cooperative-Bank-Limited'.
Please tell me what is I doing wrong
index.php
<script>
$('#bank_name').change(function(){
$('#form1').submit();
});
</script>
<?php
$res = mysqli_query($conn,$sql);
echo '<div id="div3">';
echo '<form id="form1" method="get" action="imtermediate1.php">';
echo '<img src="images/2.png" style="margin-left:30px">';
echo '<select id="bank_name" name="bank_name">';
echo '<option value="">SELECT BANK NAME</option>';
while($r = mysqli_fetch_array($res))
{
//echo $r['bank_name'];
$name = $r['bank_name'];
$name2 = explode(" ",$name);
//$name3 = implode($name2,'.');
$name5 = "";
for($i = 0; $i<count($name2); $i++)
{
$name3 = $name2[$i];
$name4 = ucfirst(strtolower($name3));
$name5 .= $name4;
}
echo '<option value="'.$name5.'">'.$name.'</option>';
}
imtermediate1.php
<?php
$name = $_GET['bank_name'];
$pieces = preg_split('/(?=[A-Z])/',$name);
$pieces2 = implode($pieces,"-");
$piece3 = ltrim($pieces2,"-");
?>
<script>
var name = "<?php echo $piece3;?>";
window.location = "./" + name;
</script>
statefinder.php
<script>
$('#state').change(function(){
$('#form2').submit();
});
</script>
<?php
$name = $_GET['bank_name'];
$pieces = strtoupper($name);
$piece2 = explode("-",$pieces);
$piece3 = implode($piece2," ");
echo '<form id="form2" method="get" action="imtermediate2.php">';
echo '<img src="images/3.png"><select name="bank_name">';
echo '<option value="'.$name.'">'.$piece3.'</option>';
echo '</select><img src="images/4.png"><br>';
$sql = "SELECT DISTINCT state FROM `TABLE 6` WHERE bank_name='$piece3' ORDER BY state ";
echo '<img src="images/2.png"><select name="state" id="state"><option>Select State Name</option>';
$res = mysqli_query($conn,$sql);
print_r($res);
while($r = mysqli_fetch_array($res))
{
echo '<option>'.$r['state'].'</option>';
}
echo '</select><img src="images/5.png"><br>';
echo '<img src="images/2.png" style="margin-left:-28px"><select><option>District</option></select><br>';
echo '<img src="images/2.png" style="margin-left:-28px"><select><option>Branch</option></select><br>';
echo '</form>';
?>

PHP does not receive parameters from Ajax request [closed]

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>

Three.js : change texture at runtime

I'm creating an UI in which the user will be able to change the texture of the selected object by clicking on the desired textures picture.
The problem is that I can only use the last texture added in the array.
Here is my php which lists the textures in my specified folder:
<ul id="textureH">
<script type="text/javascript">
texArray = [];
</script>
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
if ($extension == 'jpg'){
$texName = $dirArray[$index];
$texId = "texture". $index;
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
texArray.push(texId);
</script>
<?php
echo "<li id='".$texId."'><table><tr><td><img class='texture-image-list' src='img/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
And here's my function:
var uTexture = document.getElementById(texId);
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
var texMap = "./img/" + texName;
for (var i in texArray) {
if ((texArray[i] == texId) && (SELECTED instanceof THREE.Mesh)) {
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
}
}
I think the problem comes from the array.
Thanks to 2pha I could achieve what I wanted to do.
Here's my new code:
(The php/html)
<div class="right-panel-textures">
<h3 id="cat-hierarchy">Textures</h3>
<?php
$myDirectory = opendir('img/textures');
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
sort($dirArray);
closedir($myDirectory);
$indexCount = count($dirArray);
?>
<ul id="textureH">
<?php
for($index=0; $index < $indexCount; $index++) {
$extension = substr($dirArray[$index], -3);
$texName = $dirArray[$index];
$texId = "texture". $index;
if ($extension == 'jpg'){
?>
<script type="text/javascript">
var texName = '<?php echo $texName ?>';
var texId = '<?php echo $texId ?>';
</script>
<?php
echo "<li class='texture-single-item' data-texture-name='".$texName."' data-texture-id='".$texId."' id='texture-single-item'><table><tr><td><img class='texture-image-list' src='img/textures/" . $texName . "' alt='Image' /></td><td><span id='texture-item-name'>" . $texName . "</span></td></tr></table></li>";
}
}
?>
</ul>
</div>
(And the JavaScript)
var uTexture = document.getElementById("texture-single-item");
uTexture.addEventListener("click", updateTexture, false);
function updateTexture(){
$(".texture-single-item").bind("click", function(event) {
var nameT = $(this).attr("data-texture-name");
if (SELECTED instanceof THREE.Mesh) {
var texMap = "./img/textures/" + nameT;
SELECTED.material.map = THREE.ImageUtils.loadTexture(texMap);
SELECTED.material.needsUpdate = true;
}
});
}
Thank you :)

Unable to insert Ajax return into HTML

I'm trying to use a PHP file to process serialized info from an Ajax request. I want to send back the value of each form field to be further manipulated by javascript (inserted into a div). The result is not being inserted into the HTML. When I alert the result I get {"return":["<p>form value for name<\/p>","<p>form value for description<\/p>"]} Any suggestions?
EDIT: Updated question with relevant HTML and revised PHP code.
HTML:
<div class="col-md-4">
<h5>Heading</h5>
<div id="formBasicResults"></div>
</div>
Javascript:
.on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('formValidation');
$.post($form.attr('action'), $form.serialize())
.done(function (result) {
$('#formBasicResults').html(result.responseText);
alert(result);
},'json');
});
PHP:
if (!isset($_SESSION)) {
session_start();
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
} else {
$token = $_SESSION['token'];
}
}
foreach($_POST as $key = > $value) {
$temp = is_array($value) ? $value : trim($value);
$_SESSION[$key] = $temp;
}
$expected = array(
'name' = > 'string',
'description' = > 'string',
);
foreach($expected AS $key) {
if (!empty($_POST[$key])) {
$ {$key} = $_POST[$key];
} else {${$key} = NULL;
}
}
foreach($expected AS $key = > $type) {
if (empty($_POST[$key])) {
$ {$key} = NULL;
continue;
}
if (!isset($ {
$key})) {
$ {$key} = NULL;
}
}
function safe( $value ) {
htmlentities( $value, ENT_QUOTES, 'utf-8' );
return ($value);
}
$name = $_POST['name'];
$description = $_POST['description'];
$return['result']=array();
if(!empty($name)){$return['result'][]= '<p>' . safe($name) . '</p>';}
if(!empty($description)){$return['result'][]= '<p>' . safe($description) . '</p>';}
echo json_encode($return);
try something like this:
$('#formBasicResults').html(result['return'][0]);
or
$('#formBasicResults').html(result['return'][1]);
Instead of this:
if ($_POST['token'] == $_SESSION['token'])
{$return['return']=array();
if(!empty($_POST['name'])){$return['return'][] = '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){$return['return'][] = '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
echo json_encode($return); }}
do this:
$return['responseText']='';
if ($_POST['token'] == $_SESSION['token'])
{
if(!empty($_POST['name'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
}
}
echo json_encode($return);

Categories

Resources