Tuesday 28 January 2014

Custom AJAX File Uploader

I am very happy to share custom AJAX file up loader. It is very simple and using basic codes. So you can easily understand my code.

How to integrate this code ?


1. First you create index file, index.php


<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<form id="myUploadForm" name="myUploadForm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file[]" id="fileUpload" multiple="multiple" />
<input type="hidden" name="uploadedFilename" id="uploadedFilename" value="" />
</form>
<ul id="filelist">

</ul>
<script type="text/javascript">
$(function() {

    $(".removeUploadedFile").live('click',function() {
        var sel = $(this);
        if(!confirm("Do you want to remove this file ?")) return false;
        $.post('request.php',{action: 'remove', file: sel.attr('rel')}, function(data){
            if(data>0) {
                sel.closest('li').remove();
            }
        });
    });


    $("#fileUpload").change(function (e) {
            var sel = $(this);
            $.map($('#fileUpload').get(0).files, function(file) {
                $("#uploadedFilename").val(file.name);
                     e.preventDefault();
                    var formData = new FormData(sel.parents('form')[0]);
           
                    $.ajax({
                        url: 'request.php',
                        type: 'POST',
                        xhr: function() {
                            var myXhr = $.ajaxSettings.xhr();
                            return myXhr;
                        },
                        success: function (data) {
                            $("#filelist").append(data);
                            $("#fileUpload").val('');
                        },
                        data: formData,
                        cache: false,
                        contentType: false,
                        processData: false
                    });
                    return false;
            }); 
     });
});
</script>


2. Create another file request.php for AJAX call, request.php


<?php

switch ($_REQUEST['action']) {

        case 'upload':
        $targetPath = "uploads/";
        for($i=0; $i<count($_FILES['file']['name']); $i++){
               
                $tempFile =   $_FILES['file']['name'][$i];
                if($tempFile == $_REQUEST['uploadedFilename']){
                    //$targetFile =  str_replace('//','/', $targetPath) . $newFileName;
                    $cpy=0;
                    do {
                       
                        if($cpy>0)
                        $fileName="Copy".$cpy.$tempFile;
                        else $fileName=$tempFile;
                        $targetFile =  str_replace('//','/',$targetPath) .$fileName;
                        $cpy++;
                    }while(is_file($targetFile));
                       
                    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $targetFile)) {
                        echo "<li>".$fileName."&nbsp;&nbsp;<a href='#NOD' class='removeUploadedFile' rel='".$fileName."'>Remove</a><input type='hidden' name='hdnAttach[]' value='".$fileName."' ></li>";
                    } else{
                        echo "<li>There was an error uploading the file(".$fileName."), please try again! </li>";
                    }
                   
                }
               
        }
        break;
       
        case 'remove':
            if(file_exists("uploads/".$_POST['file'])) {
                unlink("uploads/".$_POST['file']);
                    echo 1;
                }
        break;

}

?>

3. Create a folder 'uploads' for upload image.The uploaded image should be stored in this folder.

 

 

Root Path :



Monday 13 January 2014

Simple file uploader (Php File Uploader)


I found a website phpfileuploader.com, they provide simple code for file uploading.We can upload multiple files also.I used plupuploader for file uploading before. When I checked their code, I moved this uploading techniques.

It is very simple,easy to understand and easy to integrate. They provide demo development code and we can start the development with this code.

Monday 6 January 2014

HTC Desire C shows error like no images and videos available

My phone is HTC Desire C.Two days ago I couldn't open my gallery.When I try to open gallery It shows error like no images and videos available.I thought it is because of virus.I restarted my mobile, removed my SD/memory card. But the result is still same.

I googled this error and finally I found a link.

From the above link instruction I went to setting>>Apps>>Running.

I couldn't find out the mediascanner service, I realized that It was my mistake, because suddenly I closed media services using task manager.It killed my media services.

Then I changed the setting like setting>>Apps>>All>>Media

I opened the above root, I found that media app is disabled. I enable its services and solved my problem.

Thursday 2 January 2014

Create MYSQL Table From CSV File Using PHP

The below example shows how to create MYSQL table from CSV file using PHP code.
For reference: Click Here

<?php

 //table Name
$tableName = "MyTable";
//database name
$dbName = "MyDatabase";


 $conn = mysql_connect("localhost", "root", "") or die(mysql_error());
 mysql_select_db($dbName) or die(mysql_error());

//get the first row fields
$fields = "";
$fieldsInsert = "";
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    if(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $fieldsInsert .= '(';
        for ($c=0; $c < $num; $c++) {
            $fieldsInsert .=($c==0) ? '' : ', ';
            $fieldsInsert .="`".$data[$c]."`";
            $fields .="`".$data[$c]."` varchar(500) DEFAULT NULL,";
        }
       
        $fieldsInsert .= ')';
    }
   

    //drop table if exist
    if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))>=1) {
      mysql_query('DROP TABLE IF EXISTS `'.$tableName.'`') or die(mysql_error());
    }
   
    //create table
    $sql = "CREATE TABLE `".$tableName."` (
              `".$tableName."Id` int(100) unsigned NOT NULL AUTO_INCREMENT,
              ".$fields."
              PRIMARY KEY (`".$tableName."Id`)
            ) ";
   
    $retval = mysql_query( $sql, $conn );
   
    if(! $retval )
    {
      die('Could not create table: ' . mysql_error());
    }
    else {
        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
           
                $num = count($data);
                $fieldsInsertvalues="";
                //get field values of each row
                for ($c=0; $c < $num; $c++) {
                    $fieldsInsertvalues .=($c==0) ? '(' : ', ';
                    $fieldsInsertvalues .="'".$data[$c]."'";
                }
                $fieldsInsertvalues .= ')';
                //insert the values to table
                $sql = "INSERT INTO ".$tableName." ".$fieldsInsert."  VALUES  ".$fieldsInsertvalues;
                mysql_query($sql,$conn);   
        }
        echo 'Table Created';   
    }
   
    fclose($handle);
       
}


?>

If you have any questions, please post it as comments.

Wednesday 1 January 2014

Create XML file and add/cascade css using php

The below example shows how to create a XML file using php and also shows how to add css on it.Here we are using "simplexml" php function. For more details, click here.

create a php file (index.php) and copy & past the below code

################### Start PHP Code #####################

<?php


class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addMyCss( $name, $value )
    {
        $dom_sxe = dom_import_simplexml($this);      
        $dom_parent = $dom_sxe->ownerDocument;      
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}


$xml = new SimpleXMLElement_Plus('<xml/>');
$xml->addMyCss('xml-stylesheet', 'type="text/css" href="cd_catalog.css"');
$track = $xml->addChild('markers');
for ($i = 1; $i <= 8; ++$i) {
    $marker = $xml->addChild('marker');
    $marker->addChild('name', "name$i");
    $marker->addChild('address', "address $i");
    $marker->addChild('lat', "lat $i");
    $marker->addChild('lng', "lng $i");
}

Header('Content-type: text/xml');
print($xml->asXML());

?>

################### End PHP Code #####################


Create a CSS file(cd_catalog.css) and copy and past the below code.


######################### Start CSS  ##################

markers
{
margin:10px;
background-color:#ccff00;
font-family:verdana,helvetica,sans-serif;
}

name
{
display:block;
font-weight:bold;
}

address, lat, lng
{
display:block;
color:#636363;
font-size:small;
font-style:italic;
}

########################## End CSS  ##################

If you have any questions, please post it as comments.