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)
Related
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",
Well at first you got to believe me on this: the queries I am using are all correct (tested it way to much and also everything works perfectly on the localhost). Lets start explaining my problem: I am running a small application (for fun and learning) and I do a lot of stuff with ajax requests, which works I can see it in the developer tools "sending, those requests go to a function.php file and should run. The code in the function file looks a bit like this:
if (isset($_POST['search'])) {
// Do stuff like running a query
}
All the requests go through the if statement but then all the following queries fail, while correctly writen. So I tried turning on showing erros on the live server but I can't seem to get it done (tried ini_set display errors, with htacces, and messed alot around in the server settings), so I can't see any errors only that the query fails because of this piece of code:
if ($query = mysqli_query($conn, "sql query bla bla")) {
// Dp stuff
} else {
// return error Message
echo "<p style='color:red;'>Something went wrong, please try again!</p>";
}
I get somehting went wrong all the time?
For orientation:
I have a folder, called functions, with multiple function.php files in it all connecting to the database indivitualy, maybe this has something to do with it?
This problem doesn't occurre on only one file but all the function.php files don't work. while If I put php code on origin file itself everything works fine
Hope someone can help me with this, I am out of suggestions
PS my English is not that great hope you will understand! if not let me know or if you need more information also let me know!
Edit
<?php
include_once'/../includes/dbconfig.php';
// If something is posted
if (isset($_POST['search'])) {
$word = stripVariables($_POST['search']);
$querySearch = "SELECT name, description, group_id FROM groups WHERE name LIKE '%$word%'";
$resultSearch = mysqli_query($conn, $querySearch);
$numberSearch = mysqli_num_rows($resultSearch);
// If something is found
if ($numberSearch >= 1) {
$end_result = '';
// Fetch search values, create search results
foreach ($resultSearch as $row) {
global $word;
// Get group values
$name = $row['name'];
$description = substr($row['description'], 0, 40);
$groupId = $row['group_id'];
// Make typed in word bold
$bold = '<b>' . $word .'</b>';
$fullWord = str_ireplace($word, $bold, $name);
// Create list items for each search result
$end_result .= "<li class='search-item'><div class='list-text'>" . $fullWord . "<br><b style='font-size:10pt; font-weight:normal'><span id='group_id'>" . $groupId . "</span> , " . $description ."...</b></div><div class='list-join'><div id='send_request'><p>Send Request</p></div><div><p>Cancel</p></div></div></li>";
}
echo $end_result;
} else {
// Nothing found five error
echo "<li style='color:red; padding: 10px; border: none;'>No results found!</li>";
}
}
// Prevent injections
function stripVariables($input){
$var = trim($input);
$var = strip_tags($var);
$var = stripslashes($var);
$var = htmlspecialchars($var);
return $var;
}
?>
And I use this method with ajax/ javascript
$(".join-inner input[name='submit']").click(function(){
// Get value user input
var inputSearch = $(".join-inner input[type='text']").val();
// Setup datastring
var dataString = "search=" + inputSearch;
// If inputSearch is not empty
if (inputSearch) {
// Ajax call
$.ajax({
type: "POST",
url: "functions/searchGroup.php",
data: dataString,
cache: false,
beforeSend: function(html) {
$('.results').html("");
},
success: function(html){
$('.results').html(html);
}
});
} else {
$('.results').html("<li style='color:red'>Type something to search</li>")
}
return false;
});
Are you sure that $conn is valid ?
$conn = mysqli_connect("localhost", "my_user", "my_password", "my_db");
/* check connection */
if (mysqli_connect_errno()) {
echo("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Then your code:
if ($query = mysqli_query($conn, "sql query bla bla")) {
// Dp stuff
} else {
// return error Message
echo "<p style='color:red;'>Something went wrong, please try again!</p>";
}
I'm working on a chat log manager - I wanted more control over Thunderbird's chat log archives. There's a synch functionality that basically parses the log files and uploads the messages to a database, zips the logs and stores them in an archive folder.
This process takes a long time to run, and I'd like to display a progress bar. I'm using both jQueryUI and Bootstrap - so a solution that would utilize either of these would be acceptable.
I've tried implementing both of these to no avail so far. The progress bar doesn't show up, and there's no way for me to tell if it's being incremented or not.
I've pasted the code I've got so far. Any help would be appreciated... I have basic knowledge of CSS and my knowledge of javascript is limited at best.
HTML Head
<script>
function UpdatePBar(x){
$( "#progressbar" ).progressbar( "value", x );}
</script>
HTML Body
<div id="progressbar"></div>
Synch process PHP
if(count($this->Contacts) > 0)
{
//GET CONTACTS ALIASES
$result = $this->GetContacts_aliases($folderPath);
if($result) {
echo '<script>UpdatePBar(10)</script>';
flush();
//SYNCH CONTACTS
$result = $this->synch_Contacts();
echo '<script>UpdatePBar(20)</script>';
flush();
if ($result) {
//SYNCH MESSAGES
$result = $this->synch_Messages($folderPath);
echo '<script>UpdatePBar(50)</script>';
flush();
if ($result) {
//SYNCHING SUCCESSFULLY COMPLETED
$log = "Synching of Messages Complete without errors. <br><br>";
$this->log = $this->log . $log;
//UPDATE LAST SYNCHED
$result = $this->UpdateLastSynched();
echo '<script>UpdatePBar(70)</script>';
flush();
if (!$result) {
//Update lastSynched failed
$log = "Updating lastSynched failed! <br><br>";
$this->log .= $log;
} else {
$log = "Updated Last Synched date stamp without errors <br><br>";
$this->log .= $log;
//ARCHIVE LOGS
$result = $this->ArchiveLogs($folderPath);
echo '<script>UpdatePBar(100)</script>';
flush();
if ($result) {
$log = "Archiving of log files successful!<br><br>";
$this->log .= $log;
} else {
$log = "Archiving of log files unsuccessful.<br><br>";
$this->log .= $log;
}
}
} else {
...
Thank you for your time
I think you should do that trough recursive ajax calls.
create a file on php that returns the percentage;
Example: getPercentage.php
<?
//do your stuff
echo $PERCENTAGE;
?>
Then on jquery:
<script>
readPHP();
function readPHP () {
var file="getPercentage.php";
$.ajax({
url: file,
cache: false,
success: function (data , status ) {
percentage=data;
if (percentage < 100)
{
$("#progressbar").progressbar({
value:percentage
})
setTimeout(readPHP(),1000);
}
else
{
$("#progressbar").progressbar({
value:percentage
})
}
}
})
}
</script>
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
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];
}