How to send file information when uploading img via ajax

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 586 Views - Last Post: 09 May 2019 - 03:05 PM Rate Topic: -----

#1 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

How to send file information when uploading img via ajax

Posted 06 May 2019 - 08:45 AM

am attempting to split up image file uploading to an ajax method. All of the html and JS is in one file and then I made up a PHP file that contains all of the PHP.

What I am struggling with is I am not sure how to send the image file info over to the php file and then for the rest of the php to work as it used to.

As of now, this line of code $p_img = $_POST['file']; is getting an undefined index error. However, even if that is populating, I am not sure if this will work correctly with the files being seperated.

Is there anyway that I can leave my first PHP function, UploadFile in the file with the HTML and JS and then send the function over to the PHP file?


If not, what can I do?

None of my catch PDO exceptions are reporting errors. I also am trying to put the errors into error logs, and nothing is being outputted, so I'm not sure what is wrong.


HTML

<form action="" method="POST" id="projectForm" enctype="multipart/form-data">
    <label>Project Name</label>
    <input type="text" class="input block" name="p_name">
    <label>Project Img</label>
    <input type="file" id="file" name="file" class="file-input block">
    <button id="submit">Submit Project</button>
</form>


JS

$('#projectForm').validate({
        ignore: [],
        rules: {
            p_name: {
                required: true,
                minlength: 5
            },
            p_alt: {
                required: true,
                minlength: 2
            }
        },
        messages: {
            p_name: {
                required: "Please enter the project name",
                minlength: "The project name is too short"
            },
            p_alt: {
                required: "Please enter the alt text",
                minlength: "Your alt text is too short"
            }
        },
        submitHandler: function (form, e) {
            e.preventDefault();
            var formData = new FormData(form);
            category = $(this).data('category');

            console.log(category);

            $.ajax({
                url: '/php/projectSend.php',
                type: 'POST',
                data: formData,
                success: function (data) {
                  console.log(data);
                },
                contentType: false,
                processData: false,
                error: function (xhr, textStatus, errorThrown) {
                    alert(textStatus + " | " + errorThrown);
                    alert('There are currently no project images for this selection');
                }
            });
        }
    });


PHP

ini_set('display_errors', 1);
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');

$p_name = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$p_img = $_POST['file'];
$p_alt = trim(htmlspecialchars($_POST['p_alt']));
$category = trim(htmlspecialchars($_POST['categoryName']));
$creator = trim(htmlspecialchars($_POST['creatorName']));
$status = $_POST['status'];

    function UploadFile($fileArray = array(), $destinationFolder = '../project_images/') {
        $filename       =   $fileArray['file']['name'];
        $tmp_name       =   $fileArray['file']['tmp_name'];
        $filesize       =   $fileArray['file']['size'];
        $file_error     =   $fileArray['file']['error'];
        $file           =   $fileArray['file'];
        // Save all the default data.
        $return['error']        =   true;
        $return['success']      =   false;
        $return['file']['dest'] =   $destinationFolder.$filename;
        $return['file']['size'] =   $filesize;

        if($file_error == 0)
            $return['error']    =   false;
        if(!is_dir($destinationFolder))
            mkdir($destinationFolder,0755,true);
        // If your filename is not empty, return success or fail of upload
        if (!empty($filename))
            $return['success']  = (move_uploaded_file($tmp_name, $destinationFolder.$filename));

        return $return;
    }

try {
    $con = getConfig('pdo');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    function SaveToDb($con,$filename = false) {
        // Return fail immediately if the connection is false or image is invalid
        if(empty($filename) || !$con)
            return false;
        $project_sql = "
            INSERT INTO quotes
            (p_name, p_img, p_alt, category, creator, status, date_added)
            VALUES(?, ?, ?, ?, ?, ?, NOW())
        ";
        if ($project_stmt = $con->prepare($project_sql)) {
            $project_stmt->execute(array($p_name, $p_img, $p_alt, $category, $creator, $status));
            return true;
            $proj_succ = "Success";
            echo json_encode($proj_succ);
        }
        return false;
    }
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

    if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success']) {
            echo '<h3>Sorry, an error occurred</h3>';
        }
        else {

            // Try to save it
            $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
            // Get the profile from image name
            $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;   
        }
    }


Is This A Good Question/Topic? 0
  • +

Replies To: How to send file information when uploading img via ajax

#2 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4227
  • View blog
  • Posts: 13,399
  • Joined: 08-June 10

Re: How to send file information when uploading img via ajax

Posted 06 May 2019 - 09:11 AM

Quote

As of now, this line of code $p_img = $_POST['file']; is getting an undefined index error.

