JSON data Post to server in Titanium for Android / iOS - javascript

I'm trying post my JSON data to server but it fails when i submit the data. it gives me error code 403. i tried this method in ADT for android it worked. it's not working on titanium only.
Here's my code.
function postData() {
Ti.API.info("JSON Data :" + JSONStringData);
var url = "http://www.vrsweb.in/hotels/admin/ws/orderItems.php";
var xhrpost = Titanium.Network.createHTTPClient();
xhrpost.setTimeout(5000);
xhrpost.open('POST', url);
xhrpost.setRequestHeader("Content-Type", "application/json");
xhrpost.setRequestHeader('charset', 'utf-8');
xhrpost.setRequestHeader("enctype", "multipart/form-data");
xhrpost.send(JSONStringData);
xhrpost.onerror = function(e) {
Ti.API.debug(e.error);
if (platform == 'android') {
var toast = Titanium.UI.createNotification({
message : 'Cannot Connect to server please check your internet Connection!',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
}
if (platform == 'iphone') {
alert('Cannot Connect to server please check your internet Connection!');
}
Ti.API.info("Status code :" + xhrpost.status);
};
xhrpost.onload = function() {
if (xhr.status == 200) {
Ti.API.info("XHR Status : " + xhrpost.status);
data = JSON.parse(this.responseText);
Ti.API.info("Response from server :" + data);
if (platform == 'android') {
var toast = Titanium.UI.createNotification({
message : 'Table booked Successfully!',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
}
if (platform == 'iphone') {
alert('Table booked Successfully!');
}
} else {
Ti.API.info("XHR Status : " + xhrpost.status);
}
};
}
I don't understand what am i doing wrong.
And i am Collecting data through JSON Get Method from the server and adding it to array. Converting that array into JSON and posting it to server.
Here's how i get Order id from server and saving it to array.
aButton.addEventListener('click', function() {
name = textUser.value;
qty = textPass.value;
price = textConfirmPass.value;
type = textEmail.value;
var url = "http://vrsweb.in/hotels/admin/ws/placeOrder.php?tName=" + id + "&wName=" + logName;
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(5000);
//xhr.autoEncodeUrl = false;
xhr.open('POST', url);
xhr.setRequestHeader('User-Agent', 'My User Agent');
xhr.send();
xhr.onerror = function(e) {
Ti.API.debug(e.error);
var toast = Titanium.UI.createNotification({
message : 'Error! Can not book table! ',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
Ti.API.info("Status code :" + xhr.status);
};
xhr.onload = function() {
if (xhr.status == 200) {
Ti.API.info("XHR Status : " + xhr.status);
oID = JSON.parse(this.responseText);
Ti.API.info("Response from server :" + oID);
var id = oID;
tempData = {
oId : id,
itemName : name,
qtyPerPlate : qty,
qtyPerKg : '0',
pricePerPlate : price,
pricePerKg : '0',
type : type
};
arrayOBJ.push(tempData);
orderData = {
Item : arrayOBJ
};
JSONStringData = JSON.stringify(orderData);
Ti.API.info("Data Added :" + orderData);
var toast = Titanium.UI.createNotification({
message : 'Added Data!',
duration : Titanium.UI.NOTIFICATION_DURATION_SHORT
});
toast.show();
} else {
Ti.API.info("XHR Status : " + xhr.status);
}
};
Ti.API.info("id :" + id);
Ti.API.info("name :" + logName);
});

I got it working. Here's what i changed.
xhrpost.setRequestHeader('User-Agent', 'My User Agent');
xhrpost.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

There is no need to set charset and enctype so remove it and then try to call.

Related

Sending ajax parameter to PHP script

I am working on a file drag and drop, and would like to use the same PHP page. I want to trigger the PHP script page using an action variable so it will go into the following if statement:
..
elseif ($_POST['action'] == 'uploadFile')
{
TrackEvent('CHANNEL_ACTIVATE');
echo "upload file";
}
I have an ajax call that is triggered using ondrop:
var data = new FormData();
data.append('action', 'uploadFile');
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.open('POST', 'channelEdit.php');
request.send(data);
$(this).unbind('click').click(function (e) {
});
$( "#fileList" ).trigger( "click" );
while you are sending post data in ajax you have to add setRequestHeader in request
So change your script as below :
var data = new FormData();
data.append('action', 'uploadFile');
var request = new XMLHttpRequest();
request.open('POST', 'channelEdit.php');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //<------Add this line
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.send(data);
$(this).unbind('click').click(function (e) {
});
$( "#fileList" ).trigger( "click" );

TinyMCE: Show error message on image uploads

I am able to implement the image upload example found in the documentation of TinyMCE:
https://www.tinymce.com/docs/advanced/php-upload-handler/
My question is how can I show the user a specific error message when an error occurs? For example, if I upload an invalid file type, it only shows a generic 500 error message like this:
How can I show a more specific error message to the user like
"Invalid extension"?
Hi need to write your custom images_upload_handler.
In settings add this lines :
images_upload_handler : function handler(blobInfo, success, failure, progress) {
{
var valid_extensions = ['png','jpg']
var ext, extensions;
extensions = {
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/gif': 'gif',
'image/png': 'png'
};
ext = extensions[blobInfo.blob().type.toLowerCase()] || 'dat';
//add your extension test here.
if( valid_extensions.indexOf(ext) == -1){
failure("Invalid extension");
return;
}
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.open('POST', settings.url);
xhr.withCredentials = settings.credentials;
xhr.upload.onprogress = function(e) {
progress(e.loaded / e.total * 100);
};
xhr.onerror = function() {
failure("Image upload failed due to a XHR Transport error. Code: " + xhr.status);
};
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure("HTTP Error: " + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != "string") {
failure("Invalid JSON: " + xhr.responseText);
return;
}
success(pathJoin(settings.basePath, json.location));
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
}

Adobe DPS Web Viewer Authentication

I'm attempting to use Adobe's Digital Publishing Suite Web Viewer. I've set up my Web Viewer correctly - it is working within my website. However, it is not authenticating that each user has access to the folio that the Web Viewer is accessing. Adobe has a sort of documentation on how to do this, but their documentation seems lacking. It seems as if Adobe is asking me to get users' username and password to Adobe - but that can't be right. I doubt Adobe would invite phising. But that isn't the only point I'm lost on.
My current script is as follows:
var wvQueryParamGroups = location.search.match(/[?&^#]wv=(s[\/%\-.\w]+)/),
wvQueryParam = wvQueryParamGroups && wvQueryParamGroups.length === 2 ? decodeURIComponent(wvQueryParamGroups[1]) : null;
function loadXMLDoc(url, successCallback, failCallback) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlhttp.responseText, "application/xml");
successCallback(xmlDoc);
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 0) {
alert("unsuccessful cross-domain data access attempt?");
failCallback(xmlhttp.status);
} else if (xmlhttp.readyState == 4) {
failCallback(xmlhttp.status);
} else {
console.log('readystate=' + xmlhttp.readyState + ', status=' + xmlhttp.status);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function directEntitlementSignIn(directEntitlementURL, emailAddress, password, appID, authTokenSuccess, authTokenFail) {
var response;
if (!authTokenSuccess || !authTokenFail) {
throw new Error('Callbacks are required: ');
}
loadXMLDoc(directEntitlementURL + '?emailAddress=' + emailAddress + '&password=' + password + '&appId=' + appID,
handleToken = function (data) {
token = data.documentElement.childNodes[0].innerHTML;
authTokenSuccess(token);
}
);
}
function onAuthTokenSuccess(token) {
alert(token);
// pass the token into the Authenticator class's login method
}
function onAuthTokenFail(status) {
alert("fail: " + status);
// prompt the user to try logging in again
}
function signIn(emailAddress, password) {
var deAPIURL = 'http://127.0.0.1/hostDemos r27/authHard/test.php';
var emailAddress; // user's login ID.....get from form
var password; // user's password ... get from form
var appID = 'com.publisher.magazine';
directEntitlementSignIn(deAPIURL, emailAddress, password, appID, onAuthTokenSuccess, onAuthTokenFail);
}
function eventCallback(ev) {
if (ev.eventType == "paywall") {
return false;
}
if (ev.eventType == "metadata") {
return true;
}
console.log(ev);
return true;
}
function errorCallback (message) {
console.log(message);
return true;
}
function redirectCallbackHandler (message) {
console.log(message);
}
var wv_appName = "Professional Roofing";
var wv_accountID = Account_ID_Is_Here; //Hiding account ID purposely
var wv_folio = "August 2014 Issue";
var wv_article = "Cover";
var wv_url = '/s/' + wv_appName + '/' + wv_accountID + '/' + wv_folio + '/' + wv_article + '.html';
console.log(wv_url);
var bridge = adobeDPS.frameService.createFrame({
boolIsFullScreen : true,
parentDiv : 'mainContainer',
wrapperClasses : 'uniqueFrame',
iframeID : 'demoFrame',
accountIDs : wv_accountID,
wvParam : wvQueryParam ? wvQueryParam : wv_url,
curtainClasses : 'mask hidden',
eventCallback : eventCallback,
errorCallback : errorCallback,
redirectCallback : redirectCallbackHandler
});
Adobe doesn't need your username and password, they need an authentication token.
To make it work you need:
Implement the Direct Entitlements API
Ask you account representative in Adobe to create an integrator id
After that you need to create an authenticator:
auth = adobeDPS.authenticationService.createAuthenticator(strAccountID, strIntegratorID);
And pass to it the authToken
auth.login(token, successCalck, errorCallback)

html5 upload multiple files with javascript

here is the upload logic in js
var upload = function(){
if(_file.files.length === 0){
return;
}
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.upload.addEventListener('progress', function(e){
_progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%';
}, false);
request.open('POST', 'upload.php');
request.send(data);
}
I run the function every time user selected something, but I only got the first file if user selected multiple files.
That's because you're only adding the first file to your data object:
data.append('SelectedFile', _file.files[0]);
You need to add all your files in the _file.files collection
Something like:
for(var i = 0 ; i < _file.files.length; i++ ) {
data.append('SelectedFile'+i, _file.files[i]);
}
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
Instead of this code, try something like this:
var data = new FormData();
for (var i in _file.files) data.append('SelectedFile'+i, _file.files[i]);

file upload processing file from xhr to web api

I'm using the following code to upload file to the server,
Javascript:
function FileUpload(ServerName) {
alert("Entering File Change...");
var file = this.file1[0];
alert("File Change");
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this
xhr.addEventListener('progress', function(e) {
alert("progress");
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if ( xhr.upload ) {
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
xhr.open('post', "http://localhost:49868/UploadFile/" + ServerName, true);
xhr.send(file);
}
Web api code:
[HttpPost]
[ActionName("UploadFile")]
public HttpResponseMessage UploadFile(string servername)
{
try
{
HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var httpRequest = HttpContext.Current.Request;
HttpResponseMessage result = null;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();
// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
//var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs("C:\\Users\\Desktop\\New folder (4)\\" + postedFile.FileName);
//files.Add(filePath);
//File.Copy(filePath, RootPath + postedFile.FileName);
//File.Delete(filePath);
}
// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
catch (Exception ex)
{
return null;
}
}
My Question is how to handle this on the server side, i.e in the web api, how to get the file there on the server and store it in some specific location?
Now the httpRequest.Files is returned null, where to get the file and save it?

Categories