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);
Related
I want to get set if statement of no. of count of array from database. I already have a if statement checking the count but I am unable to use it in my file.
Help me replicate the count if statement here. I want to wrap pro_type and is_pro in if statement of no. of counts similar in reaferandearn page .
My function where I need if count statement :
users.php file
public function update_valid_refer_point($id){
global $db;
$user_balance = $db->where('id',$id)
->getOne('users',array('balance'));
$_POST['pro_type'] =4;
$_POST['is_pro'] =1;
$bal =$user_balance['balance']+500;
$updated = $db->where('id', $id)
->update('users', array('pro_type' => 4,'is_pro' => 1,'balance' => $bal));
return TRUE;
}
The file where I have similar if count statement but I have no idea how to use it above :
referandearn.php
if(count($data['refferal_data']['data']) > 0){
for($u=0; $u<count($data['refferal_data']['data']);$u++){
$userFirstName = $data['refferal_data']['data'][$u]->first_name;
$userLastName = $data['refferal_data']['data'][$u]->last_name;
$userName = $userFirstName.' '.$userLastName;
$userProfilePhoto = $data['refferal_data']['data'][$u]->avater;
$refferalDate = date('d - M - Y',strtotime($data['refferal_data']['data'][$u]->refferalDate));
$userRefferalCode = $data['refferal_data']['data'][$u]->refferalCode;
?>
<li>
<img src="<?php echo $userProfilePhoto;?>" width="75" height="75" viewBox="0 0 24 24" style="margin-right: 15px; border-radius: 50%;"/>
<?php echo $userName."<br>".$refferalDate;?>
</li>
<?php
}
}else{
?>
<li>
<?php echo 'No reffered user yet';?>
</li>
<?php
}
?>
referandearn controller :
Class Referearn extends Theme {
public static function LoadreffralUsers() {
global $_AJAX, $_CONTROLLERS;
$data = '';
$ajax_class = realpath($_CONTROLLERS . 'aj.php');
$ajax_class_file = realpath($_AJAX . 'loadmore.php');
if (file_exists($ajax_class_file)) {
require_once $ajax_class;
require_once $ajax_class_file;
$_POST['page'] = 1;
$loadmore = new Loadmore();
$refferal_users = $loadmore->refferal_users();
parent::$data['refferal_data'] = $refferal_users;
/*if (isset($refferal_users['html'])) {
$data = $refferal_users['html'];
}*/
}
return $data;
}
}
And loadmore referusers function :
function refferal_users() {
global $db, $_BASEPATH, $_DS,$_excludes;
if (self::ActiveUser() == NULL) {
return array(
'status' => 403,
'message' => __('Forbidden')
);
}
$error = '';
$page = 0;
$perpage = 7;
$html = '';
$html_imgs = '';
$template = '';
if (isset($_POST) && !empty($_POST)) {
if (isset($_POST[ 'page' ]) && (!is_numeric($_POST[ 'page' ]) || empty($_POST[ 'page' ]))) {
$error = '<p>• ' . __('no page number found.') . '</p>';
} else {
$page = (int) Secure($_POST[ 'page' ]) - 1;
}
}
if ($error == '') {
$limit = $perpage;
$offset = $page * $perpage;
//$query = GetRefferalUserQuery(self::ActiveUser()->id, $limit, $offset);
//exit;
//$refferal_users = $db->rawQuery($query);
$sql = 'SELECT U.id,U.online,U.lastseen,U.username,U.avater,U.country,U.first_name,U.last_name,U.location,U.birthday,U.language,U.relationship,U.height,U.body,U.smoke,U.ethnicity,U.pets,U.gender, RU.refferalDate, RU.refferalCode FROM users U INNER JOIN refferalusers RU ON RU.refferalBy = U.id ';
$sql .= ' WHERE RU.refferalTo = '.self::ActiveUser()->id.' AND ( ';
$sql .= ' U.verified = "1" AND U.privacy_show_profile_random_users = "1" ';
// to exclude blocked users
$notin = ' AND U.id NOT IN (SELECT block_userid FROM blocks WHERE user_id = '.self::ActiveUser()->id.') ';
// to exclude liked and disliked users users
$notin .= ' AND U.id NOT IN (SELECT like_userid FROM likes WHERE ( user_id = '.self::ActiveUser()->id.' OR like_userid = '.self::ActiveUser()->id.' ) ) ';
$sql .= ' ) ';
$sql .= ' ORDER BY U.id DESC LIMIT '.$limit.' OFFSET '.$offset.';';
$random_users = $db->objectBuilder()->rawQuery($sql);
$theme_path = $_BASEPATH . 'themes' . $_DS . self::Config()->theme . $_DS;
//$template = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'random_users.php';
//$template1 = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'matches_imgs.php';
if (file_exists($template)) {
foreach ($random_users as $random_user) {
if($random_user->id!=(int)auth()->id){
ob_start();
require($template);
$html .= ob_get_contents();
ob_end_clean();
}
}
}
return array(
'status' => 200,
'page' => $page + 2,
'html' => $html,
'data' => $random_users
);
} else {
return array(
'status' => 400,
'message' => $error
);
}
}
I want to get set if statement of no. of count of array from database. I already have a if statement checking the count but I am unable to use it in my file.
Help me replicate the count if statement here. I want to wrap pro_type and is_pro in if statement of no. of counts similar in reaferandearn page .
My function where I need if count statement :
users.php file
public function update_valid_refer_point($id){
global $db;
$user_balance = $db->where('id',$id)
->getOne('users',array('balance'));
$_POST['pro_type'] =4;
$_POST['is_pro'] =1;
$bal =$user_balance['balance']+500;
$updated = $db->where('id', $id)
->update('users', array('pro_type' => 4,'is_pro' => 1,'balance' => $bal));
return TRUE;
}
The file where I have similar if count statement but I have no idea how to use it above :
referandearn.php
if(count($data['refferal_data']['data']) > 0){
<?php
}>
referandearn controller :
Class Referearn extends Theme {
public static function LoadreffralUsers() {
global $_AJAX, $_CONTROLLERS;
$data = '';
$ajax_class = realpath($_CONTROLLERS . 'aj.php');
$ajax_class_file = realpath($_AJAX . 'loadmore.php');
if (file_exists($ajax_class_file)) {
require_once $ajax_class;
require_once $ajax_class_file;
$_POST['page'] = 1;
$loadmore = new Loadmore();
$refferal_users = $loadmore->refferal_users();
parent::$data['refferal_data'] = $refferal_users;
/*if (isset($refferal_users['html'])) {
$data = $refferal_users['html'];
}*/
}
return $data;
}
}
And loadmore referusers function :
function refferal_users() {
global $db, $_BASEPATH, $_DS,$_excludes;
if (self::ActiveUser() == NULL) {
return array(
'status' => 403,
'message' => __('Forbidden')
);
}
$error = '';
$page = 0;
$perpage = 7;
$html = '';
$html_imgs = '';
$template = '';
if (isset($_POST) && !empty($_POST)) {
if (isset($_POST[ 'page' ]) && (!is_numeric($_POST[ 'page' ]) || empty($_POST[ 'page' ]))) {
$error = '<p>• ' . __('no page number found.') . '</p>';
} else {
$page = (int) Secure($_POST[ 'page' ]) - 1;
}
}
if ($error == '') {
$limit = $perpage;
$offset = $page * $perpage;
//$query = GetRefferalUserQuery(self::ActiveUser()->id, $limit, $offset);
//exit;
//$refferal_users = $db->rawQuery($query);
$sql = 'SELECT U.id,U.online,U.lastseen,U.username,U.avater,U.country,U.first_name,U.last_name,U.location,U.birthday,U.language,U.relationship,U.height,U.body,U.smoke,U.ethnicity,U.pets,U.gender, RU.refferalDate, RU.refferalCode FROM users U INNER JOIN refferalusers RU ON RU.refferalBy = U.id ';
$sql .= ' WHERE RU.refferalTo = '.self::ActiveUser()->id.' AND ( ';
$sql .= ' U.verified = "1" AND U.privacy_show_profile_random_users = "1" ';
// to exclude blocked users
$notin = ' AND U.id NOT IN (SELECT block_userid FROM blocks WHERE user_id = '.self::ActiveUser()->id.') ';
// to exclude liked and disliked users users
$notin .= ' AND U.id NOT IN (SELECT like_userid FROM likes WHERE ( user_id = '.self::ActiveUser()->id.' OR like_userid = '.self::ActiveUser()->id.' ) ) ';
$sql .= ' ) ';
$sql .= ' ORDER BY U.id DESC LIMIT '.$limit.' OFFSET '.$offset.';';
$random_users = $db->objectBuilder()->rawQuery($sql);
$theme_path = $_BASEPATH . 'themes' . $_DS . self::Config()->theme . $_DS;
//$template = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'random_users.php';
//$template1 = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'matches_imgs.php';
if (file_exists($template)) {
foreach ($random_users as $random_user) {
if($random_user->id!=(int)auth()->id){
ob_start();
require($template);
$html .= ob_get_contents();
ob_end_clean();
}
}
}
return array(
'status' => 200,
'page' => $page + 2,
'html' => $html,
'data' => $random_users
);
} else {
return array(
'status' => 400,
'message' => $error
);
}
}
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;
?>
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 can't retrieve json string data from my php script using ajax call.
Here is my ajax script :
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(data){
$("#app_panel").append(data.html);
$('.inv_date').hide();
}
});
and this is my php script:
<?php
//wall ===================================================
session_start();
include("../../dbinfo.inc.php");
$from = $_POST['from'];
$to = $_POST['to'];
$sel = $_POST['sel'];
// connect to the database
$client_id = $_SESSION['clientid'];
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
$results = array(
'html' => $html
);
$html = " ";
if($sel == "all"){
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
}else{
$query=" select * from tele_panel_call where (client='$client_id' AND date_time BETWEEN '$from' AND '$to') ORDER BY date_time DESC";
$result = $mysqli->query($query);
}
if ($result->num_rows > 0){
while ($row = $result->fetch_object())
{
$from = $row->from;
$to = $row->to;
$html .= '<div style="width:590px;height:15px;background: url(img/clientimg/wrap-white.png)repeat;padding: 5px 5px 5px 5px;margin-bottom:5px;">';
$query_from=" select * from tele_agent_dialer where (client='$client_id' AND (dialer='$from' OR dialer='$to'))";
$result_from = $mysqli->query($query_from);
$row_from = $result_from->fetch_assoc();
$dialer = $row_from['dialer'];
if($dialer == $from){
$image = 'outgoing';
$out = $out+1;
}
if($dialer == $to){
$image = 'incoming';
$in = $in+1;
}
if($dialer != $to & $dialer != $from){
$image = 'extension';
$ext = $ext+1;
}
$html .= '<img src="img/clientimg/'; $html .= $image; $html .= '.png" style="float:left;margin-right:10px;height:15px">';
$html .= '<div style="float:left;margin-right:5px;width:135px;height:30px;overflow:hidden;"><b>From: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $from, $matches ) )
{
$from = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $from;
$html .= '</div>
<div style="float:left;margin-right:5px;width:125px;height:30px;overflow:hidden;">
<b>To: </b>';
if( preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $to, $matches ) )
{
$to = '('. $matches[1] . ') ' .$matches[2] . '-' . $matches[3];
}
$html .= $to;
$html .= '</div>
<div style="float:left;width:160px;margin-right:5px;height:30px;overflow:hidden;">
<b>Date/Time: </b>'; $html .= $row->date_time;
$html .= '</div>
<div style="float:left;width:100px;margin-right:5px;height:30px;overflow:hidden;">
<b>Duration: </b>';
$duration = $row->duration;
preg_match("#(\d+):(\d+)#", $duration, $matches );
$min = $min + $matches[1];
$sec = $sec + $matches[2];
$html .= $duration;
$html .= '</div>';
$html .= '</div>';
}
}else{
echo "No results to display!";
}
$jsonString = json_encode($results);
echo $jsonString;
$mysqli->close();
?>
Can someone please tell me what I'm doing wrong here? My php script doesn't have any errors when I check the page itself.
Also it's good to add proper header for json data output (at the begining of the script for example).
header("Content-Type: application/json");
As for query results, you should debug it. Try to print the query and run it in Phpmyadmin (or other database administration tool)