That's because files end up in the $_FILES array.
Was This Post Helpful? 0
  • +
  • -

#3 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 06 May 2019 - 09:16 AM

I actually noticed that and changed that line of code to:

$p_img = $_FILES['file'];


Still nothing is working. The file is not sending to the specified folder, my query is not sending to the db and the error files are not generating. Nothing is showing up in the response tab of the console either.
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4227
  • View blog
  • Posts: 13,399
  • Joined: 08-June 10

Re: How to send file information when uploading img via ajax

Posted 06 May 2019 - 09:51 AM

Quote

Still nothing is working.

Then you should check your error messages.

Quote

my query is not sending to the db

That's an obvious one since the variables you use are out of scope.

Quote

Nothing is showing up in the response tab

Then you have to step through your code and explicitly check where something goes wrong.

This post has been edited by Dormilich: 06 May 2019 - 09:51 AM

Was This Post Helpful? 0
  • +
  • -

#5 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 06 May 2019 - 10:26 AM

I'm not getting any error messages anywhere though. I built in and extra try/catch and added in the file_put_contents so that the specific error per section would go to a different log file. No file is generating. No error messages are generating. There is nothing in the console stating an error. I'm not sure how else I could debug if nothing is reporting.
Was This Post Helpful? 0
  • +
  • -

#6 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 06 May 2019 - 10:34 AM

I just wrapped another try/catch around the variable section, too. It still didn't create an error file.

