PHP does not receive parameters from Ajax request [closed] - javascript

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>

Related

How to pass variables in a url using javascript and receive them using php?

What I am trying to do is to pass in variables from javascript to a php file using the url. The php is suppose to then parse the url into a json string and then store the json string on a separate text file. The php will then return the json string to the javascript for it to display. After a lot of testing I do believe my code isn't opening the php file or the php isn't parsing the url correctly.
here is the javascript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
obj = this.responseText;
var data = JSON.parse(obj);
alert(data);
txt += "<tr><th>Student Id</th><th>Student Name</th><th>Type</th></tr>";
for (x in data.student){
txt += "<tr><td>" + data.student[x].id + "</td>";
txt += "<td>" + data.student[x].lname + ", " + data.student[x].fname + "</td>";
txt += "<td>" + data.student[x].type + "</td></tr>";
}
document.getElementById("display").innerHTML = txt;
}
xhttp.open("GET", "assign13.php?type="+type+"&fname="+fname+"&lname="+lname+"&id="+id+"&fname2="+fname2+"&lname2="+lname2+"&id2="+id2, true);
xhttp.send();
alert("all done");
}
Here is the php file:
<?php
class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->$fname = $fname;
$this->$type = $type;
$this->$lname = $lname;
$this->$id = $id;
}
}
$s1 = new student();
$s2 = new student();
$type = $_GET["type"];
$fname = $_GET["fname"];
$lname = $_GET["lname"];
$id = $_GET["id"];
$f2 = $_GET["fname2"];
$l2 = $_GET["lname2"];
$i2 = $_GET["id2"];
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1, $s2);
}
else{
$directory = array($s1);
}
$str = json_encode($directory);
file_put_contents("../data/data.txt", $str);
echo $str;
?>
You have errors on your php class, it should be like this.....
<?php
class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->fname = $fname;
$this->type = $type;
$this->lname = $lname;
$this->id = $id;
}
function getAll(){
return [
'fname' => $this->fname,
'type' => $this->type,
'lname' => $this->lname,
'id' => $this->id,
];
}
}
$s1 = new student();
$s2 = new student();
$type = "A";
$fname = "B";
$lname = "C";
$id = "12";
$f2 = "Test";
$l2 = "Test";
$i2 = "10";
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1->getAll(), $s2->getAll());
}
else{
$directory = array($s1->getAll());
}
$str = json_encode($directory);
echo $str;
?>

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

Error while uploading picture from mobile

