Jump to content

netpumber

Members
  • Posts

    107
  • Joined

  • Last visited

Posts posted by netpumber

  1. Hello.

     

    Server returns this json

    {"status":1,"job_status":"READY","iterations":["Contig2","Contig75"],"accessions":["NP_001061702","NP_001068174"]}

    And i would like to print out in a textarea (using the above jQuery command)

    $('#info').val()

    something like this:

     

    Contig2 : NP_001061702

    Contig75 : NP_001068174

     

    Any idea on how to achieve this?

     

    Thanks!

  2. Hmm i

     

    created a global var

    $aR = '';

    then in the 

    // Submit Data to ncbi.
    // Sends form's data to classController.php
    function NCBI_submit_data()
    {
        $formData = $('#blastx_form').serialize();
        $php_method = 'ncbi_request';    
        $finalData = $formData + "&php_method=" + $php_method;
        $aR = ajaxReq('POST','../../classes/classController.php',$finalData,'json');
        console.log($aR);
    }
    
    
    // General Ajax function
    function ajaxReq($method,$url,$data,$dataType)
    {
        $.ajax({
            type: $method,
            url:  $url,
            async: 'false',
            data: $data,
            dataType: $dataType,
            success: function(json, textStatus, jqXHR)
            {
                $aR = json;
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                console.log('Ajax call error: '+jqXHR.status+' '+errorThrown)                
            }
        });
    }

    But doesn't seem to work.

  3. Hi!

     

    I have this code above:

     

    // Submit Data to ncbi.
    // Sends form's data to classController.php
    function NCBI_submit_data()
    {
        $formData = $('#blastx_form').serialize();
        $php_method = 'ncbi_request';    
        $finalData = $formData + "&php_method=" + $php_method;
        $aR = ajaxReq('POST','../../classes/classController.php',$finalData,'json');
        console.log($aR);
    }
    
    
    // General Ajax function
    function ajaxReq($method,$url,$data,$dataType)
    {
        $.ajax({
            type: $method,
            url:  $url,
            async: 'false',
            data: $data,
            dataType: $dataType,
            success: function(json, textStatus, jqXHR)
            {
                return json;
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                console.log('Ajax call error: '+jqXHR.status+' '+errorThrown)                
            }
        });
    }

    Server returns a json object and i want to save it in aR variable.

    But console.log($aR); returns undefined

     

    Any idea on how to fix it ?

     

  4. I changed the path but im still getting this error :

     

    Warning: move_uploaded_file(/var/www/httpdocs/geneBank/mupload/uploads/PL-17534/1.jpg): failed to open stream: Permission denied in/var/www/httpdocs/geneBank/mupload/upload.php on line 47

    Warning: move_uploaded_file(): Unable to move '/tmp/php2HcnFL' to '/var/www/httpdocs/geneBank/mupload/uploads/PL-17534/1.jpg' in /var/www/httpdocs/geneBank/mupload/upload.phpon line 47

     

  5. Finally with ZAP tool found that the upload.php file returns this :

     

    Warning: move_uploaded_file(uploads/PL-17534/1.jpg): failed to open stream: Permission denied in /var/www/httpdocs/geneBank/mupload/upload.php on line 47

    Warning: move_uploaded_file(): Unable to move '/tmp/phpn7XUJH' to 'uploads/PL-17534/1.jpg' in /var/www/httpdocs/geneBank/mupload/upload.php on line 47

     

     

    upload directory has 777 permissions and chowned to http user , but the message id still produced .

  6. From the PHP manual on error code 3

     

    Which means for some reason the client (the users browser) is not uploading file properly. Maybe the connection between the server and client is being timeout/lost? 

     

     

    Yes i know what error code 3  means but the weird thing is that the server and the client is the same PC in both cases. Either if i'm running the application locally (127.0.0.1) or running it through the web (e.g www.blahblah.com). I cannot find a reason for the connection to timeout/lost , every time i'm trying it.

  7. Hello!

     

    I have a problem with uploading some files from my web app, when i m running it through Apache's document root.

     

    Let's take it from the beginning.

     

    I have create a vhost where all the files of my web app are there.

    Here is the vhost directive of apache's config

     

    <VirtualHost 127.0.0.1:80>
        DocumentRoot "/home/n3t/dev/http/geneBank/"
        ServerName dev.geneBank
        ServerAlias dev.geneBank
        ErrorLog "/var/log/httpd/VHost-geneBank/error_log"
        CustomLog "/var/log/httpd/VHost-geneBank/access_log" common
        <Directory /home/n3t/dev/http/geneBank/>
                        DirectoryIndex index.htm index.html index.php
                        Options ExecCGI Indexes FollowSymLinks MultiViews Includes
                        AllowOverride All
                        Order allow,deny
                        allow from all
                        Require all granted
        </Directory>
    </VirtualHost>

    and here is the php file that uploads files.

     

    <?php
    
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    
    // A list of permitted file extensions
    $allowed = array('png', 'jpg', 'gif');
    
    // Check if a rec id has sent and creates a directory with its name.
    if($_POST['uplRecID'] != ''){
    
            //Check if the given RecId is valid by begining with 'PL'.
            $str = substr($_POST['uplRecID'], 0, 2);
            if($str == 'PL'){
    
                    // Check if the directory allready exists.
                    if(!file_exists("uploads/".$_POST['uplRecID'])){
    
    
                            echo " Dir didn't exist and we create it now..";
                            if(!mkdir("uploads/".$_POST['uplRecID'], 0777)){
                                    echo '{"status":"error creating the dir"}';
                            }
                    }
            }else{
                    echo '{"status":"Unaccepted recID"}';
                    exit;
            }
    }
    
    
    if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
    
    
            $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
    
    
            if(!in_array(strtolower($extension), $allowed)){
                    echo '{"status":"Unaccepted extension"}';
                    exit;
            }
    
    
    
    
            if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_POST['uplRecID'].'/'.$_FILES['upl']['name'])){
                    echo '{"status":"success"}';
                    exit;
            }
    }else{
    
    echo $_FILES['upl']['error'];
    echo '{"status":"error"}';
    exit;
    
    
    }
    ?>
    So, when im running this code from dev.geneBank (Vhost) everything works like a charm. But when i move that code into apache's document root (/var/www/httpdocs/) directory and run it through the web (not locally) , $_FILES['upl']['error'] returns error with number 3.
     
    So i thought that maybe the fault is that document root isn't configured for file uploading.
     
    If i am correct, is there any way to configure the document root using .htaccess file ? I don't want to change the main httpd.conf file.
     
    Thank you.
     
  8. Hi!

     

    Server sends such a json object:

    {"status":1,"recId":"PL-17534","collectionDate":"08-04-2014","collectorsName":"asdf","donorsName":"","sciName":"asdf","family":"asdf","comName":"asdf","variety":"","area":"asdf","photoFiles":["1.jpg","internet.jpg"]}

    So i want to change the html content of an element , by customizing the contents of json object in the photoFiles array.

     

    I tried something like this but doesn't seem to work

     

    $('#photosTab').html(function(){
        $.each(json.photoFiles, function(i,item){
        return '<img src="'+json.photoFiles[0]+'"><br>';
        })
    });

    Any idea ?

     

  9. Hello guys.

     

    I have a file with the above function that returns the $db variable.

     

    function mysql_init(){
    $db = new PDO('mysql:host=localhost;dbname=geneticDb;charset=utf8', 'dev', 'dev');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
    return $db; 
    }

    Now i want to use this variable in every method of the above class without call again that function in each method. Somehow i want to call this once and then just use the $db variable.

     

    <?php
    require_once('mysql.php');
    
    
    class Note
    {
    private $_done; 
    private $_noteType;
    private $_plantId;
    private $_noteTitle;
    private $_noteText;
    private $_regenerationDate;
    private $_noteId;
    
    
    public function __construct()
    {
    
    
    }
    
    
    public function addNote($noteType, $plantId , $noteTitle, $noteText)
    {
    $this->_noteType = $noteType;
    $this->_plantId = $plantId;
    $this->_noteTitle = $noteTitle;
    $this->_noteText = $noteText;
    
    
    $db = mysql_init();
    $sql = "INSERT INTO notes ( noteId , noteType, plantId, noteTitle, noteText ) VALUES ('', ?, ?, ?, ?)";
    $prq = $db->prepare($sql);
    $prq->bindValue(1,$this->_noteType, PDO::PARAM_STR);
    $prq->bindValue(2,$this->_plantId,PDO::PARAM_INT);
    $prq->bindValue(3,$this->_noteTitle,PDO::PARAM_STR);
    $prq->bindValue(4,$this->_noteText,PDO::PARAM_STR);
    
    
    
    
    ($prq->execute()) ? $this->_done = 1 : $this->_done = 0;
    
    
    
    
    if ($this->_done == '0')
    {
    $json = array('status' => $this->_done, 'error' => $prq->errorCode() );
    $JsonObject = json_encode($json);
    }else{
    $json = array('status' => $this->_done);
    $JsonObject = json_encode($json);
    }
    
    
    
    
    echo $JsonObject;
    }
    
    
    public function addRegenerationNote($noteType, $plantId , $regenerationDate)
    {
    $this->_noteType = $noteType;
    $this->_plantId = $plantId;
    $this->_regenerationDate = $regenerationDate;
    
    
    $db = mysql_init();
    $sql = "INSERT INTO notes ( noteId , noteType, plantId, regenerationDate ) VALUES ('', ?, ?, ?)";
    $prq = $db->prepare($sql);
    $prq->bindValue(1,$this->_noteType,PDO::PARAM_STR);
    $prq->bindValue(2,$this->_plantId,PDO::PARAM_INT);
    $prq->bindValue(3,$this->_regenerationDate,PDO::PARAM_STR);
    
    
    ($prq->execute()) ? $this->_done = 1 : $this->_done = 0;
    
    
    
    
    if ($this->_done == '0')
    {
    $json = array('status' => $this->_done, 'error' => $prq->errorCode() );
    $JsonObject = json_encode($json);
    }else{
    $json = array('status' => $this->_done);
    $JsonObject = json_encode($json);
    }
    
    
    
    
    echo $JsonObject;
    }
    
    .....

    As you can see i call in every method the mysql_init() function. Is it possible to call it only once at the start of the class and then just use the $db var ?

     

    Thank you.

  10. I have this php code for counting the pages number and retrieve data from database, but something is going wrong with the pager as i can see.

    Specifically i think that there is a problem with the json file structure.

    Here is the php code:

    public function getLogsList($page,$limit,$sidx,$sord)
    {
    init_mysql();
    
    $return_array = array();
    $row_array = array();
    
    // Getting pages number (for jqGrid pager)
    
    if(!$sidx) $sidx =1;
    $result = mysql_query("SELECT COUNT(*) AS count FROM logs");
    $row = mysql_fetch_array($result);
    $count = $row['count']; 
    
    if( $count >0 ) {
    $total_pages = ceil($count/$limit);
    } else {
    $total_pages = 0;
    }
    
    if ($page > $total_pages) $page=$total_pages;
    $start = $limit*$page - $limit;
    
    $row_array['page'] = $page;
    $row_array['total'] = $total_pages;
    $row_array['records'] = $count;
    
    array_push($return_array,$row_array);
    
    // Getting data for jqGrid table
    
    $data = mysql_query("SELECT * FROM logs ORDER BY log_id DESC");
    
    if(mysql_num_rows($data))
    {
    while($row = mysql_fetch_array($data)) 
    {
    
    $row_array['log_id'] = $row['log_id'];
    $row_array['ip'] = $row['ip'];
    $row_array['hostname'] = $row['host'];
    $row_array['log'] = $row['input'];
    $row_array['date'] = $row['date'];
    
    array_push($return_array,$row_array);
    } 
    }
    
    echo json_encode($return_array);
    }

    The json file looks like this :

    [{"page":"1","total":2,"records":"34"},{"page":"1","total":2,"records":"34","log_id":"108","ip":"127.0.0.1","hostname":"","log":"having 1=1","date":"09-06-2013 22:05:57"},{"page":"1","total":2,"records":"34","log_id":"107","ip":"127.0.0.1","hostname":"","log":"\/\/","date":"09-06-2013 22:05:57"},.....}]

    as you can see page , total and records are printed every time and thats why i think that something is going wrong with the structure of json file.

     

    I saw in a forum that the json file must have this structure but i cannot make it look like this

    {
    "page": "1",
    "total": 1,
    "records": "6",
    "rows": [
    {
    "head": {
    "student_name": "Mr S. Jack ",
    "year": 2007
    
    },
    "sub": [
    {
    "course_description": "Math ",
    "date": "22-04-2010",
    "number": 1,
    "time_of_add": "2:00",
    "day": "today"
    }
    ]
    
    }
    ]
    }

    Can you help me on this issue ?

     

    Thanks in advance

     
  11. Hello i was watching

    video on how to create a login script in php and i thought to use it.

     

    So here is the code :

     

    <?php
    
    include("config.php");
    
    class login
    {
    	private $_id;
    	private $_username;
    	private $_password;
    	private $_passmd5;
    
    	private $_errors;
    	private $_access;
    	private $_login;
    	private $_token;
    	
    
    	public function __construct()
    	{
    		$this->_errors 	= 	array();
    		$this->_login 	= 	isset($_POST['login']) ? 1 : 0 ;
    		$this->_access 	= 	0;
    		$this->_token 	= 	($this->_login) ? $_POST['token'] : $_SESSION['token'];
    
    		$this->_id 	= 	0;
    		$this->_username	= 	($this->_login) ? $this->filter($_POST['username']) : $this->$_SESSION['username'];
    		$this->_password	= 	($this->_login) ? $this->filter($_POST['password']) : '';
    		$this->_passmd5		= 	($this->_login) ? md5($this->_password) : $this->$_SESSION['password'];
    
    	}
    
    	public function isLoggedIn()
    	{
    		($this->_login) ? $this->verifyPost() : $this->verifySession();
    		return $this->_access;
    	}
    
    	public function filter($var)
    	{
    		return preg_replace('/[^a-zA-Z0-9]/', '', $var);
    	}
    
    	public function verifyPost()
    	{
    		try
    		{
    			if(!$this->isTokenValid())
    				throw new Exception("Invalid Form Submition");
    
    			if(!$this->isDataValid())
    				throw new Exception("Invalid Form Data");
    
    			if(!$this->verifyDatabase())
    				throw new Exception("Invalid Username/Password");
    
    		$this->_access = 1;
    		$this->registerSession();				
    		}
    
    		catch(Exception $e)
    		{
    			$this->_errors[] = $e->getMessage();
    		}
    	}
    
    	public function verifySession()
    	{
    		if($this->sessionExist() && $this->verifyDatabase())
    			$this->_access = 1;
    	}
    
    	public function verifyDatabase()
    	{
    		init_mysql();
    
    		$data = mysql_query("SELECT user_id FROM users WHERE user_name = '{$this->_username}' AND user_password='{$this->_passmd5}'");
    
    		if(mysql_num_rows($data))
    		{
    			$row = mysql_fetch_assoc($data);
    			$this->_id = $row['user_id'];
    			return true;
    		}
    		else
    		{
    			return false;
    		}
    	
    	}
    
    	public function isDataValid()
    	{
    		return preg_match('/^[a-zA-Z0-9]{5,12}$/', $this->_username) && preg_match('/^[a-zA-Z0-9]{5,12}$/', $this->_password) ? 1 : 0 ;
    	}
    
    	public function isTokenValid()
    	{
    		return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token']) ? 0 : 1;
    	}
    
    	public function registerSession()
    	{
    		$_SESSION['ID'] 		= $this->_id;
    		$_SESSION['username'] 	= $this->_username;
    		$_SESSION['password']	= $this->_passmd5;
    	}
    
    	public function sessionExist()
    	{
    		return (isset($_SESSION['username']) && isset($_SESSION['password'])) ? 1 : 0;
    	}
    
    	public function showErrors()
    	{
    		echo "<h3>Errors</h3>";
    
    		foreach ($this->_errors as $key => $value) {
    			echo $value . "<br>";
    		}
    	}
    
    }
    
    
    ?>
    

     

     

    Here is the code of login.php

     

    <?php
    session_start();
    
    $token = $_SESSION['token'] = md5(uniqid(mt_rand(),true));
    
    if(isset($_POST['login']))
    {
    	include('classes/class.login.php');
    
    	$login = new Login;
    
    	if($login->isLoggedIn())
    		header('location: op-index.php');
    	else
    		$login->showErrors();	
    }
    ?> 

     

     

    But it seems that i have a problem with isTokenValid() Function.

     

     

    return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token']) ? 0 : 1;
     

    If i try to login it returns me this error Invalid Form Submition but i cannot understand why.

     

    So if i change the above code into this 

     

     

    return (!isset($_SESSION['token'])  ? 0 : 1;
     

    everything works like a charm but when is the || operator it returns false.

     

    Can someone image why this could happen ?

     

    Also $this->_token will be always different from $_SESSION['token'] because the $token variable changes after the form submition.

  12. Hello im trying to make a text editor for a site and i have some problems with javascript.

     

    I started here as simple as can be, without any textarea and so.

    At first im just trying to modify a <p>.

    Here you can see the code.

     

    http://jsfiddle.net/9e753/

     

    As you can try i can make the text bold but i cannot undo it.

     

    Also i want to ask you haw can i achieve to make this change:

    (lets say we have a bolded text)

     

    text

     

    and we want to unbold only two or one letter eg:

     

    text

    text

     

    and so on...

     

    Any hint is welcomed.

    Thanks in advance.

  13. Hello out there.

     

    Im trying to create a simple text editor for a web site.

    I want to add to him something like the code button in this forum.

    So by selecting a specific text, color it's background with gray color.

    Here is what i have for now but if i have a multi row text selected(rows created by pressing enter) the function test() doesn't work. It works only if i select a row each time.

     

    
    
    <!DOCTYPE html>
    
    
    <html lang="en" xmlns="http://www.w3.org/1999/html"> 
    <head>
    
    
    
     <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" href="Awesome/css/font-awesome.css">
    
    
    
    </head>
    <body onload="InitEditable()">
    
    
     <div style="margin-left:10px;">
       <p>
         <div class="btn-group">
          <a class="btn" href="#" onclick="fontEdit('bold')"><i class="icon-bold"></i></a>
          <a class="btn" href="#" onclick="fontEdit('italic')"><i class="icon-italic"></i></a>
          <a class="btn" href="#" onclick="fontEdit('underline')"><i class="icon-underline"></i></a>
          <a class="btn" href="#" onclick="test()"><i class="icon-link"></i></a>
           <a class="btn" href="#" onclick="fontEdit('justifyLeft')"><i class="icon-align-left"></i></a>
           <a class="btn" href="#" onclick="fontEdit('justifyCenter')"><i class="icon-align-center"></i></a>
           <a class="btn" href="#" onclick="fontEdit('justifyRight')"><i class="icon-align-right"></i></a>
           <a class="btn" href="#" onclick="fontEdit('justifyFull')"><i class="icon-align-justify"></i></a>
         </div>
       </p>
     </div>
    
    
     <div style="margin-left:10px;"><iframe id="textEditor" style="width:500px;height:170px;font-family:arial;font-size:11px;"></iframe></div>
    
    
    
    
    <script type="text/javascript">
    
    
    var editorDoc;
    var editor;
    
    
    function InitEditable() 
    {
     editor = document.getElementById("textEditor");
     editorDoc = editor.contentwindow.document;          
     var editorBody = editorDoc.body;
    
    
     if ('contentEditable' in editorBody) {
             // allow contentEditable
         editorBody.contentEditable = true;
     }else {  // Firefox earlier than version 3
    
         if ('designMode' in editorDoc) {
                 // turn on designMode
             editorDoc.designMode = "on";                
         }
     }
    }
    
    
    
    function fontEdit(x,y)
    {
    editorDoc.execCommand(x,"",y);
    editorDoc.focus();
    }
    
    
    function test(){
    
    
     var range = document.getElementById("textEditor").contentwindow.window.getSelection().getRangeAt(0);
    
    
    
     var newNode = document.createElement('div');
     newNode.style.backgroundColor = "gray";
    
    
     range.surroundContents(newNode);    
     return false;  
    
    
    }
    </script>
    
    
    </body>
    </html>
    
    

     

    There must be a problem with surroundContents() and divs but cannot think something to solve it.

     

    Any idea is welcomed!

    Thanks in advance.

  14. Hello again.

     

    I tried it out with ajax.

     

    <html>
    <head>
    
    <script language="JavaScript" src="json.js"></script>
    </head>
    <body>
    
      <textarea id="text"></textarea>
    
    <script type="text/javascript">
      
      var httpRequest; 
      var textarea = document.getElementById('text');
    
      
        if (window.XMLHttpRequest) { 
          httpRequest = new XMLHttpRequest();
        } 
         
        if (!httpRequest) {
          alert('Giving up  Cannot create an XMLHTTP instance');
          return false;
        }
        httpRequest.onreadystatechange = loopData;
        httpRequest.open('GET', 'http://localhost/json/data.php', true);
        httpRequest.send();
      
      function loopData()
      {
        setTimeout(alertContents,2000);
      }
    
      function alertContents() {
        if (httpRequest.readyState === 4) {
          if (httpRequest.status === 200) {
            
            var vars = JSON.parse(httpRequest.responseText);
            textarea.value = vars[0];
          } else {
            alert('There was a problem with the request.');
          }
        }
      }
    
      
    
    </script>
    </body>
    </html>

     

    At data.php file i create an array() called $vars that fills with a loop. Then ajax receives the output of data.php and print them in textarea.

     

    The problem remains. Ajax has to wait till data.php end up with the loop , and then it (ajax) can receive the output.

     

    I wanna make it work like this:

     

     

    php file

    ajax

    in first loop $vars[0]="h"

    print out h

    in second loop $vars[1]="e"

    print out e

    in third loop $vars[2]="l"

    print out l

     

    and so on...

    Any more hint ?

     

    Thank you.

     

     

  15. Thank you for the code.

     

    Tried to change it and make it to take the value from a php loop and print it out in the textarea but nothing happened. With some way i have to synchronize php with javascript and i think this is impossible. Here is the code

     

    <textarea id='txt' cols="30" rows="5"></textarea>
    <br />
    <script type="text/javascript">
            document.getElementById("txt").value="";
    </script>
    
    <?php
    
    $i=0;
    for($i=0;$i<=10;$i++)
    { ?>
    <script type="text/javascript">
            var t = document.getElementById("txt");       
            t.value = t.value + <?php echo json_encode($i);?>;
    </script>
    
    <?php
    }
    ?>
    

    I also tried to use sleep(); but i had the same results.

     

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.