error handling during ajax file upload using jquery form plugin - php

i have a situation where i'm stuck at the idea of catching the appropriate error during file upload in the ajax response in jquery form-plugin.
i'l give an idea of what i want to achieve through some pseudocode.
My php is :
$file = strtolower($_FILES["myfile"]["name"]);
$extension = substr($file, strrpos($file, '.') + 1);
if($extension == 'jpg'){
// upload the file
if(move_uploaded_file($_FILES["myfile"]["tmp_name"], $folder . $finalFilename)){
// do something here like
echo "<div id='statusContainer'>
<table><tr><td>
<img src='uploads/".$finalFilename."'>
</td></tr>
<tr><td>".$finalts."</td></tr></table>
</div>";
}
} else {
$error = 1; // will give numbers to different errors like filetype error, size error etc..
}
now my JS code is :
(function() {
var status = $('#status');
$('form').ajaxForm({
complete: function(xhr) {
if(xhr.responseText == "// what do i get echoed here so i can run an array and show user appropriate error like size error, type error etc. // "){
// i want to open a dialog box with correct error message//
} else{
status.hide().html(xhr.responseText).fadeIn(1000);
}
}
});
})();
shall i get the error number echoed in the ajax response and run through an array to get the message? but then i'll have to put in a lot of if conditions in the ajax response with different error numbers.
Please anyone have a more logical idea??

you could make an array and pass error json_encode()'ing it and parse json response from ajaxForm, like
php part:
$responseArr = array();
if( file_is_uploaded ) {
$responseArr["error"] = "0";
$responseArr["message"] = "File uploaded success message";
}
else {
$responseArr["error"] = "1";
$responseArr["message"] = "Error message here";
}
echo json_encode($responseArr); //pass it as response
js part::
$('form').ajaxForm({
dataType: "json",
success: function(response) {
//parse json response and perform accordingly
console.log( response );
}
});

To cut down on traversing an array in JS, and matching error IDs to descriptions, could you associate the error description itself to be relayed in the ajax response? This would keep your JS lean and keep error handling serverside.
Example:
<tr><td>".$finalts."</td></tr></table>
</div>";
}
$error_descriptions = array("Filesize Error", "Extension Error");
} else {
$error = error_descriptions[1];
}

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",

Display JSON on UI

Maybe i am wrong but i can not find anyone who wants to display a json message just in json format from url on the page except for me.
I have a webshop in html, javascript and css. I am looking for some code example to display the json message just on the page. I don't want to parse the json into html or what else. I just want to display the json message as it is like this format: {"success":0,"message":"User not known"}.
This message above is the url response from my php database in xampp.
Below is my code and it works good, the problem is that this code is static. I am looking for some dynamic solution where you enter the url and it responds with json message. Any help is appriciated.
this is my login.html
if(form.id.value == "" || form.pass.value == "") {
alert("Empty details!");
}else if (form.id.value=="johan" && form.pass.value=="123") {
location="Page2.html"
} else { alert("Wrong username or password!")
}
}
and this is the json read:
// 1 - read josn:
var my_json_output = {"success":1,"message":"Vol","Username":"jan","UserSurname":"janman"}',
json_yes.succes json_yes = JSON.parse(my_json_output);
var my_json_output = '{"success":0,"message":"User_Unknown"}',
json_no = JSON.parse(my_json_output);
if(json_no.success == 1) { alert("Welcome, " + s + json_yes.Username);
}else if(json_no.success == 0) { alert("Try again");
}
Now i could find the answer and will share with others: just make a variable from XMLHttpRequest(); and use that variable for the message:
myconnect = new XMLHttpRequest();

Can't read php file when upload image to server in titanium

