MobileFirst 6.3 invoking backend service created adapter procedure - soap

I am having a hard time working out how to invoke my adapter which MobileFirst has created for me using the Discover Back End Service feature.
I created my adapter, and I am not using the following code to try and call it:
function callService(){
alert("Calling into Backend");
var options = {
onSuccess : loadSuccess,
onFailure : loadFailure,
invocationContext: {}
};
var params = {"itemRequiredReference":10};
var invocationData = {
adapter : 'SoapAdapter1',
procedure : 'inquireSingleService_inquireSingle',
parameters : [params]
};
WL.Client.invokeProcedure(invocationData, options);
}
But this does not seem to work. I get the error :
{"status":200,"invocationContext":{},"invocationResult":{"statusCode":500,"errors":[],"isSuccessful":true,"Envelope":{"SOAP-ENV":"http://schemas.xmlsoap.org/soap/envelope/","Body":{"Fault":{"":"","detail":{"CICSFault":{"CDATA":"DFHPI1010 02/02/2015 22:11:37 GENAPPA1 CPIH 00518 XML generation failed. A conversion error (INVALID_ZONED_DEC) occurred when converting field itemReferenceNumber for WEBSERVICE inquireSingleWrapper.","xmlns":"http://www.ibm.com/software/htp/cics/WSFault"}},"faultcode":"SOAP-ENV:Server","faultstring":"Conversion to SOAP failed"}},"soap":"http://schemas.xmlsoap.org/soap/envelope/"},"statusReason":"Internal Server Error","responseHeaders":{"Date":"Mon, 02 Feb 2015 22:11:37 GMT","Content-Length":"000000000000608","Content-Type":"text/xml; charset=UTF-8","Connection":"Keep-Alive","Server":"IBM_CICS_Transaction_Server/5.2.0(zOS)"},"warnings":[],"responseTime":578,"totalTime":581,"info":[]}}
The generated adapter code looks like this :
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Generated code - Do not edit //
// //
// This is a SOAP adapter that was auto-generated by Worklight for invocation of specific SOAP-based services. //
// The adapter may invoke more than one service as long as they are all from the same enpdpoint (server host). //
// Each adapter procedure matches a single operation for the same endpoint server and accepts: //
// params - Serialized JSON representation of the XML-based SOAP body to be sent to the service //
// headers - Custom HTTP headers to be specified when invoking the remote service. It is a JSON object with //
// the headers names and values. E.g. { 'name1' : 'value1', 'name2' : 'value2' } //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function inquireSingleService_inquireSingle(params, headers){
var soapEnvNS = '';
// The value of 'soapEnvNS' was set based on the version of the SOAP to be used (i.e. 1.1 or 1.2).
soapEnvNS = 'http://schemas.xmlsoap.org/soap/envelope/';
// The following mappings object was autogenerated from the XML schema of the input message to the service.
// It is being used to support a params JSON when invoking this procedure that don't specify the namespace
// prefix nor specifying whether a property is attribute or not.
//
// The 'roots' object has the list of message parts within the invocation SOAP message. Each entry has a
// mapping between the root element name and its namespace prefix and type.
// Each root object may define 'nsPrefix' and 'type'. Both are optional - If there is no need for a NS prefix
// then the 'nsPrefix' should not be specified. If the element is a simple type then the 'type' should not be
// specified.
//
// The 'types' object has a list of types each defining the children of the type and the definition of each
// child. If the child is a complext type, the 'type' property has a reference to the child type definition.
// Each child object may define:
// 'nsPrefix' (optional) - Holds the namespace prefix to be attached to the element. If there is no need for
// a NS prefix then the 'nsPrefix' should not be specified.
// 'type' (optional) - If the element is a simple type then the 'type' should not be specified. If it is an
// attribute then 'type' should have the value of '#'. Otherwise the value of 'type' is a reference to the
// type definition within the 'types' object.
var mappings = {
roots: {
'inquireSingleRequest': { nsPrefix: 'reqns', type: 'reqns:inquireSingleRequest' }
},
types: {
'reqns:inquireSingleRequest': {
children: [
{'itemRequiredReference': { nsPrefix: 'reqns' }}
]
}
}
};
var namespaces = 'xmlns:resns="http://www.exampleApp.inquireSingleResponse.com" xmlns:reqns="http://www.exampleApp.inquireSingleRequest.com" xmlns:tns="http://www.exampleApp.inquireSingleResponse.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
var request = buildBody(params, namespaces, mappings, soapEnvNS);
var soapAction = '';
return invokeWebService(request, headers, soapAction);
}
function buildBody(params, namespaces, mappings, soapEnvNS){
var body =
'<soap:Envelope xmlns:soap="' + soapEnvNS + '">\n' +
'<soap:Body>\n';
var fixedParams = {};
for (var paramName in params) {
if (mappings['roots'][paramName]) { //There is mapping for this param
var root = mappings['roots'][paramName];
var name = paramName;
if (root['nsPrefix'])
name = root['nsPrefix'] + ':' + paramName;
fixedParams[name] = handleMappings(params[paramName], root['type'], mappings['types']);
}
else {
fixedParams[paramName] = params[paramName];
}
}
body = jsonToXml(fixedParams, body, namespaces);
body +=
'</soap:Body>\n' +
'</soap:Envelope>\n';
return body;
}
function handleMappings(jsonObj, type, mappings) {
var fixedObj = {};
var typeMap = mappings[type]['children']; //Get the object that defines the mappings for the specific type
// loop through the types and see if there is an input param defined
for(var i = 0; i < typeMap.length; i++) {
var childType = typeMap[i];
for(var key in childType) {
if(jsonObj[key] !== null) { // input param exists
var childName = key;
if (childType[key]['nsPrefix'])
childName = childType[key]['nsPrefix'] + ':' + key;
if (!childType[key]['type']) //Simple type element
fixedObj[childName] = jsonObj[key];
else if (typeof jsonObj[key] === 'object' && jsonObj[key].length != undefined) { //Array of complex type elements
fixedObj[childName] = [];
for (var i=0; i<jsonObj[key].length; i++)
fixedObj[childName][i] = handleMappings(jsonObj[key][i], childType[key]['type'], mappings);
}
else if (typeof jsonObj[key] === 'object') //Complex type element
fixedObj[childName] = handleMappings(jsonObj[key], childType[key]['type'], mappings);
else if (childType[key]['type'] == '#') //Attribute
fixedObj['#' + childName] = jsonObj[key];
}
}
}
return fixedObj;
}
function getAttributes(jsonObj) {
var attrStr = '';
for(var attr in jsonObj) {
if (attr.charAt(0) == '#') {
var val = jsonObj[attr];
attrStr += ' ' + attr.substring(1);
attrStr += '="' + xmlEscape(val) + '"';
}
}
return attrStr;
}
function jsonToXml(jsonObj, xmlStr, namespaces) {
var toAppend = '';
for(var attr in jsonObj) {
if (attr.charAt(0) != '#') {
var val = jsonObj[attr];
if (typeof val === 'object' && val.length != undefined) {
for(var i=0; i<val.length; i++) {
toAppend += "<" + attr + getAttributes(val[i]);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val[i], toAppend);
toAppend += "</" + attr + ">\n";
}
}
else {
toAppend += "<" + attr;
if (typeof val === 'object') {
toAppend += getAttributes(val);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val, toAppend);
}
else {
toAppend += ">" + xmlEscape(val);
}
toAppend += "</" + attr + ">\n";
}
}
}
return xmlStr += toAppend;
}
function invokeWebService(body, headers, soapAction){
var input = {
method : 'post',
returnedContentType : 'xml',
path : '/exampleApp/inquireSingleWrapper',
body: {
content : body.toString(),
contentType : 'text/xml; charset=utf-8'
}
};
WL.Logger.error("ANDY:"+body.toString());
//Adding custom HTTP headers if they were provided as parameter to the procedure call
//Always add header for SOAP action
headers = headers || {};
if (soapAction != 'null')
headers.SOAPAction = soapAction;
input['headers'] = headers;
return WL.Server.invokeHttp(input);
}
function xmlEscape(obj) {
if(typeof obj !== 'string') {
return obj;
}
return obj.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, '&apos;')
.replace(/</g, '<')
.replace(/>/g, '>');
}
I am a little lost - the parameters parameter on the invocationData object is what needs to be fixed - but its really very unclear what mapping as a json object I am meant to be passing as a parameter. Can somebody please show me what parameter I need to pass to set itemRequiredReference to the number 30.
If you need the WSDL I used to generate the service this is what I used : http://we.tl/fHgRos3f4e
This is the service being invoked from soapUI #idan :

