AJAX, JSON, and PHP - Uncaught SyntaxError: Unexpected token < - php

So I am using AJAX to upload an image with this image manager tool I am building... all of a sudden its not working... I didn't change any code or anything.
The .php runs and uploads the image, but the events I want to fire after the json is encoded and sent back arent happening. :/
The console logs Uncaught SyntaxError: Unexpected token <
The same things is happening on another AJAX request, but is fine on the third one...
In the past when I get this error, it is a PHP syntax error, but I have not updated the .php in a while.. soooo Im stumped.
Here is my Javascript:
$("#chosenfile").change(function(){
if($(this).attr('name')) {
var data;
data = new FormData();
data.append('uploadedfile', $( '#chosenfile' )[0].files[0]);
$('#loader').css('display','block');
$.ajax({
url: '/includes/uploadimage.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function ( data ) {
//console.log(data); //returns a string of the data.
var image = JSON.parse(data); //parses the string into an object.
console.log(image); //logs the object.
if (image.error) {
alert(image.error);
$('#remove').click();
$('#loader').css('display','none');
} else {
if (image.link) { //If the image is uploaded and returned a link.
$('#remove').click();
$('#loader').css('display','none');
$('#scrollwindow').append("<div class='you'><img imgid='" + image.id + "' src='" + image.link + "' alt=''><span class='delete'>x</span></div>").fadeIn(200);
addToSlider(1);
};
}
}
});
}
});
Here is my PHP:
<?php
include '../includes/global.php'; // General Vars and Functions I use sitewide.
/* ------------------------- */
/* -- Lets Get that file! -- */
/* ------------------------- */
$file = $_FILES["uploadedfile"];
$Return = array();
$status = "failure";
/* ------------------------- */
/* - Okay, lets upload it! - */
/* ------------------------- */
$Return["type"] = $file["type"];
$target_path = "../uploads/"; // Define a folder to upload to
$allowedExts = array("jpeg", "jpg", "JPG", "JPEG", "image/jpg"); // Array of allowed extensions.
$extension = end(explode("/", $file["type"])); // Find extension.
$maxsize = 2097152; // Get Max file size from hidden field in form.
if ($file) {
if (in_array($extension, $allowedExts)) // If the extension is allowed.
{
if(($file["size"] < $maxsize)) { // If size is less then max file size.
$uploadResponse = "The file is a good size - ";
$target_path = $target_path . basename($file['name']); //Add file name string to upload folder destination string.
$imageLink = "http://scoutsamerica.com/uploads/" . basename( $file['name']); // This is the full link
if (file_exists($target_path)) { // If that file already exists, add a random integer to the end of it after a "_".
$uploadResponse .= "This file exists: " . $target_path;
$randomNum = rand(1, 9999999);
$crudparts = explode(".", $file["name"]); //split filename and extension again.
$exceptExt = $crudparts[0]; //Filename
$extension = $crudparts[1]; //Extension
$target_path = "../uploads/" . $exceptExt . "_" . $randomNum . "." . $extension; //rename it with the random number.
$imageLink = "http://scoutsamerica.com/uploads/" . $exceptExt . "_" . $randomNum . "." . $extension;
$uploadResponse .= " Path changed to: " . $target_path;
}
if(move_uploaded_file($file['tmp_name'], $target_path)) {
$uploadResponse .= "The file ". basename( $file['name']) . " has been uploaded to " . $target_path . "</br></br>";
} else {
$uploadResponse .= "There was an error uploading the file, please try again! </br>";
$uploadResponse .= "File size: " . ($file["size"] / 1024) . "kb</br>";
$uploadResponse .= "Max size: " . ($maxsize / 1024) . "kb";
}
$status = "success";
$Return["link"] = $imageLink;
/* ---------------------------------- */
/* - Time to upload that image, yo. - */
/* ---------------------------------- */
$imageSql = "INSERT INTO images (id, link, model_id, addedon) VALUES (".
"null, " .
PrepSQL($imageLink) . ", " .
PrepSQL($myId) . ", " .
PrepSQL($date) . ")";
mysql_query($imageSql) or die("Images: " . mysql_error());
} else {
$uploadResponse = "The file must less then " . ($maxsize / 1024) . "kb.";
$status = "failure";
$Return["error"] = $uploadResponse;
}
} else {
$uploadResponse = "The file must be a .jpg file.";
$status = "failure";
$Return["error"] = $uploadResponse;
}
} else {
$uploadResponse = "No Image.";
$status = "failure";
$Return["error"] = $uploadResponse;
}
/* ------------------------- */
/* - Lets Send it back :) - */
/* ------------------------- */
$Return["status"] = $status;
$Return["id"] = mysql_insert_id();
$Return["traveler"] = $file;
str_replace('\\/', '/', json_encode($Return));
echo json_encode($Return);
?>
RAW Response:
<script>
function hairEyesFind(haireyes){
if (haireyes == "blonde") {
return "z";
};
if (haireyes == "dirty blonde") {
return "b";
};
if (haireyes == "auburn") {
return "c";
};
if (haireyes == "brown") {
return "d";
};
if (haireyes == "black") {
return "e";
};
if (haireyes == "red") {
return "f";
};
if (haireyes == "blue2") {
return "g";
};
if (haireyes == "green2") {
return "h";
};
if (haireyes == "hazel2") {
return "i";
};
if (haireyes == "brown2") {
return "j";
};
}
</script>{"type":"image\/jpeg","link":"http:\/\/scoutsamerica.com\/uploads\/485604_10201093620571706_1239548317_n_5119195.jpg","status":"success","id":281,"traveler":{"name":"485604_10201093620571706_1239548317_n.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpX1qywo","error":0,"size":60368}}

