Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have tried everything i found on net and none seem to work and ive been on this for past 2 weeks. i want to be able to upload image file along with other form data and insert or update my sql DB. the list and delete works fine while create and update shows an error that says Error communicating with server.

What I have tried:

 	<script type="text/javascript">
    
 // Read a page GET URL variables and return them as an associative array.
function getVars(url)
{
    var formData = new FormData();
    var split;
    $.each(url.split("&"), function(key, value) {
        split = value.split("=");
        formData.append(split[0], decodeURIComponent(split[1].replace(/\+/g, " ")));
    });

    return formData;
}

// Variable to store your files
var files;

$( document ).delegate('#userfile','change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
    files = event.target.files;
}

//The actions for your table:   
    
    
        var baseurl = "http://localhost/agbookshop/";
		$(document).ready(function () {

		    //Prepare jTable
			$('#AuthorTableContainer').jtable({
                title: 'Table of Authors',
                selecting:true,
                paging:true,
                sorting:true,
                defaultSorting: 'lnam DESC',
                pageSize:6,
            actions: {
            // simple ajax call to get the list of users
                     listAction: 'actions/authoreditaction.php?action=list',
                     deleteAction: 'actions/authoreditaction.php?action=delete',
                updateAction: function (postData) {
                    var formData = getVars(postData);

                    if($('#userfile').val() !== ""){
                        formData.append("userfile", $('#userfile').get(0).files[0]);
                    }

                    return $.Deferred(function ($dfd) {
                        $.ajax({
                            url: 'actions/updateauthor',
                            type: 'POST',
                            dataType: 'json',
                            data: formData,
                            processData: false, // Don't process the files
                            contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                            success: function (data) {
                                $dfd.resolve(data);
                                $('#AuthorTableContainer').jtable('load');
                            },
                            error: function () {
                                $dfd.reject();
                            }
                        });
                    });
                },
                createAction: function (postData) {
                    var formData = getVars(postData);

                    if($('#userfile').val() !== ""){
                        formData.append("userfile", $('#userfile').get(0).files[0]);
                    }

                    return $.Deferred(function ($dfd) {
                        $.ajax({
                            url: 'actions/authoreditaction.php?action=create',
                            type: 'POST',
                            dataType: 'json',
                            data: formData,
                            processData: false, // Don't process the files
                            contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                            success: function (data) {
                                $dfd.resolve(data);
                                $('#AuthorTableContainer').jtable('load');
                            },
                            error: function () {
                                $dfd.reject();
                            }
                        });
                    });
                }
                    },                  
                fields: {
					authid: {
						key: true,
						create: false,
						edit: false,
						list: false
					},
					fnam: {
						title: 'FIRST NAME',
						width: '8%'
					},
					lnam: {
						title: 'LAST NAME',
						width: '8%'
					},
                imgpath: {
                    title: 'AUTHOR PHOTO',
                    type: 'file',
                    create: false,
                    edit: true,
                    list: true,
                    display: function(data){
                        return '<img src="' + data.record.imgpath +  '" width="80" class="preview">';
                    },
                    input: function(data){
                        return '<img src="' + data.record.imgpath +  '" width="80" class="preview">';

                    },
                    width: "8%",
                    listClass: "class-row-center"
                },
                    image: {
                        title: 'Select Author Photo',
                        list: false,
                        create: true,
                        input: function(data) {
                            html = '<input type ="file" id="userfile" name="userfile" accept="image/*" />';
                            return html;
                        }
                    },
				addr: {
						title: 'ADDRESS',
                        type: 'textarea',
						width: '6%'
					},
					phone: {
						title: 'PHONE',
						width: '7%'
					},
					fbook: {
						title: 'FACEBOOK',
						width: '7%'
					},
					twitter: {
						title: 'TWITTER',
						width: '8%'
					},
					emails: {
						title: 'EMAIL',
						width: '7%'
					},
					aboutauthor: {
						title: 'ABOUT AUTHOR',
                        type: 'textarea',
						width: '7%'
					}
				}
			});
            
                           //Re-load records when user click 'load records' button.
                $('#LoadRecordsButton').click(function (e) {
                    e.preventDefault();
                    $('#AuthorTableContainer').jtable('load', {
                        fnam: $('#fnam').val(),
                        lnam: $('#lnam').val()
                    });
                });

			//Load person list from server
			$('#AuthorTableContainer').jtable('load');
		});


	</script>
Here's my PHP UPDATE script

 //Update record in database
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){

            $target_file=$target_dir.basename($_FILES["userfile"]["name"]);
            $imageFileType =strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
            $db_targpath='authors/'.$target_file;
            $target_file = '../authors/'.$target_file;
         //$maxFileSize = 5 * 1024 * 1024; 5mb
         //    $maxFileSize = 25 * 1024 ; 25kb
    
          //Check if file already exists, then delete it
        if (file_exists($target_file)) {
           unlink($target_file);
        }
    if($_FILES['fileUpload']['size'] > $maxFileSize){
        $errors = 'File size is greater than allowed size';
    }
        
        if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $target_file)) {
 //            echo 'File is uploaded successfully.';

 //     Handle other code here
}
  }	      
                     
    $fn=Validate($_POST["fnam"]);    
    $ln=Validate($_POST["lnam"]);    
    $addr=Validate($_POST["addr"]);    
    $phn=Validate($_POST["phone"]);    
    $fb=Validate($_POST["fbook"]);    
    $twt=Validate($_POST["twitter"]);    
    $em=Validate($_POST["emails"]);    
    $abta=Validate($_POST["aboutauthor"]);    
        
          $sql="UPDATE authors SET fnam='".$fn . "', lnam ='".$ln."', addr='".$addr."', phone='".$phn."', fbook='".$fb."', twitter='".$twt."', emails='".$em."', aboutauthor='".$abta."' WHERE authid=".$_POST["authid"];
                   
        $DB->exec($sql);

		//Return result to jTable
		$jTableResult = array();
		$jTableResult['Result'] = "OK";
		print json_encode($jTableResult);
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900