ajax not uploading file pic to database and server - php

My problem is that my script doesnt upload the pic on serv and insert it into database when i use ajax submit for some reason. If i submit form with php action="file.php" it works. Here are my ajax script and php one.I dont see where the problem is and why it works with php submit and not working with ajax. Thnx in advance.
<script>
$(function() {
//twitter bootstrap script
$("button#submit").click(function(){
$.ajax({
type: "POST",
url: "engine/app/process.php",
data: $(\'form.edit\').serialize(),
dataType:\'json\',
success: function(data){
$("#bday").html(data.a)
$("#locatie").html(data.b)
$("#descriere").html(data.c)
$("#interes").html(data.d)
$("#status").html(data.e)
$(".img").html(data.f)
$("#myModal").modal(\'hide\');
},
error: function(){
alert("failure");
}
});
});
});
</script>
php script
<?php
require_once('../core/dbconfig.php');
$dbc = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASS, DB_NAME);
$nume=$_POST['nume'];
$bday=$_POST['bday'];
$locatie=$_POST['locatie'];
$status=$_POST['status'];
$interese=$_POST['interese'];
$despre=$_POST['descriere'];
$id_user=$_POST['id_user'];
$query="Update `users` SET username='$nume',bday='$bday',Locatie='$locatie',Relatie='$status',Interese='$interese',Descriere='$despre' where id='$id_user' ";
$result=mysqli_query($dbc,$query) or die("query failed: " . mysqli_error($dbc));
$path = '../../images/users/'.$id_user.'/';
if(!is_dir($path)){
mkdir($path,0755);
}
$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "JPG");
$name = $_FILES['img1']['name'];
$size = $_FILES['img1']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
/*$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;*/
$actual_image_name=$id_user.'.'.$ext;
$tmp = $_FILES['img1']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$queryz="Insert into Galerie (ID_User,Poza,Poza_Profil) VALUES ('$id_user','$actual_image_name',1)";
$resultz=mysqli_query($dbc,$queryz) or die("query failed: " . mysqli_error($dbc));
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
echo json_encode(array("a" => $bday, "b" => $locatie,"c" => $despre,"d" => $interese,"e" => $name,"f" => ""));
?>

The serialize method puts your form fields data in a string complying to the application/x-www-form-urlencoded content type used to submit forms to servers for processing, while files are submitted in requests encoded in the multipart/form-data content type, so, serialize ignores file inputs.
You should use formData
var form = new FormData(document.getElementById('your_frm_id'));
var file = document.getElementById('img1').files[0];
if (file) {
$('#sent_progress').show();
form.append('img1', file);
}
In ajax use
data: form,
Read More here https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
Or you can use some Jquery Plugin to upload your file with form
hope it will help

With only Ajax request you can't upload the file to the server. A Better option is use jQuery Form
This links also includes some example codes, follow the documentation and achieve what you want.
Take a look how to implement jQuery Form plugin, on Ajax based image upload

Related

Ajax File upload 'An error occurred trying to load resource' and network connection lost in Safari