unexpected token probably means you've got a corrupted JSON response from the server. Most likely it's an html-formatted PHP error/warning, embedded before/after the json data, e.g.
<p>PHP Warning: blah blahblah</p>[...json text here ...]
Since html is not valid json, you get that error message. So check out the RAW response from the server for that particular ajax call, and see what's coming back from the server.

A few things:
Why are you using \/ instead of just /?
Shouldn't the first return statement in the response be "a" not "z"?
Why do you have a block of JSON at the end of the response?

Related

How Can i save the converted jpg image to a specific directory?

the following code is saving the converted jpg file to the home directory like where the code is placed i want to store it in a folder namely images.
the file dcm-to-jpg is the file that i am executing on the web browser and then all the functions are being called. basically this is a dicom to jpg converter the solution i want is to save the converted file to a new folder that i have already created and also do let me know how to change the name of the file is that possible too??
Thanks in advance!! :)
Filename = dcm-to-jpg.php
<?PHP
#
# Creates a jpeg and jpeg thumbnail of a DICOM file
#
require_once('../class_dicom.php');
$file = (isset($argv[1]) ? $argv[1] : 'image1.dcm');
if(!$file) {
print "USAGE: ./dcm_to_jpg.php <FILE>\n";
exit;
}
if(!file_exists($file)) {
print "$file: does not exist\n";
exit;
}
$job_start = time();
$d = new dicom_convert;
$d->file = $file;
$d->dcm_to_jpg();
system("ls -lsh $file*");
$job_end = time();
$job_time = $job_end - $job_start;
print "Created JPEG and thumbnail in $job_time seconds.\n";
?>
filename = class_dicom.php
### Convert a DICOM image to JPEG. $this->file is the filename of the image.
### $this->jpg_quality is an optional value (0-100) that'll set the quality of the JPEG produced
function dcm_to_jpg() {
$filesize = 0;
$this->jpg_file = $this->file . '.jpg';
$convert_cmd = BIN_DCMJ2PNM . " +oj +Jq " . $this->jpg_quality . " --use-window 1 \"" . $this->file . "\" \"" . $this->jpg_file . "\"";
$out = Execute($convert_cmd);
if(file_exists($this->jpg_file)) {
$filesize = filesize($this->jpg_file);
}
if($filesize < 1) {
$convert_cmd = BIN_DCMJ2PNM . " +Wm +oj +Jq " . $this->jpg_quality . " \"" . $this->file . "\" \"" . $this->jpg_file . "\"";
$out = Execute($convert_cmd);
}
return($this->jpg_file);
}
?>