Well I finally found a useful documentation page here :http://www-01.ibm.com/support/knowledgecenter/SSHS8R_6.3.0/com.ibm.worklight.dev.doc/dev/c_invocation_generated_soap_adapter.html
and the solution was to set parameters variable to :
var params = {"inquireSingleRequest": {"itemRequiredReference": "10"}}
var invocationData = {
adapter : 'SoapAdapter1',
procedure : 'inquireSingleService_inquireSingle',
parameters : [params]
};
This allowed it to work perfectly.

Related

Enterprise Architect - How to set column key to Autonum?

I have a bunch of tables with Id int primary keys. However, I forgot to set AutoNum to True in the UI. Since changing all hundreds of tables is tedious, how can I set this property for all Id columns?
I have built a script that runs through each table and detects the Id column:
var package as EA.Package;
package = Repository.GetTreeSelectedPackage();
var tablesEnumerator = new Enumerator(package.Elements);
while (!tablesEnumerator.atEnd()) {
var table as EA.Element;
table = tablesEnumerator.item();
var methodsEnumerator = new Enumerator(table.Methods);
while (!methodsEnumerator.atEnd()) {
var method as EA.Method;
method = methodsEnumerator.item();
if (method.Name !== "Id") { continue; }
Session.Output(method.Name);
// Now what?!
}
}
I have searched for AutoNum in EnterpriseArchitect docs and APIs, but was unable to find suitable references.
According to Autonum in Column Properties inaccessible you can actually change the AutoNum behaviour via API with the means of TaggedValues. So there is no need of direct SQL updates to the database.
Setting the tagged values property and AutoNum on the Id attribute (not the method of the table seems to do the magic. It tried it via the builtin script engine and it works:
Before running the script
After running the script
The update script
!INC Local Scripts.EAConstants-JScript
function main()
{
var package = Repository.GetTreeSelectedPackage();
var elements as EA.Collection;
elements = package.Elements;
Session.Output("Elements Count " + elements.Count);
for ( var ec = 0 ; ec < elements.Count ; ec++ )
{
var element as EA.Element;
element = elements.GetAt(ec);
if("Table" != element.MetaType) continue;
Session.Output("Element: Name '" + element.Name + "' [" + element.ElementGUID + "] '" + element.MetaType + "'.");
var attributes as EA.Collection;
attributes = element.Attributes;
for ( var ac = 0; ac < attributes.Count ; ac++)
{
var attribute as EA.Attribute;
attribute = attributes.GetAt(ac);
if("Id" != attribute.Name) continue;
Session.Output("Attribute: Name '" + attribute.Name + "' [" + attribute.AttributeGUID + "] in element '"+ element.Name + "' [" + element.MetaType + "].");
var hasTvProperty = false;
var hasTvAutonum = false;
var taggedValues as EA.Collection;
taggedValues = attribute.TaggedValues;
Session.Output("TaggedValues: Count " + taggedValues.Count);
for ( var tc = 0; tc < taggedValues.Count; tc++)
{
var taggedValue as EA.TaggedValue;
taggedValue = taggedValues.GetAt(tc);
if("property" != taggedValue.Name && "AutoNum" != taggedValue.Name) continue;
Session.Output("TaggedValue: Name '" + taggedValue.Name + "'. Value '" + taggedValue.Value + "'");
if("property" != taggedValue.Name)
{
taggedValue.Value = "AutoNum=1;StartNum=1;Increment=1;";
taggedValue.Update();
element.Update();
hasTvProperty = true;
}
if("AutoNum" != taggedValue.Name)
{
taggedValue.Value = "True";
taggedValue.Update();
element.Update();
hasTvAutonum = true;
}
}
if(!hasTvProperty)
{
var tv = taggedValues.AddNew("property", "AutoNum=1;StartNum=1;Increment=1;");
tv.Update();
element.Update();
}
if(!hasTvAutonum)
{
var tv = taggedValues.AddNew("AutoNum", "True");
tv.Update();
element.Update();
}
break;
}
}
}
main();
Content of the t_attributetags table

algolia/instantsearch: connectMenu refine() remove current refined value

Is there any way to REMOVE a refined value with connectMenu’s connector?
These are the things I tried that did not work:
passing an empty string refine('')
passing a null value refine(null)
passing a false value refine(false)
passing no parameter refine()
The reason why I’d like to do this is because otherwise currentRefinedValues widget shows an attribute as refined even if it’s not.
var customMenuRenderFn = function (renderParams, isFirstRendering) {
var container = renderParams.widgetParams.containerNode;
var title = renderParams.widgetParams.title || 'dropdownMenu';
var templates = renderParams.widgetParams.templates;
var hideIfIsUnselected = renderParams.widgetParams.hideIfIsUnselected || false;
var cssClasses = renderParams.widgetParams.cssClasses || "";
if (isFirstRendering)
{
$(container).append(
(templates.header || '<h1>' + renderParams.widgetParams.attributeName + '</h1>') +
'<select class="' + cssClasses.select + '">' +
'<option value="__EMPTY__">Tutto</option>' +
'</select>'
).hide();
var refine = renderParams.refine;
if (! hideIfIsUnselected)
{
$(container).show();
}
else
{
$(hideIfIsUnselected).find('select').on('items:loaded', function () {
if (isFirstRendering) {
var valueToCheck = $(hideIfIsUnselected).find('select').val();
$(container).toggle(valueToCheck !== '__EMPTY__');
$(container).find('select').off('items:loaded');
}
});
$(hideIfIsUnselected).find('select').on('change', function (event) {
var value = event.target.value === '__EMPTY__' ? '' : event.target.value;
if (value === '') {
refine();
}
$(container).toggle(value !== '');
});
}
$(container).find('select').on('change', function (event) {
var value = event.target.value === '__EMPTY__' ? '' : event.target.value;
refine(value);
});
}
function updateHits (hits)
{
var items = renderParams.items;
optionsHtml = ['<option class="' + cssClasses.item + '" value="__EMPTY__" selected>Tutto</option>']
.concat(
items.map(function (item) {
return `<option class="${cssClasses.item}" value="${item.value}" ${item.isRefined ? 'selected' : ''}>
${item.label} (${item.count})
</option>`;
})
);
$(container).find('select').html(optionsHtml);
$(container).find('select').trigger('items:loaded');
}
if (hideIfIsUnselected && $(hideIfIsUnselected).val() !== '__EMPTY__') {
updateHits(renderParams.items);
} else if (! hideIfIsUnselected) {
updateHits(renderParams.items);
}
}
var dropdownMenu = instantsearch.connectors.connectMenu(customMenuRenderFn);
The refine function actually toggles the value (setting it if not set, or unsetting if set). If you want to unselect any item in the menu, you need to find the currently selected value and use refine on it.
connectMenu(function render(params, isFirstRendering) {
var items = params.items;
var currentlySelectedItem = items.find(function isSelected(i) {
return i.isRefined;
});
params.refine(currentlySelectedItem);
});
This example won't solve your code completely, but it shows how to find the currently selected item and unselect it.

Resolving Promise Angular 2

I have the following problem.
In a function I have a promise as a return type. This function is in the class Hierarchy.
updateNodeValues(entity: String, data: {}): Promise<any>{
let jsonBody = JSON.stringify(data);
let url = environment.endpointCore + '/api/' + entity + '/' + data['id'];
return this.http.put(url, jsonBody, this.options)
.toPromise()
.then(response => {
return response;
})
.catch(this.handleError);
}
This function is in class node.
onSubmit(): void{
var currentForm = this.form.value;
var entityName = this.inflection.classify(this.node.type).toLowerCase();
var requiredData = {};
for(var i = 0; i < this.formItems.length; i++){
this.formItems[i].value = currentForm[Object.keys(currentForm)[i]];
}
for(var i=0; i<this.formItems.length; i++){
requiredData[this.globalService.camelize(this.formItems[i].label)] = this.formItems[i].value
}
Promise.resolve(this.hierarchyService.updateNodeValues(entityName, requiredData)).then(response => {
alert(response.ok);
if(response.ok){
this.globalService.showSuccessMessage('Values updated');
this.refreshGui(requiredData);
}
});
this.editMode = false;
}
The problem is that when i try to resolve promise and invoke this.refreshGui(requireddata) nothing is happening. I have read about how the fat arrow is preserving the 'context' of this, and I do not understand why invoking this method is not doing anything, while invoking successMessage produces expected outcome.
The method that I am invoking looks like this, and it is also in the class node.
private refreshGui(data: {}){
this._node.data = data;
this.objectProperties = new Array();
this.nodeChildren = new Array();
for (var property in data) {
var propertyValue = data[property];
if (propertyValue instanceof Array) {
this.nodeChildren.push({label: property, value: "total: ".concat(propertyValue.length.toString())});
} else {
this.objectProperties.push({label: property, value: propertyValue});
}
}
}
The solution that I found to be working was to implement custom event. The problem was that within the async callback resolution, the context of what this is would "get lost". The fat arrow enabled me to invoke class method with this, but the properties within the would be "lost". Because of this reason I have took the logic from the method, and put it in the callback part and set expected and needed results in some variable. This variable was passed to my custom event and set to class variable in the custom event handler appropriately.

How to pass parameters to a MobileFirst HTTP adapter

I need to run an HTTP adapter to access a SOAP WSDL service. It has 2 fields userid and password.
I have auto generated the adapter by discover backend services. Can anyone guide me to how to pass values from adapter initially to access the service?
function userlogin_ep_process(params, headers){
var soapEnvNS = '';
soapEnvNS = 'http://schemas.xmlsoap.org/soap/envelope/';
var mappings = {
roots: {
'process': { nsPrefix: 'client', type: 'client:process' }
},
types: {
'client:process': {
children: [
{'username': { nsPrefix: 'client' }},
{'userpwd': { nsPrefix: 'client' }}
]
}
}
};
var namespaces = 'xmlns:client="http://xmlns.oracle.com/InternetMobile/AbsManagement/BPELProcessUserLogin" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" ';
var request = buildBody(params, namespaces, mappings, soapEnvNS);
var soapAction = 'process';
return invokeWebService(request, headers, soapAction);
}
function buildBody(params, namespaces, mappings, soapEnvNS){
var body =
'<soap:Envelope xmlns:soap="' + soapEnvNS + '">\n' +
'<soap:Body>\n';
var fixedParams = {};
for (var paramName in params) {
if (mappings['roots'][paramName]) { //There is mapping for this param
var root = mappings['roots'][paramName];
var name = paramName;
if (root['nsPrefix'])
name = root['nsPrefix'] + ':' + paramName;
fixedParams[name] = handleMappings(params[paramName], root['type'], mappings['types']);
}
else {
fixedParams[paramName] = params[paramName];
}
}
body = jsonToXml(fixedParams, body, namespaces);
body +=
'</soap:Body>\n' +
'</soap:Envelope>\n';
return body;
}
function handleMappings(jsonObj, type, mappings) {
var fixedObj = {};
var typeMap = mappings[type]['children']; //Get the object that defines the mappings for the specific type
// loop through the types and see if there is an input param defined
for(var i = 0; i < typeMap.length; i++) {
var childType = typeMap[i];
for(var key in childType) {
if(jsonObj[key] !== null) { // input param exists
var childName = key;
if (childType[key]['nsPrefix'])
childName = childType[key]['nsPrefix'] + ':' + key;
if (!childType[key]['type']) //Simple type element
fixedObj[childName] = jsonObj[key];
else if (typeof jsonObj[key] === 'object' && jsonObj[key].length != undefined) { //Array of complex type elements
fixedObj[childName] = [];
for (var i=0; i<jsonObj[key].length; i++)
fixedObj[childName][i] = handleMappings(jsonObj[key][i], childType[key]['type'], mappings);
}
else if (typeof jsonObj[key] === 'object') //Complex type element
fixedObj[childName] = handleMappings(jsonObj[key], childType[key]['type'], mappings);
else if (childType[key]['type'] == '#') //Attribute
fixedObj['#' + childName] = jsonObj[key];
}
}
}
return fixedObj;
}
function getAttributes(jsonObj) {
var attrStr = '';
for(var attr in jsonObj) {
if (attr.charAt(0) == '#') {
var val = jsonObj[attr];
attrStr += ' ' + attr.substring(1);
attrStr += '="' + xmlEscape(val) + '"';
}
}
return attrStr;
}
function jsonToXml(jsonObj, xmlStr, namespaces) {
var toAppend = '';
for(var attr in jsonObj) {
if (attr.charAt(0) != '#') {
var val = jsonObj[attr];
if (typeof val === 'object' && val.length != undefined) {
for(var i=0; i<val.length; i++) {
toAppend += "<" + attr + getAttributes(val[i]);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val[i], toAppend);
toAppend += "</" + attr + ">\n";
}
}
else {
toAppend += "<" + attr;
if (typeof val === 'object') {
toAppend += getAttributes(val);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val, toAppend);
}
else {
toAppend += ">" + xmlEscape(val);
}
toAppend += "</" + attr + ">\n";
}
}
}
return xmlStr += toAppend;
}
function invokeWebService(body, headers, soapAction){
var input = {
method : 'post',
returnedContentType : 'xml',
path : '/soa-infra/services/Mobile/AbsManagement/userlogin_ep',
body: {
content : body.toString(),
contentType : 'text/xml; charset=utf-8'
}
};
//Adding custom HTTP headers if they were provided as parameter to the procedure call
//Always add header for SOAP action
headers = headers || {};
if (soapAction != 'null')
headers.SOAPAction = soapAction;
input['headers'] = headers;
return WL.Server.invokeHttp(input);
}
function xmlEscape(obj) {
if(typeof obj !== 'string') {
return obj;
}
return obj.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, '&apos;')
.replace(/</g, '<')
.replace(/>/g, '>');
}
To invoke the adapter and pass the parameters you need to call WL.Client.invokeProcedure in your particular case you can use
var invocationData = {
adapter: 'YOUR_ADAPTER_NAME',
procedure: 'userlogin_ep_process',
parameters: {
process: {
username: 'YOUR_USERNAME',
userpwd: 'YOUR_PASSWORD'
}
}
};
WL.Client.invokeProcedure(invocationData, {
onSuccess: yourSuccessFunction,
onFailure: yourFailureFunction
});