I m trying to upload a file and a thumb of that file (using the cropper v2.3.0).
This code work on all other browser but in safari it gives an error.
The problem describe as follow:
on safari browser on desktop when upload the file then the below error occurred and used other then safari browser there is no error and get success message.
I test both ways that first upload only the cropped image that is in base64
encode or also in blob as file with appending into formData but on both ways that error not resolved.
I also tried to upload the image only then error occurred sometimes or sometimes not.
if use cropper adjust then the error occurred (this is my assumption)
My js Code to submit the form
function addFile() {
$("#result").html("");
var myForm = $('#mainForm');
var formData = new FormData(myForm[0]);
$.ajax({
url: "action.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
dataType: "json",
success: function (data) // A function to be called if request succeeds
{
$("#result").html(data.response + " : " + data.message);
},
error: function (res) {
$("#result").html(res.responseText);
}
});
return false;
}
my action php code
<?php
$uploadThumbnailPath = "dir";
$thumbImgData = $_POST['thumbImg'];
$numberOfImages = 1;
$isImageUploaded = 0;
if ($thumbImgData != "") {
//thumbnail image uploading code
list($type, $thumbImgData) = explode(';', $thumbImgData);
list(, $thumbImgData) = explode(',', $thumbImgData);
$thumbImgData = base64_decode($thumbImgData);
$myTimeStamp = "thumbImg_" . time() . uniqid();
$displayImageName = $myTimeStamp . ".png";
$dir = $uploadThumbnailPath;
if (file_put_contents("$dir/$displayImageName", $thumbImgData)) {
$jpgFormatImageName = $myTimeStamp . ".jpg";
convertPNGtoJPG("$dir/$displayImageName", "$dir/$jpgFormatImageName", 238, 238, 238, 1);
if (file_exists("$dir/$displayImageName")) {
unlink("$dir/$displayImageName");
}
$isImageUploaded = 1;
}
} else {
$arrayResponse = array("response" => "thumbImg_BLANK", "message" => 'thumbImg_BLANK');
echo json_encode($arrayResponse);
exit;
}
for ($i = 1; $i <= $numberOfImages; $i++) {
if (isset($_POST["imgName$i"])) {
$itemImagesName = "";
} else {
$itemImagesName = $_FILES["imgName$i"]['name'];
}
if ($itemImagesName != "") {
$extension = pathinfo($itemImagesName, PATHINFO_EXTENSION);
$uploadNewFileNameWithoutExt = "image_" . md5($i . time());
$uploadDirPath = "dir/p/";
$uploadNewFileName[$i] = $uploadNewFileNameWithoutExt . '.' . $extension;
$uploadNewFileWithPathName = $uploadDirPath . $uploadNewFileName[$i];
$mesUpload = uploadImageFileOnServer("imgName$i", $allowedExts, $maxFileSize, $uploadNewFileWithPathName);
}
}
$itemImages = implode("#:#", $uploadNewFileName);
$thumbnailImageName = "default_thumbnail.png";
if ($isImageUploaded == 1) {
$thumbnailImageName = $jpgFormatImageName;
}
if ($mesUpload == "FILE_UPLOADED") {
$arrayResponse = array("response" => "OK", "message" => "OK UPLOAD SUCCESS");
echo json_encode($arrayResponse);
exit;
} else {
/* $mesUpload */
$arrayResponse = array("response" => "FILE_FAILED", "message" => "FAIL TO UPLOAD");
echo json_encode($arrayResponse);
exit;
}
?>
Here the screen shots of the error of that
this is image where the
screen shot 1
screen shot 2
Please help me to solving this issue. i am puzzled for this error and i have not getting any idea to resolved this problem.
If any one want to use i upload a sample code on the web click on below link
https://tamapev.000webhostapp.com/upload-img/
The issue is probbaly you sending the form data to the wrong page, first determine whether action.php is in the root directory or if it is in a directory called "upload-img". Then send the request to that given page.
Next for the error that says "An error occurred trying to load resource", to see what the actual error is, in your first screenshot there is a little button in the panel that says "Response", Click on it and change it to "JSON"
If "action.php" is in "upload-img" then you need to change
url: "action.php", to url: "/upload-img/action.php",

simple parse error with my form submit using ajax and file upload

