-1

I have this php webpage that uploads a cvs file to my postgres DB. It works fine enough, but, I'd like to turn this php webpage into an HTMl page with an ajax call to a separate php script. What's the best method for achieving this goal without additional external resources?

Here's my code.

<?php
$db = "postgres";
$host = "localhost";
$port = "5432";
$user = "xxxx";
$password = "xxxx";
$timeout = "5";
$table = "my_table";
$dbconn = pg_connect("host = $host port = $port dbname = $db user = $user password = $password connect_timeout = $timeout ")
        or die("Could not connect:" . pg_last_error());


pg_query("TRUNCATE TABLE $table");
if ($_FILES[csv][size] > 0) {

    //get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file, "r");

    //loop through the csv file and insert into database
    do {
        if ($data[0]) {
            $queryA = "INSERT INTO $table (usb_number, affiliation, type_company, status,  region,  company_name,  full_address,  street_number,  city,  state,  county,  zip_code,  cs_account,  cs_store_number,  c_type,  fully_verified,  expiring_soon,  phone_number, latitude, longitude) VALUES
        ( 
                    '" . addslashes($data[0]) . "', 
                    '" . addslashes($data[1]) . "', 
                    '" . addslashes($data[2]) . "',
                    '" . addslashes($data[3]) . "', 
                    '" . addslashes($data[4]) . "', 
                    '" . addslashes($data[5]) . "', 
                    '" . addslashes($data[6]) . "', 
                    '" . addslashes($data[7]) . "', 
                    '" . addslashes($data[8]) . "', 
                    '" . addslashes($data[9]) . "', 
                    '" . addslashes($data[10]) . "', 
                    '" . addslashes($data[11]) . "', 
                    '" . addslashes($data[12]) . "', 
                    '" . addslashes($data[13]) . "', 
                    '" . addslashes($data[14]) . "', 
                    '" . addslashes($data[15]) . "', 
                    '" . addslashes($data[16]) . "', 
                    '" . addslashes($data[17]) . "',
                    '" . addslashes($data[18]) . "',
                    '" . addslashes($data[19]) . "'
                ) 
            ";
            $resultA = pg_query($queryA);
        }
    } while ($data = fgetcsv($handle, 1000, ","));
    // 
    pg_query("UPDATE $table SET
  geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)");

    if(!$resultA){
        $errrormessage = pg_last_error();
        echo "Error with query: ".$errormessage;
        exit();
    }

    echo "Table updated!";
    //redirect 
//    header('Location: import.php?success=1');
    die;
}
?> 


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
        <title>Import a CSV File with PHP & Postgres</title> 
        <link href="../lib/css/datatables.min.css" rel="stylesheet" type="text/css"/>
        <link href="../lib/font-awesome-4.4.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
        <link href="../lib/js/bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
        <script src="../lib/js/jquery-2.1.4.js" type="text/javascript"></script>
        <script src="../lib/js/jquery-ui-1.11.4/jquery-ui.min.js" type="text/javascript"></script>
        <script src="../lib/js/bootstrap-3.3.5-dist/js/bootstrap.min.js" type="text/javascript"></script>
        <script src="../lib/js/datatables.min.js" type="text/javascript"></script>
        <style>
            .btn-file {
                position: relative;
                overflow: hidden;
                height: 35px;
            }
            .btn-file input[type=file] {
                position: absolute;
                top: 0;
                right: 0;
                min-width: 100%;
                min-height: 100%;
                font-size: 100px;
                text-align: right;
                filter: alpha(opacity=0);
                opacity: 0;
                outline: none;
                background: white;
                cursor: inherit;
                display: block;
            }
            fieldset {
                -webkit-border-radius: 8px;
                -moz-border-radius: 8px;
                border-radius: 8px;
            }
        </style>
    </head> 
      <?php
     $resultA;