Use of undefined constant IMAGETYPE_WEBP - assumed 'IMAGETYPE_WEBP'

my version of PHP 5.6.3 and checked in PHP.INI that my php supports and accepts WEBP image files
It is constantly giving error.
Notice: Use of undefined constant IMAGETYPE_WEBP - assumed
'IMAGETYPE_WEBP' in C:\xampp\htdocs\dubai\xfiles1.php on line 19
Warning: image_type_to_mime_type() expects parameter 1 to be long,
string given in C:\xampp\htdocs\dubai\xfiles1.php on line 19
my php supports and accepts WEBP files and even display the WEBP images.
<?php
if (isset($_POST["csubmit"])) {
$_POST["property_title"] = str_replace(' ','-','meraki developers dubai Arjan 2bhk apartment');
$_POST["property_type"] = '2bhk';
// image mime to be checked against
$imagetype = array(image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_JPEG),
image_type_to_mime_type(IMAGETYPE_PNG),image_type_to_mime_type(IMAGETYPE_WEBP));
$error_msg = "";
$imageUploadERROR = FALSE;
$FOLDER = "uploads/";
$myfile = $_FILES["property_images"];
for ($i = 0; $i < count($myfile["name"]); $i++) {
if ($myfile["name"][$i] <> "" && $myfile["error"][$i] == 0) {
// uploaded file is OK
if (in_array($myfile["type"][$i], $imagetype)) {
// get the extention of the file
$file_extention = #strtolower(#end(#explode(".", $myfile["name"][$i])));
// Setting an unique name for the file
$file_name = $_POST["property_title"] . '-' . date("Ymd") . '_' . rand(10000, 990000) . '.' . $file_extention;
if (move_uploaded_file($myfile["tmp_name"][$i], $FOLDER . $file_name) === FALSE) {
$error_msg = "Error while uploading the file";
} else {
$error_msg = "File uploaded successfully with name: " . $file_name;
$location = 'uploads/' . $file_name;
mysqli_query($con,"insert into photo (location) values ('$location')");
}
} else {
$error_msg = "File is not a valid image type.";
}
}
if ($imageUploadERROR) {
// if upload error break the loop and display the error
break;
}
}
if ($imageUploadERROR === FALSE) {
// Failed to upload file, you can write your code here
echo $error_msg;
} else {
// file is uploaded, you can write your code here
echo "All file is uploaded successfully";
}
}?>
I dont know how to get thru this WEBP imagetype.
Any help is appreciated
From the manual...
IMAGETYPE_WEBP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
(Available as of PHP 7.1.0)
So this is only - Available as of PHP 7.1.0
Same error for my in PHP 7.0.0
Solved with:
if(!defined('IMAGETYPE_WEBP')){
define('IMAGETYPE_WEBP', 18);
}

PHP MySQL jQuery Uploading Multiple Files to server issue