I'm uploading a picture, it works fine if I am using a computer but if I am using my phone it says:
Sorry, there was an error uploading your slip
<?php
if(isset($_POST["imagea"]) || isset($_POST["imageb"]) || isset($_POST["imagec"]) || isset($_POST["imaged"])){
$post_image = "";
if(isset($_POST["imagea"])){
$post_image = $paying[1];
}
else if(isset($_POST["imageb"])){
$post_image = $paying[2];
}
else if(isset($_POST["imagec"])){
$post_image = $paying[3];
}
else if(isset($_POST["imaged"])){
$post_image = $paying[4];
}
else if(isset($_POST["imagee"])){
$post_image = $paying[5];
}
else if(isset($_POST["imagef"])){
$post_image = $paying[6];
}
else if(isset($_POST["imageg"])){
$post_image = $paying[7];
}
else if(isset($_POST["imageh"])){
$post_image = $paying[8];
}
else if(isset($_POST["imagei"])){
$post_image = $paying[9];
}
else if(isset($_POST["imagej"])){
$post_image = $paying[10];
}
echo "uploading $post_image";
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["slip"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(1) {
// Check file size
if ($_FILES["slip"]["size"] > 5000000) {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, your file is too large.");';
echo " window.location.href = window.location.href;";
echo ' </script>';
$uploadOk = 0;
}
// Allow certain file formats
else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, only JPG, JPEG, PNG & GIF or non empty files are allowed..");';
echo " window.location.href = window.location.href;";
echo ' </script>';
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, your file was not uploaded.");';
echo " window.location.href = window.location.href;";
echo ' </script>';
// if everything is ok, try to upload file
} else {
include "connect.php";
$mem_no = $_COOKIE['mem_no'];
$slip_id = get_slip_id() + 1;
//$paying = get_slip_rec($mem_no);
$today = date('y-m-d');
$slip_name = $mem_no."".$post_image;
$target_file = "uploads/$slip_name.jpg";
if (move_uploaded_file($_FILES["slip"]["tmp_name"], $target_file)) {
if(!slip_exisists("$target_file")){
$sql = "insert into table (slip_id,slip_name,poster,receiver,slip_status,slip_date) values($slip_id,'$slip_name','$mem_no','$post_image','pending','$today')" ;
$result = mysqli_query($conn,$sql);
}
echo "errorf ".mysqli_error($conn);
echo '<script type="text/javascript">';
echo 'alert("your deposit slip have been successfully uploaded please wait for your payment to be confirmed");';
echo " window.location.href = window.location.href;";
echo ' </script>';
} else {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, there was an error uploading your slip.");';
echo " window.location.href = window.location.href;";
echo ' </script>';
}
}
}
function slip_exisists($slip_name){
include "connect.php";
$sql = "select * from slip where slip_name = $slip_name and slip_status = 'pending'";
$result = mysqli_query($conn,$sql);
if($result){
return true;
}
else{
return false;
}
}
function get_slip_id(){
include "connect.php";
$sql = "select slip_id from slip order by slip_id desc";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_array($result,MYSQLI_NUM);
return $row[0];
}
else{
return 1;
}
}
function get_slip_rec($mem_noi){
include "connect.php";
$sql = "select mem_no from pay_request, req_hist where paying member = '$mem_noi' and pay_request.request_code = req_hist.request_code";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_array($result,MYSQLI_NUM);
return $row[0];
}
else{
return '404';
}
}
}
?>

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);

AJAX responseXML error: Uncaught TypeError

I am having the following code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
result = xmlhttp.responseXML.getElementsByTagName("tr");
if(result)
console.log(result);
showTable(result);
isClicked = false;
}
}
xmlhttp.open("GET", "php_includes/getResult.php?search=" + document.getElementById("search").value, true);
xmlhttp.send();
my file will produce something like:
<tr><td>1</td><td>APPLES</td><td> 0000000000414</td><td>$0.79</td></tr>
<tr><td>2</td><td>Apple Sauce</td><td> 0000000000528</td><td>$1.92</td></tr>
<tr><td>3</td><td>Apple</td><td> 0000000000540</td><td>$0.59</td></tr>
<tr><td>4</td><td>Snapple</td><td> 0000000000543</td><td>$0.69</td></tr>
By running the code I get the following error:
"Uncaught TypeError: Cannot call method 'getElementsByTagName' of null"
However, when I use the xmlhttp.responseText it get the result. Any idea?
This is my PHP file:
$x = 1;
$count = 0;
$result2 = array();
$result .= "<search>";
while ($row = sqlsrv_fetch_array($stmt)) {
// $class = ($x % 2 !== 0) ? 'whiteBackground' : 'graybackground';
//echo "OOMAD INJA";
//$name = sqlsrv_get_field( $stmt, 0);
//echo "$i $name<br/>";
//setlocale(LC_MONETARY, 'en_US');
$plu = $row["F01"];
$result2[] = $row['F02'];
//$result .= "<tr class='$class' onclick = 'clicked($plu);' onmouseover='ChangeColor(this, true);' onmouseout='ChangeColor(this, false);' ><td>" . $x . "</td><td class='searchtable'>" . $row["F02"] . "</td><td> " . $row["F01"] . "</td><td height= '40px'>\$" . number_format((float) $row["F30"], 2, '.', '') . "</td></tr>";
$result .= "<tr1><td1>" . $x . "</td1><td2>" . htmlentities($row["F02"]) . "</td2><td3> " . $row["F01"] . "</td3><td4>\$" . number_format((float) $row["F30"], 2, '.', '') . "</td4></tr1>";
$x++;
}
$result .="</search>";
echo $result;

Categories

Resources