//        ?> 
    <body> 
        <div class="col-lg-12">
            <br/><br/>
            <div class="col-lg-3">
                <form class="form-inline" role="form" action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
                    <fieldset>
                        <legend>Update Client Table</legend>
                        <span class="btn btn-md btn-default  btn-file">
                            <i class="fa fa-search"></i>  Browse <input name="csv" type="file" id="csv" /> 
                        </span>
                        <!--input name="csv" type="file" id="csv" /--> 
                        <button class="form-control btn btn-md btn-primary" type="submit" name="Submit" value="Submit">Submit</button> 
                    </fieldset>
                </form>
            </div>
        </div>
    </body> 
</html> 
Dean
  • 209
  • 2
  • 14

1 Answers1

1

You need to do an ajax upload such as the one in this question here How can I upload files asynchronously?

First Make an ajax post on button click:

  <form class="form-inline" role="form" action="" method="post" enctype="multipart/form-data" name="form1" id="form1"> 
    <fieldset>
        <legend>Update Client Table</legend>
        <span class="btn btn-md btn-default  btn-file">
            <i class="fa fa-search"></i>  Browse <input name="csv" type="file" id="csv" /> 
        </span>
        <!--input name="csv" type="file" id="csv" /--> 
        <button class="form-control btn btn-md btn-primary" type="submit" name="Submit" value="Submit">Submit</button> 
    </fieldset>
</form>
<script>
$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'upload.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: function(retdata){
            alert(retdata); // This will be the echo from the php script
        }
        error: function(){
            alert('Error!');
        },
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});
</script>

Then in your upload.php do all that stuff you were doing with the postgres etc. Make sure you echo a response before exit/die so your Javascript complete function will have an idea as to what happened!

<?php
$db = "postgres";
$host = "localhost";
$port = "5432";
$user = "xxxx";
$password = "xxxx";
$timeout = "5";
$table = "my_table";
$dbconn = pg_connect("host = $host port = $port dbname = $db user = $user password = $password connect_timeout = $timeout ")
        or die("Could not connect:" . pg_last_error());


pg_query("TRUNCATE TABLE $table");
if ($_FILES[csv][size] > 0) {

    //get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file, "r");

    //loop through the csv file and insert into database
    do {
        if ($data[0]) {
            $queryA = "INSERT INTO $table (usb_number, affiliation, type_company, status,  region,  company_name,  full_address,  street_number,  city,  state,  county,  zip_code,  cs_account,  cs_store_number,  c_type,  fully_verified,  expiring_soon,  phone_number, latitude, longitude) VALUES
        ( 
                    '" . addslashes($data[0]) . "', 
                    '" . addslashes($data[1]) . "', 
                    '" . addslashes($data[2]) . "',
                    '" . addslashes($data[3]) . "', 
                    '" . addslashes($data[4]) . "', 
                    '" . addslashes($data[5]) . "', 
                    '" . addslashes($data[6]) . "', 
                    '" . addslashes($data[7]) . "', 
                    '" . addslashes($data[8]) . "', 
                    '" . addslashes($data[9]) . "', 
                    '" . addslashes($data[10]) . "', 
                    '" . addslashes($data[11]) . "', 
                    '" . addslashes($data[12]) . "', 
                    '" . addslashes($data[13]) . "', 
                    '" . addslashes($data[14]) . "', 
                    '" . addslashes($data[15]) . "', 
                    '" . addslashes($data[16]) . "', 
                    '" . addslashes($data[17]) . "',
                    '" . addslashes($data[18]) . "',
                    '" . addslashes($data[19]) . "'
                ) 
            ";
            $resultA = pg_query($queryA);
        }
    } while ($data = fgetcsv($handle, 1000, ","));
    // 
    pg_query("UPDATE $table SET
  geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)");

    if(!$resultA){
        $errrormessage = pg_last_error();
        echo "Error with query: ".$errormessage;
        exit();
    }

    echo "Table updated!";
    die;
}
?> 
Community
  • 1
  • 1
Chizzle
  • 1,677
  • 1
  • 17
  • 26
  • beforeSend references "beforeSendHandler". where is that function? – Dean Nov 06 '15 at 13:48
  • You can omit that. It's just a place where you can run some code if you want to do something immediately before the request is posted. – Chizzle Nov 06 '15 at 15:40