I just finished designing a basic site to upload some files to the server, and store the file names in a database for searching functions. I designed the site using the following tutorial: www.formget.com.
My problem is when I go to upload more than one file at a time, it appends the filenames together for a single file.
Example:
Filename Example
Here is my code for uploading the files:
$error = '';
if(isset($_POST['submit']))
{
$j = 0; // Variable for indexing uploaded image.
$target_path = 'uploads/'; // Declare path for uploaded images.
for($i = 0; $i < count($_FILES['file']['name']);$i++) // Loop to get individual element from the array.
{
$valid_ext = array('jpeg','jpg','png','gif'); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_ext = end($ext); // Store extensions in the variable.
$filename = md5(uniqid());
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1]; // Set the target path with a new name of image.
if(($_FILES['file']['size'][$i] < 5000000) // Approx. 5MB files can be uploaded.
&& in_array($file_ext,$valid_ext))
{
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path))
{
// If file moved to uploads folder.
$success .= '<p class="success">('.$j.') Image uploaded successfully.</p>';
$date = date('Y-m-d H:i:s');
$stmt = $db->prepare('INSERT INTO uploads (filename,postdate,userid) VALUES (?,?,?)');
if($stmt)
{
$image = $filename . '.' . $ext[count($ext) - 1];
$stmt->bind_param('sss',$image,$date,$_SESSION['id']);
if($stmt->execute())
{
$success .= '<p class="success">('.$j.') Image added to database successfully.</p>';
}
else
{
$error .= '<p class="error">Error 34. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">Error 30. Please contact the Site Administrator.</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Please Try Again!</p>';
}
}
else
{
$error .= '<p class="error">('.$j.') Invalid file size or type.</p>';
}
$j = $j + 1; // Increment the number of uploaded images according to the files in the array.
}
}
Here is the jQuery:
var abc = 0; // Declare and define global increment value.
$(document).ready(function()
{
// To add new input file field dynamically, on click of "Add More Files" button, below function will be executed.
$('#add_more').click(function()
{
$(this).before($("<div/>",
{
id: 'filediv'
}).fadeIn('slow').append($("<input/>",
{
name: 'file[]',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will execute on change event of file input to select different file.
$('body').on('change', '#file', function()
{
if(this.files && this.files[0])
{
abc += 1; // Increment global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("abcd" + abc).append($("<img/>",
{
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function()
{
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e)
{
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e)
{
var name = $(":file").val();
if(!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
Any input as to why it keeps appending the filenames together would be appreciated. Please note that in the database, the filenames are correct, just not on the server itself in the uploads directory.
You are not resetting $target_path inside your for loop and therefore string concatenating it while looping. Results will be like A, AB, ABC, ... This is the issue:
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1];
You could create two variables.
$target_path = 'uploads/';
outside of your for-loop and use something like
$move_to_target = $target_path . $filename . '.' . $ext[count($ext) - 1];
inside your for-loop and update your call of move_uploaded_file to pass $move_to_target instead of $target_path. Your database entries are not affected because you build up the filename again in $image - this however seems bad practice (redundant code), if you want to enhance your code define $image first and then create $move_to_target like this:
$move_to_target = $target_path . $image;

Fileupload — Add random name and set max-size, how to do it?

Hi,
Today I have a file upload script.
The problem is that it does not rename file names, and has a maximum file upload size.
How can I add this to my current script?
$Filename=$_POST['Filename'];
$Name=$_POST['Name'];
$pic=($_FILES['Filename']['name']);
if (isset($_POST['save']) && !empty($_POST['Name']) && !empty($_POST['Category']) && !empty($_POST['Time'])){
$sql = "INSERT INTO View SET MergeID='{$_GET['id']}', Name='{$_POST['Name']}', Category='{$_POST['Category']}', Media='$pic', Time='{$_POST['Time']}'";
mysql_query($sql) or die(mysql_error());
GetFileUpload();
}
function GetFileUpload() {
if (file_exists("Media/" . $_FILES["Filename"]["name"])) {
echo $_FILES["Filename"]["name"] . " file already exist ";
} else {
move_uploaded_file($_FILES["Filename"]["tmp_name"], "Media/" . $_FILES["Filename"]["name"]);
// echo "File: ". basename( $_FILES['Filename']['name']). " has been created.";
}
}
if ($_FILES["Filename"]["size"] < 2000000)
{
if ($_FILES["Filename"]["error"] > 0)
{
echo "Return Code: " . $_FILES["Filename"]["error"] . "<br>";
}
else
{
$rand =rand(1000,9999);
$fname=$rand."-".$_FILES["Filename"]["name"];
move_uploaded_file($_FILES["Filename"]["tmp_name"], "Media/" .$rand );
}
For Ramdon name you can use timestamp along with the filename that will make it unique
use the DateTime() function of php.
If you are not using any framework you can set the fileupload limit from php.ini file
or use this
// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
reference http://www.php.net/manual/en/features.file-upload.php
$_FILES['Filename']['size'] will return you the size of the file in bytes, make a check on it accordingly to your maximum allowed size.
As for the renaming file, I use this piece of function:
function rename_file($file_to_rename)
{
$actual_name = pathinfo($file_to_rename,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($file_to_rename, PATHINFO_EXTENSION);
$name = $actual_name.".".$extension;
$i = 1;
while(file_exists("Media/".$actual_name.".".$extension))
{
$actual_name = (string)$original_name.'_'.$i;
$name = $actual_name.".".$extension;
$i++;
}
return $name; //For example, if file name is 1.jpg, this returns 1.jpg if that file doesn't exist else keeps incrementing like 1_1.jpg, 1_2.jpg etc.
}
function GetFileUpload($new_name) {
move_uploaded_file($_FILES["Filename"]["tmp_name"], "Media/" . $new_name);
// echo "File: ". basename( $_FILES['Filename']['name']). " has been created.";
}
$new_file_name = rename_file($_FILES['Filename']['name']);
GetFileUpload($new_file_name);
Edited:
Your GetFileUpload changed to match with the rename_file function.

"Only variables should be passed by reference" error

I can't really read PHP but I'm trying to upload a csv file in my page through php and got the following error. I know there are many threads that talks about this but I don't quite understand what they mean. Looking for an answer if someone could explain to me what's going on and provide a fix.
Strict Standards: Only variables should be passed by reference
in C:\xampp\htdocs\search\php\loader\csvFileUploader1.php on
line 9 failure to upload the file >>> Error code:
1
Here's the PHP
<?php
// using upload at click from http://code.google.com/p/upload-at-click/
// FileData is the name for the input file
$file_result = "";
$file = $_FILES['Filedata'];
$allowedExtensions = array("csv", "txt");
$extension = end(explode(".", $file["name"]));
function isAllowedExtension($fileName) {
global $allowedExtensions;
return in_array(end(explode(".", $fileName)), $allowedExtensions);
}
if($file["error"] > 0){
echo "failure to upload the file >>> ". "Error code: ".$file["error"]."<br>";
}else{
//echo " >>> CURRENT DIR: ".getcwd() . "\n";
$workDir = getcwd();
$dir = substr($workDir, 0, -10);
$path = $file["name"];
$newFileLoc = $dir.$path;
$file_result.=
"<br> Upload: " . $file["name"] . "<br>" .
" Type: " . $file["type"] . "<br>" .
" Size: " . $file["size"] . "<br>" .
" file uploaded to: ".$newFileLoc."<br>";
// txt - text/plain
// rtf - application/msword
// dat/obj - application/octet-stream
// csv - application/vnd.ms-excel
// maximum 200 MB file - 200,000,000 k
if ( ($file["type"] == "application/vnd.ms-excel" || $file["type"] == "text/plain")
&& isAllowedExtension($file["name"])
&& ($file["size"] < 200000000)
)
{
move_uploaded_file($file["tmp_name"], $newFileLoc);
//echo $file_result.=" >>> File uploaded successfull!!";
echo "|".$path;//"filePath : " . $newFileLoc;
}else{
echo " >>> NOT a file valid: ". isAllowedExtension($file["name"]);
}
}
?>
You can't pass along the return value of a function to end().
Make it:
$arrayVar = explode(".", $file["name"]);
$extension = end($arrayVar);
You would have the same issue with other PHP functions. For example empty(someFunction()) would not work.

Categories