try {
$p_name = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$p_img = $_FILES['file'];
$p_alt = trim(htmlspecialchars($_POST['p_alt']));
$category = trim(htmlspecialchars($_POST['categoryName']));
$creator = trim(htmlspecialchars($_POST['creatorName']));
$status = $_POST['status'];
} catch (PDOException $e) {
    echo "Variable sending failed " . $e->getMessage();
	file_put_contents('error_log_var', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
}

Was This Post Helpful? 0
  • +
  • -

#7 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2287
  • View blog
  • Posts: 6,978
  • Joined: 15-January 14

Re: How to send file information when uploading img via ajax

Posted 06 May 2019 - 01:30 PM

You're telling it to catch a PDOException from a bunch of code that will never throw a PDOException. A regular PHP error does not cause an exception to be thrown that you can catch, most built-in functions do not throw exceptions. The PDO class does if you set it to throw exceptions when there's an error.

What exactly happens when you run this? What is the output?
Was This Post Helpful? 0
  • +
  • -

#8 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 07 May 2019 - 06:40 AM

Thanks for the info. I didn't know that was the case. Well no errors are being sent to the standard error file that normal php function errors are sent to.

Nothing happens when I run this. I'm not getting any output. I am just trying to insert the fields into the db and get the image to upload into the folder.
Was This Post Helpful? 0
  • +
  • -

#9 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 07 May 2019 - 09:09 AM

If I do
var_dump($p_img);
... I get the following output in the response:

array(5) {
  ["name"]=>
  string(13) "capColor2.PNG"
  ["type"]=>
  string(9) "image/png"
  ["tmp_name"]=>
  string(14) "/tmp/phpz5BTml"
  ["error"]=>
  int(0)
  ["size"]=>
  int(169768)
}

Was This Post Helpful? 0
  • +
  • -

#10 Dormilich   User is offline

  • 痛覚残留
  • member icon

Reputation: 4227
  • View blog
  • Posts: 13,399
  • Joined: 08-June 10

Re: How to send file information when uploading img via ajax

Posted 07 May 2019 - 09:24 AM

As mentioned in post #4 your problem lies with the SaveToDb() function.
Was This Post Helpful? 0
  • +
  • -

#11 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 07 May 2019 - 09:38 AM

I agree the issue lies within the saveToDb function. However, I don't think that is the root of it.

My file function is not performing correctly. Whenever I do var_dump's on any of the arrays, I get nothing in response.

I'm not sure how to combine the
$p_img = $_FILES['file'];


into the $fileArray.

For instance, if I do this:

var_dump($p_img['name']);

I get the correct file name.

However, with $fileArray already being an array, I'm not sure how to add in the $p_img. I know the following is wrong, but I don't know how else to do it.

$filename = $fileArray[$p_img]['name'];

Was This Post Helpful? 0
  • +
  • -

#12 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2287
  • View blog
  • Posts: 6,978
  • Joined: 15-January 14

Re: How to send file information when uploading img via ajax

Posted 07 May 2019 - 10:53 AM

Why aren't you seeing the error messages about undefined variables? Are you looking in the right place? Add this to the top of your code to check:

ini_set('display_errors', 1);

Was This Post Helpful? 0
  • +
  • -

#13 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 07 May 2019 - 11:23 AM

I'm not sure why there aren't any error messages being put into the error_log file. There was initially when I had $_POST['file'];. Since I changed that, nothing has been inserted into the error_log file.

I have the ini_set code at the top of my file.

I have the following:

ini_set('display_errors', 1);
error_reporting(E_ALL);


Was This Post Helpful? 0
  • +
  • -

#14 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2287
  • View blog
  • Posts: 6,978
  • Joined: 15-January 14

Re: How to send file information when uploading img via ajax

Posted 07 May 2019 - 12:56 PM

It sounds like your save function is not running then, or not getting to line 49 in the code you posted here, because that line should launch several undefined variable warnings.
Was This Post Helpful? 0
  • +
  • -

#15 pfar54   User is offline

  • D.I.C Addict

Reputation: 0
  • View blog
  • Posts: 519
  • Joined: 30-April 15

Re: How to send file information when uploading img via ajax

Posted 09 May 2019 - 06:31 AM

I agree that it isn't reaching that point. I don't know how else to debug this situation.

Here is my new PHP code:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');

$p_name = trim(htmlspecialchars($_POST['p_name'], ENT_QUOTES));
$p_alt = trim(htmlspecialchars($_POST['p_alt']));
$category = trim(htmlspecialchars($_POST['categoryName']));
$creator = trim(htmlspecialchars($_POST['creatorName']));
$status = $_POST['status'];
//var_dump($p_img);


	function UploadFile($fileArray, $destinationFolder = '../project_images/') {
		//$p_img = $fileArray['file'];

		$fileUploadData = $fileArray['file'];
		var_dump($fileUploadData);
		$filename       =   $fileUploadData['name'];
		$tmp_name       =   $fileUploadData['tmp_name'];
		$filesize       =   $fileUploadData['size'];
		$file_error     =   $fileUploadData['error'];
       /* $filename       =   $fileArray['file']['name'];
	    $tmp_name       =   $fileArray['file']['tmp_name'];
        $filesize       =   $fileArray['file']['size'];
        $file_error     =   $fileArray['file']['error'];
        $file           =   $fileArray['file'];*/
		
		/*
		$filename       =   $fileArray[$fileNameVar];
        $tmp_name       =   $fileArray[$fileTmpNameVar];
        $filesize       =   $fileArray[$fileSizeVar];
        $file_error     =   $fileArray[$fileErrorVar];
        $file           =   $fileArray[$p_img];
*/
		var_dump($filename);
        // Save all the default data.
        // Success and error should be set by default to fail
        $return['error']        =   true;
        $return['success']      =   false;
        $return['file']['dest'] =   $destinationFolder.$filename;
        $return['file']['size'] =   $filesize;

        if($file_error == 0)
            $return['error']    =   false;
        // I added a directory creation function so you don't have to 
        // manually make folders. This will do it for you.
        if(!is_dir($destinationFolder))
            mkdir($destinationFolder,0755,true);
        // If your filename is not empty, return success or fail of upload
        if (!empty($filename))
            $return['success']  = (move_uploaded_file($tmp_name, $destinationFolder.$filename));

        return $return;
    }

try {
    $con = getConfig('pdo');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Create a save-to-database function so it's easier and reusable
	function SaveToDb($con,$filename = false) {
        // Return fail immediately if the connection is false or image is invalid
        if(empty($filename) || !$con)
            return false;
		$project_sql = "
			INSERT INTO quotes
			(p_name, p_img, p_alt, category, creator, status, date_added)
			VALUES(?, ?, ?, ?, ?, ?, NOW())
		";
		if ($project_stmt = $con->prepare($project_sql)) {
			$project_stmt->execute(array($p_name, $p_img, $p_alt, $category, $creator, $status));
			return true;
			$proj_succ = "Success";
			echo json_encode($proj_succ);
		}
		return false;
	}
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
	file_put_contents('error_log_new', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: \n" . print_r($e, 1), FILE_APPEND);
}

	if(isset($_POST['create'])) {
        // Try uploading
        $upload =   UploadFile($_FILES);
        // If upload fails
        if(!$upload['success']) {
            echo '<h3>Sorry, an error occurred</h3>';
		}
        else {
            // You could add error handling here based on the results of 
            // each function's success or failure below.

            // Try to save it
            $saveToDb   =   SaveToDb($con,$upload['file']['dest']);
            // Get the profile from image name
            $profPic    =   ($saveToDb)? getPhoto($con,$upload['file']['dest']) : false;   
        }
    }

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2