Ajax success does not display message - javascript

my ajax success:function is not work.When i have successfully uploaded file,it should dispay message.However,it does not display message eventhough the file has been successfully uploaded.Can somone help me fix this problem?
Here is my code;
type: 'POST',
url: 'upload.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
$(".progress-bar").width('0%');
},
error:function(){
$('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
},
success: function(resp){
if(resp == 'ok'){
$('#uploadForm')[0].reset();
$('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
console.log('it works');
}else if(resp == 'err'){
$('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
}
}
php code:
$upload = 'err';
if(!empty($_FILES['file'])){
$targetDir = "D:/MMHE4DFiles/";
$allowTypes = array('avi');
$path=$_POST['path'];
$fileName = basename($_FILES['file']['name']);
$targetFilePath = $targetDir.$path.".avi";//$fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath);
}
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)){
$upload = 'ok';
echo $upload;
}
}

This cannot work.
Reason:
You move the file twice. But after the first move it is gone, so the second move must fail.
Solution:
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath) )
{
echo "ok";
exit();}
}
echo "err";
(Delete your last paragraph. )

Related

php ajax file upload, $_FILE is empty

I have a blob object and some data need to be post to fileHandler.php
so I pack them into a FormData:
console.log("start saving");
var url1 = URL.createObjectURL(blob);
var url2 = "data:application/octet-stream," + encodeURIComponent(JSON.stringify(dataPack));
console.log(url1);
console.log(url2);
fd.append('realName', dataPack.name);
fd.append("ans", JSON.stringify(dataPack.ans));
fd.append("log", JSON.stringify(dataPack.log));
fd.append("part", dataPack.part);
fd.append('fileToUpload', blob);
window.postData = fd;
and upload them via ajax:
$.ajax({
type: 'POST',
url: '../php/fileHandler.php',
data: postData,
processData: false,
contentType: false,
success: function() {
uploadSuccess();
},
error: function() {
uploadFail();
},
progress: function(e) {
console.log(e);
//make sure we can compute the length
if(e.lengthComputable) {
//calculate the percentage loaded
var pct = parseInt((e.loaded / e.total) * 100);
//log percentage loaded
$('#uploadProgress').width(pct+"%").text(pct+"%");
console.log(pct);
}
//this usually happens when Content-Length isn't set
else {
console.warn('Content Length not reported!');
}
}
}).done(function(data) {
console.log(data);
if(data ==="ok") {
uploadSuccess();
}
else {
uploadFail();
}
});
php file handler:
<?php
$target_dir = "uploads/";
$realName = trim($_POST['realName']);
$part = $_POST['part'];
$ans = json_decode($_POST['ans']);
$log = json_decode($_POST['log']);
$fileNameNoEx = $target_dir . $realName . "-" . $part ."-". time();
$target_file = $fileNameNoEx . ".mp3";
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
//save files
$f = fopen($fileNameNoEx.".txt", "w");
fwrite($f, "Answer log:\n");
foreach ($ans as $page => $val) {
fwrite($f, "$page : $val\n");
}
fwrite($f, "\nPage switching event log:\n");
foreach ($log as $l) {
fwrite($f, "{$l->time}s ---> {$l->page}\n");
}
fclose($f);
echo "ok";
} else {
var_dump($ans);
var_dump($log);
var_dump($_POST);
var_dump($_FILES);
var_dump($target_file);
echo "asdsad";
echo "Sorry, there was an error uploading your file.";
}
}
then strange things happen, sometimes uploading failed, and I when I try to upload again(in console, with the same data), browser keep logging:
NULL
NULL
array(0) {
}
array(0) {
}
string(24) "uploads/--1500100885.mp3"
asdsadSorry, there was an error uploading your file.
it seems that postData is empty? But when I check the postData in browser console:
> postData.get("fileToUpload")
File {name: "blob", lastModified: 1500101804839, lastModifiedDate: Sat Jul 15 2017 14:56:44 GMT+0800 (China Standard Time), webkitRelativePath: "", size: 12597888…}
> postData.get("realName")
"jjj"
why???? how can $_FILES[] and $_POST[] be emtpy?
This problem happens often when the file is very large.
PHP has a maximum post size, try to increase it: Increasing the maximum post size
If PHP didn't have this limit I could send an infinitely large POST to your web server until either it runs out of disk or RAM.

AJAX Uploading Image on form submit