I'm able to get the file uploaded and in to the directory I want so that part seems to work but I'm not sure why I'm getting a parse error in the js console in chrome. Because of this error my bottom javascript won't execute and I need it to do so.
Here's the ajax:
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
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, textStatus, jqXHR)
{
alert(data);
script = $(data).text();
$.globalEval(script);
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
Here's the html:
<?php
echo '<span class="new_profile_save_upload_image_span"><img src="'.$url_root.'/images/615721406-612x612.jpg"/ class="new_profile_save_upload_image_img"></span>';
?>
<form action="" method="post" enctype="multipart/form-data" name="new_profile_save_upload_image_input_form" id="new_profile_save_upload_image_input_form">
<input type="file" id="new_profile_save_upload_image_input" name="new_profile_save_upload_image_input" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
<input type="submit" value="Upload Image" name="submit">
</form>
And here is the php:
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
<script>
var scope1 = '<?php echo $url_root;?>';
var scope2 = '<?php echo $username;?>';
var scope3 = '<?php echo $file['name'];?>';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
$('.new_profile_save_upload_image_span').empty();
$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
alert(data) doesn't seem to be popping up, so there's something wrong previous to that execution.
I tried this code with simply 'submit.php' but it doesn't seem to work without the 'files' addition to it.
Also do I have the filename correct? Should the file's filename be $file['name'] in php? I'm trying to get the file name as a string and place it in when the default image is (as an image to be displayed), using an img html tag and inserting it via jquery, as you can see at the bottom under .
The ajax should execute this script at the bottom but it doesn't due to the error.
Also is there a nicer way of writing the bottom jquery scripts that I have written?
Error I'm getting:
ERRORS: Syntax Error: Unexpected Token < in JSON at position 103
Thanks in advance.
If you want to return JSON and HTML at the same time, you could put the HTML into an element of the $data array.
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
$data['html'] = <<<EOS
<script>
var scope1 = '$url_root';
var scope2 = '$username';
var scope3 = '{$file['name']}';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
\$('.new_profile_save_upload_image_span').empty();
\$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
EOS;
}
echo json_encode($data);
?>
Then in the JavaScript you do:
script = $(data.html).text();
It's better to use try-catch block in your PHP code, and send status with the response set to true or false. Also, send the $url_root and $username variables within the JSON object.
See this beginner's guide on Image Uploading with PHP and AJAX to learn everything about creating AJAX handler, validating, saving and sending a response back to the client side.

Error in my php file I can't seem to find? Perhaps caused by ajax?

First of all, I've just met with ajax and jquery and I must admit they seem pretty interesting. But I lost quite some time on figuring out why are my results in uploading img-s always the same.The idea is creating a page where I could import multiple images with some restrictions such as size and extension,but for some reason errors just aren't printing. It just prints alert("Image Uploaded") no matter what the result. This is the ajax part of my html:
<script>
$(document).ready(function(){
$('#uploadForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData:false,
success: function(data)
{
$("#gallery").html(data);
alert("Image Uploaded");
}
});
});
});
</script>
And this is the upload.php that I simply call in my html file:
<?php
//upload.php
$output = '';
if(is_array($_FILES))
{
foreach ($_FILES['files']['name'] as $name => $value)
{
$totalImageIndex = ($name+1);
$file_name = explode(".", $_FILES['files']['name'][$name]);
$file_size = $_FILES['files']['size'][$name];
$allowed_ext = array("png", "gif");
if(in_array($file_name[1], $allowed_ext))
{
if($totalImageIndex <= 5 ) {
// 2 MB is 2097152 bytes.
if($file_size < 2097152){
$new_name = $totalImageIndex . '.' . $file_name[1];
$sourcePath = $_FILES['files']['tmp_name'][$name];
$targetPath = "slike/".$new_name;
if(move_uploaded_file($sourcePath, $targetPath))
{
$output .= '<img src="'.$targetPath.'" width="150px" height="180px" />';
}
}
else { continue ; }
} else echo 'file is too big!';
} else echo 'wrong file format!';
}
echo $output;}
?>
Any idea or suggestion would be appriciated, thank u in advance!
In ajax on success you will get the data back that you echoed on your php file so either you get the image back or the error back you can simply alert(data); only and see what you getting in your ajax code you are alerting alert(image uploded) which will always be called as you are getting an error data also as success just remove that alert and do only alert(data) and you will see the error if any

upload file using ajax like facebook uploading