I have tried to get the image from gallery and upload the selected image to server using webservices in titanium.
I have used below code. But am getting the debug error : HTTP error And also it shows the alert box like "There was an error during the connection"
This code is working fine in my development server.But it is not working in my client server. What's the reason ? why my code is not working in my client server ?
The file upload is working fine when upload the file from android device.But it's not working while upload a file from iphone device.Can you please give me a idea to resolve this issue ?
Why am getting this error on my console window.
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var request = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}
else{
alert(this.responseText);
}
},
onerror: function(e){
Ti.API.debug(e.error);
alert("There was an error during the connection");
},
timeout:20000,
});
var uploadabc = event.media.imageAsResized(400 , 400);
request.open("POST",url+"client/manager/at_manager_create_common_file.php");
var params = ({"manager_id": manager_id,"file": uploadabc,});
// var params = ({"manager_id": manager_id,"file": event.media,});
request.send(params);
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]
});
}
EDIT:
this is php file :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$manager_id = $data['manager_id'];
$file_name = $data['file_name'];
$source = base64_decode($data['source']);
include "db_connect.php";
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT * from at_common_files WHERE user_id = '$manager_id' and file_name = '$file_name'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$response='{"Error":"1","Message":"Filename already existed"}';
echo $response;
} else {
$upload_dir = 'common_files/'.$manager_id."_".$file_name;
file_put_contents($upload_dir,$source);
$qugery = mysql_query("insert into at_common_files (user_id,file_name) values ($manager_id, '$file_name') ");
$response = '{"Error":"0","Message":"Successfully file is created"}';
echo $response;
}
?>
EDIT:
As am getting the below error :
: [DEBUG] HTTP error
: [INFO] IN ERROR {"type":"error","source":{"cache":false},"code":404,"error":"HTTP error","success":false}
if i have call the same url and pass a manager_id alone , am getting the results fine.if i have passing the manager_id and file, this time only am getting the Http error. i can't find a exact issue.Because the same titanium code and php code (development server)is working fine and the image is uploading to development server folder. but i have moved the same php file to my client server.now it is not working . also the same web service url is working fine in browser and android.it's not working in iphone only.so that exactly i can't find where is the issue ? can you please give me a solutions.
EDIT :
please refer the below link:
http://developer.appcelerator.com/question/174462/image-not-uploading-from-iphone#comment-224007
I have facing a exact same issue.could you please give me a solution.
i have found many questions like this (e.g. The 'Passive' connection '<appname>' access to protected services is denied).
the answer is always:
"This error is what's known as a "Red Herring". It's a clue that's misleading. The HID isn't a real error that affects your app. There should be other messages that may indicate what's going on."
so look if there is a other error massege which describes your problem.
for example try to escape the filename you are using within the sql statements:
$file_name = mysql_real_escape_string($data['file_name']);
Make sure your device is connected to the internet and then try it like this:
Titanium:
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info('IN ERROR ' + JSON.stringify(e));
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}else{
alert(this.responseText);
}
};
xhr.open('POST', url+"client/manager/at_manager_create_common_file.php");
xhr.send({
media: event.media,
manager_id: manager_id
});
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]*/
});
}
PHP:
<?php
//this function returns a random 5-char filename with the jpg extension
function randomFileName()
{
$length = 5;
$characters = 'abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string . '.jpg';
}
//create the random filename string and uploads target variables
$randomString = randomFileName();
$target = 'common_files/'.$randomString;
if(move_uploaded_file($_FILES['media']['tmp_name'], $target))
{
echo "success";
}
else
{
echo "moving to target failed";
}
?>
For more info check this link: http://code.tutsplus.com/tutorials/titanium-mobile-build-an-image-uploader--mobile-8860
If it works like this you will have to add your logic again (resizing and manager_id)

get the result from mysql+php and shows in titanium

I have developing the one application using titanium.
Here the values are inserted successfully.But i didn't get the success message from webservices code.
I have using following code for insert a databaase :
In titanium side code :
function StaffRegistration(){
if($.staff_firstname.value != "" && $.staff_firstname.value != null){
var request = Ti.Network.createHTTPClient({
onload:alert(this.responseText),
onerror: function(e){
Ti.API.debug(e.error);
alert(this.responseText);
},
timeout:1000,
});
request.open("POST","xxx/xxx.php");
var params = ({"staff_firstname": $.staff_firstname.value,"staff_email": $.staff_email.value,"staff_password": $.staff_password.value,});
request.send(params);
}
else{
alert("Please enter the firstname");
}
Ti.API.info("Result for registration = " + this.responseText);
};
I have using a following php(webservice code) :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$staff_firstname = $data['staff_firstname'];
$staff_email = $data['staff_email'];
$staff_password = md5($data['staff_password']);
include "db_connect.php";
$db = new DB_CONNECT();
$result = mysql_query("SELECT staff_email,staff_firstname from at_staff WHERE staff_email = '$staff_email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while($queryresult=mysql_fetch_array($result)) {
$uname[]=$queryresult['staff_firstname'];
$uemail[]=$queryresult['staff_email'];
}
if(in_array($staff_firstname,$uname) and in_array($staff_email,$uemail)) {
$response='{"Error":"1","Message":"Username and Email already exist"}';
echo $response;
} else if (in_array($staff_firstname,$uname)) {
$response='{"Error":"1","Message":"Username already exist"}';
echo $response;
} else {
$response='{"Error":"1","Message":"Email already exist"}';
echo $response;
}
} else {
$response='{"Error":"1","Message":"Successfully Registered"}';
echo $response;
$data=array("staff_firstname"=>"'".$staff_firstname."'",
"staff_email"=>"'".$staff_email."'",
"staff_password"=>"'".$staff_password."'"
);
echo $response;
}
?>
How can i get the $response in titanium from this webservice url.
#user2218667
Ti.API.info("Result for registration = " + this.responseText);
will NEVER work as you show in the first piece of code .
why ? because you send a request which will take like 1 seconde (for exemple), obviously, your programm won't wait 1 sec after
request.send(params);
i will continue the programm and when the request return a result, it will get into
onload(e) :
and here only you will be able to have your $result.
is this ok? well now, if this.responseData isn't effective, I don't have the solution .Can you check your line : "} else {" ,i supose there is a if above in the code? are you sure $result is defined upper?
Can you try the same request without titanium with a basic html form to be sure $result is write correctly in this case, like this, we will know if the problem come from php or from the link betwin php & titanium.
well , i supose it's asynchronous request, so the folowing may not work
Ti.API.info("Result for registration = " + this.responseText);
coud you try :
onload : function(e) {
Ti.API.info(this.responseText); // maybe Ti.API.info(this.reponsedata) according to your php.
},
onerror : function(e) {...
in my mind, if you receive JSON information (it trully look's like), you need
this.responseData //instead of this.responseText

jQuery plugin Validation email check if else CRAZY WIERD

I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})

Categories