I'm trying to upload an image with some other variables and on the form submit, do my php code to save the image to the users profile_picture table.
I want to make my image upload in the same form as saving my data changes.
This is a picture of what it looks like so you can have a better understanding :
I did it before where I used the POST method, but for AJAX i'm not sure how to do it.
My Javascript code is (note that this doesn't work, I just tried having a go - It returns Illegal invocation in the console.log) :
<script>
function updateMyAccount() {
var fd = new FormData($("#fileinfo"));
var password = document.getElementById("myAccountNewPassword").value;
var profilePicture = document.getElementById("myAccountNewProfilePic").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
SaveAccountChanges: true,
securePassword_Val: password,
fd
},
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
My PHP code is :
//My account AJAX POST
if(($_POST['SaveAccountChanges']) == true & isset($_POST['securePassword_Val']))
{
$member_config->doUpdateAccountInfo($con);
}
Then my function to upload the image and save it to the database :
function doUpdateAccountInfo($con)
{
//Upload users image to our /uploads directory
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
$save_to_database = ("uploads/" . $_FILES["fileToUpload"]["name"]);
$normalPassword = mysqli_real_escape_string($con, $_POST["securePassword_Val"]);
$pwd = password_hash($normalPassword, PASSWORD_DEFAULT);
$username = $_SESSION["username"];
if(!empty($_FILES['fileToUpload']) & !empty($_POST['securePassword_Val']))
{
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {} else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
$query = "UPDATE users SET password = '$pwd', profile_picture = '$save_to_database' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password and profile picture</i></b>!</p></div>';
//echo '1';
}
else if (empty($_FILES['fileToUpload']) & empty($_POST['securePassword_Val']))
{
$query = "UPDATE users SET password = '$pwd' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>profile picture</i></b>!</p></div>';
//echo '1';
}
else if (empty($_POST['securePassword_Val']) & !(empty($_FILES['fileToUpload'])))
{
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) { echo 'Successfully uploaded image'; } else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
$query = "UPDATE users SET profile_picture = '$save_to_database' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password</i></b>!</p></div>';
//echo '1';
}
else if (empty($_POST['securePassword_Val']) & empty($_FILES['fileToUpload']))
{
$result = mysqli_query($con, $query) or die('error');
//echo '<div class="panel -danger"><div class="panel-body"><p>You have failed to update your <b><i>password and profile picture</i></b>!</p></div>';
echo '0';
}
else
{
//echo '<div class="panel -danger"><div class="panel-body"><p>An error occured!</p></div>';
echo '0';
}
}
I have looked a the link that was posted and now have this code :
<script>
function updateMyAccount() {
var fdata = new FormData($("#data"));
fdata.append("securePassword_Val",$("#myAccountNewPassword").val());
fdata.append("SaveAccountChanges",true);
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data:
//SaveAccountChanges: true,
//securePassword_Val: password,
fdata
,
async: false,
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
How would I go about making the image upload through this method ?
Normally, I wouldn't answer this question because it gets asked many times. But I see few issues in your code, so I'm going to make an attempt.
JavaScript
(1) Ensure that you have included jQuery script
(2) Ensure that you have a form element (preferrably give it an ID attribute e.g. myform for referencing) and all your inputs have name attributes.
(3) Pass the native form element (not jQuery object) into FormData constructor. This will allow you to pass all the input elements with name attributes from your form -- so you don't need to manually add them. Exception is your SaveAccountChanges field that you want to pass, here you need to use FormData.append().
(4) Set $.ajax data option to only the FormData object. Set contentType and processData options to false.
function updateMyAccount() {
// document.getElementById('myform') === $("#myform")[0] === myform
var fd = new FormData($("#myform")[0]);
fd.append('SaveAccountChanges', true);
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: fd,
contentType: false,
processData: false,
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
});
return false;
}
And this should be the minimum that you need on the client-side. When debugging, use your browser's web tools.
PHP
(6) Turn on your PHP error reporting.
(7) Learn the difference between && and & -- they are not the same.
(8) Because you are uploading using FormData, you need a stronger validation for your upload fields. $_FILES['fileToUpload'] will not be empty even when you don't select a file.

convert php image upload script to json response

I wrote the script for uploading image in folder say (upload) in my case.
It's working perfectly !
I just want to get response message in json.
I don't know how to use json in scrip and where.
Thanks !
script.js
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // 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
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image after validation
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
ajax_php_file.php
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
firstly pass a property in ajax
dataType: "JSON"
next you have to build and array of all the data that your out putting in stead of echo for eg
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
change to
$respons['msg']="<span id='invalid'>***Invalid file Size or Type***<span>";
then use
echo json_encode($respons);
this will pass a json object your client side
once there you can console output your data to see how to access the nested objects

PHP echo jQuery AJAX request

This is my jQuery request to upload an image file
$('#upload-image').change(function(e){
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType))
return;
console.log(file);
var form_data = new FormData();
form_data.append('file', file);
console.log(form_data);
$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
This is upload.php on local webserver
<?php
header('Access-Control-Allow-Origin: *');
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
echo $target_path;
}
?>
When I upload the image and send request. It returns and logs for me complete code lines of upload.php, not the result from echo command line that I want. I check console Network tab and see that the response is nothing except complete code of upload.php. It truly does not handle anything server-side. What did I do wrong?
You need to make sure that PHP runs server-side. If there's no PHP handler installed, the server will return the content of your upload.php file as text. I think that's your primary problem.
Based on your platform, you may try:
http://www.wampserver.com/en/ (windows)
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04 (Ubuntu)
https://www.mamp.info/en/ (MacOS)
First of all make sure your PHP works, by creating a file called info.php in your webroot folder with the following content
<?php
phpinfo();
This should display your configuration. Then you can start debugging the Javascript. The content type should by multipart/form-data so that the server knows it expects an upload.
Good luck!

Ajax login issues

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.

Categories

Resources