My problem is, I want to upload a csv file without pressing a submit button and I used ajax for that case. But now, their is something errors appear, and the error said fopen() Filename cannot be empty. But I already get the file value that I want, but the $_FILES[$fie]['tmp_name'] can't read this value. But if I attach the variable in an alert() they display the exact filename. This is my sample codes.
This is the html:
<form id="Form2">
<input type="file" id="fie" />
</form>
this is the javascript:
<script style="text/javascript">
$(function(){
$('#Form2').change(function(e){
e.preventDefault();
var sub = document.getElementById("fie").files[0].name;
if($('#cat1').hasClass('show')){
$('#cat1').hide();
$('#cat2').html("<img src='pb1.gif' />");
$.ajax({
url:'uploading.php',
action:'get',
data: 'fie='+sub,
success: function(data){
$('#cat2').html(data);
}
});
}
});
});
</script>
This is the Php:
uploading.php
<?php
include("conn.php"); //assuming that connected to a database.
if (isset($_GET['fie'])) {
echo "<script>alert('".$_GET['fie']."')</script>";//IN ALERT THEY EXECUTE THE EXACT VALUE OF THE FILE I INPUT
$fie = $_GET['fie'];
$file = $_FILES[$fie]['tmp_name']; //PROBLEM IS THIS. THEY CAN'T READ THE VALUE AND TELL THEIR IS NO FILE.
$handle = fopen($file,'r') or die ('Cannot open file');
fgets($handle);
do {
if (isset($data[0])) {
mysql_query("INSERT INTO tbl_numbers (numbers,cute) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."')");
}
}
while ($data = fgetcsv($handle,1000,",","'"));
echo "Successful Upload~!";
}
?>
Thanks for the reply.

Jquery Form plugin picture retrieve

I am using the Jquery Form plugging to try and upload a picture to my mysql DBMS. I use the JqueryForm ajaxForm() call to do this. It calls a php file on my server and that script puts the file into the database. I then attempt to get that file out of the database in the same script. I guess the nuts and bolts of how I do it is irrelevant. I really want to know how I would get a picture back from an ajax call using the AjaxForm call from the jqueryForm pluggin. Does anybody have an example of how to do this using that pluggin? I am a little lost...
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$(document).ready(function () {
$('#profilepicbutton').live('change', function () {
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#registerpt3").ajaxForm({
target: '#preview',
success: function (data) {
$("#preview").html('');
$("#preview").append("<img src=" + data + "></img>");
}
}).submit();
});
});
</script>
Now, On the jquery form pluggin site, there is a page in particular that has instructions for file uploads...
http://jquery.malsup.com/form/#file-upload
The example that they give is a little blank...
<textarea>
for (var i=0; i < 10; i++) {
// do some processing
}
</textarea>
Now, what am I supposed to do with that? Why am I looping through some data structure? If you look on there page, you will see they are remarkable brief in their instructions of what to do. Anybody have any tutorials or advice? Thanks.
UPDATE PHP Code
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['profilepicinput']['name'];
$size = $_FILES['profilepicinput']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['profilepicinput']['tmp_name'];
$fp = fopen($tmp, 'r');
$data = fread($fp, filesize($tmp));
$data = addslashes($data);
fclose($fp);
values('$email', '$tmp')");
if(mysql_query("insert into Personal_Photos (Email, Pics) values('$email', '$data')"))
{
$query="select Pics, MAX(ID) from Personal_Photos where Email='$email'";
$result=mysql_query($query) or die("Error: ".mysql_error());
$row=mysql_fetch_array($result);
$mime = 'image/yourtype';
$base64 = base64_encode($contents);
$uri = "data:$mime;base64,$base64";
header("Content-type: image/jpg");
print($row['Pics']);
}
else
{
die('Invalid query: ' . mysql_error());
echo "failed";
}
}
else
echo "Image file size max 1 MB. Image Size:"+$size;
}
else
echo "Invalid file format..";
}
else
echo "Please select image..! Bull shit".$email;
exit;
}
If I understand your question right, you can create a so called data URI.
In PHP it's quite simple:
$mime = 'image/yourtype';
$base64 = base64_encode($contents);
$uri = "data:$mime;base64,$base64";
And pass this as string in the ajax reponse to be directly entered as you outlined in your question.
Hopefully this helps, I'm not fluent with jqueryform.

Categories