jquery.jeditable.ajaxupload.js how to send file?

maybe somebody can to explain me why I can't send file, maybe needed additional script or something els?
/*
* Ajaxupload for Jeditable
*
* Copyright (c) 2008-2009 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Depends on Ajax fileupload jQuery plugin by PHPLetter guys:
* http://www.phpletter.com/Our-Projects/AjaxFileUpload/
*
* Project home:
* http://www.appelsiini.net/projects/jeditable
*
* Revision: $Id$
*
*/
$.editable.addInputType('ajaxupload', {
/* create input element */
element : function(settings) {
settings.onblur = 'ignore';
var input = $('<input type="file" id="upload" name="upload" />');
$(this).append(input);
return(input);
},
content : function(string, settings, original) {
/* do nothing */
},
plugin : function(settings, original) {
var form = this;
form.attr("enctype", "multipart/form-data");
$("button:submit", form).bind('click', function() {
//$(".message").show();
// Modification to include original id and submitdata in target's querystring
var queryString;
if ($.isFunction(settings.submitdata)) {
queryString = jQuery.param(settings.submitdata.apply(self, [self.revert, settings]));
} else {
queryString = jQuery.param(settings.submitdata);
}
if (settings.target.indexOf('?') < 0) {
queryString = '?' + settings.id + '=' + $(original).attr('id') + '&' + queryString;
} else {
queryString = '&' + settings.id + '=' + $(original).attr('id') + '&' + queryString;
}
settings.target += queryString;
// End modification
$.ajaxFileUpload({
url: settings.target,
secureuri:false,
// Add the following line
data : settings.submitdata,
fileElementId: 'upload',
dataType: 'html',
success: function (data, status) {
$(original).html(data);
original.editing = false;
},
error: function (data, status, e) {
alert(e);
}
});
return(false);
});
}
});
$(\".ajaxupload\").editable('/?action=upload_profile_photo', {
indicator : '<i class=\"fa fa-spinner fa-pulse\"></i>',
type : 'ajaxupload',
submit : 'Upload',
cancel : 'Cancel',
tooltip : \"Click to upload...\"
});
<p class=\"ajaxupload\" id=\"profile_photo\"><img class=\"img-thumbnail img-responsive\" src=\"http://www.in-elite.com/?action=no_image_text\" alt=\"\"></p>
how result its passed only
print_r($._GET)Array ( [action] => upload_profile_photo [id] =>
profile_photo ) print_r($._POST)Array ( [value] => 20150501_153530.jpg
[id] => profile_photo )
And question so, How to send file?
Ux I found the problem ;-)
I'm forgot to add one js file called jquery.ajaxfileupload.js
<script type=\"text/javascript\" src=\"/includes/JS/jquery.ajaxfileupload.js\" charset=\"utf-8\"></script>
And content of this jquery.ajaxfileupload.js file is
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data);
//jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})
Now everything ok and file are uploaded successfully.... Just needed to modified php script for which type of the data you need to upload