w2ui grid select line after delete - w2ui

in w2ui grid I want to select grid line after I delete a line below. Here is mine javascript code :
w2ui[ grd_obj.grid_id ].on( 'delete', function( event )
{
event.onComplete = function()
{
var min_ind = 100000
var sel = w2ui[ grd_obj.grid_id ].getSelection()
for ( var r in sel )
{
var ind = w2ui[ grd_obj.grid_id ].get( sel[ r ].recid, true )
min_ind = Math.min( ind, min_ind )
}
if ( event.phase == 'after' )
{
var ind = w2ui[ grd_obj.grid_id ].prevRow( min_ind )
var rcd = w2ui[ grd_obj.grid_id ].records[ ind ]
w2ui[ grd_obj.grid_id ].selectNone()
w2ui[ grd_obj.grid_id ].select( { recid: rcd[ grd_obj.grid_table.grid_key ], column: 0 } )
}
}
})
I can't find how to recatch "reload" after delete ... Debugging I'm seeing, that in "after" event .select() is working and can see that needful record is selectted. But, as I can understand, "delete" trigger "reload" of grid and mine selection dissapears ... :(
How to solve this problem ?
Server side database (mysql+php).
Thanks in advance ...
EDITED (SOLVED):
Found solution. Not sure that this is good, but it's working ... Did something llike that :
In own grid object added "grid_setRec" parameter. Then in "delete" event assign this value
w2ui[ grd_obj.grid_id ].on( 'delete', function( event )
{
event.onComplete = function()
{
var min_ind = 10000
var sel = w2ui[ grd_obj.grid_id ].getSelection()
for ( var r in sel )
{
var ind = w2ui[ grd_obj.grid_id ].get( sel[ r ].recid, true )
min_ind = Math.min( ind, min_ind )
}
if ( w2ui[ grd_obj.grid_id ].total > 0 )
{
var ind = w2ui[ grd_obj.grid_id ].prevRow( min_ind )
var rcd = w2ui[ grd_obj.grid_id ].records[ ind ]
grd_obj.grid_setRec = rcd[ grd_obj.grid_table.grid_key ]
}
}
})
In "load" event seeing this value :
w2ui[ grd_obj.grid_id ].on( 'load', function( event )
{
event.onComplete = function()
{
if ( grd_obj.grid_setRec != '' )
{
reload_callBack( grd_obj, grd_obj.grid_setRec )
grd_obj.grid_setRec = ''
}
}
})
reload_callBack function I'm alreday using as "reload" event callback, then adding new record to grid.
function reload_callBack( grd_obj, rcd_id )
{
setTimeout( function ()
{
w2ui[ grd_obj.grid_id ].selectNone()
w2ui[ grd_obj.grid_id ].select( { recid: rcd_id, column: 0 } )
var ind = w2ui[ grd_obj.grid_id ].get( parseInt( rcd_id ), true )
w2ui[ grd_obj.grid_id ].scrollIntoView( ind )
}, 100 )
}
Now it works as I wanted ... :)

Solved this problem, addign own variable for reload. "Delete" event triiger "load" event. Here I'm seeing need it reselect with callback function or not ...

Related

How reduce draw call in this sence? URP SRP Batcher

Unity2021.3.10f1, URP, SRP Batcher on
I created a 10x10x10 cube matrix in the sence.
The cube is a prefab. It 1:1:1 default size, with a SRP Batcher compatible shader.
Now 5000+ Batches in runtime. How can I reduce the batches?
source: https://gist.github.com/andrew-raphael-lukasik/df4a36ff2ad89078258fd653c422a021
// scr* https://gist.github.com/andrew-raphael-lukasik/df4a36ff2ad89078258fd653c422a021
using System.Collections.Generic;
using UnityEngine;
public class GpuInstancingForGameObjects : MonoBehaviour
{
[SerializeField] Camera _camera = null;
[SerializeField] MeshRenderer[] _meshRenderers = new MeshRenderer[0];
/// <summary>
/// Prefer "true" ☑ as "false" ☐ require updates every frame.
/// It is a good idea to keep lists of still and moving mesh renderers in a separate components.
/// </summary>
public bool meshesAreStill = true;
Dictionary<(Mesh mesh,Material material),(List<Transform> transforms,Bounds aabb)> _sources = new Dictionary<(Mesh,Material),(List<Transform>,Bounds)>();
Dictionary<(Mesh mesh,Material material),(Matrix4x4[] matrices,Bounds aabb)> _batches = new Dictionary<(Mesh,Material),(Matrix4x4[],Bounds)>();
Dictionary<int,Stack<Matrix4x4[]>> _freeMatrices = new Dictionary<int,Stack<Matrix4x4[]>>();
Plane[] _frustum = new Plane[6];
void Start ()
{
Initialize();
UpdateMatrices();
if( _camera==null ) _camera = Camera.main;
if( _camera==null )
{
Debug.LogError( "no camera, can't continue" , this );
enabled = false;
}
}
void Update ()
{
if( !meshesAreStill ) UpdateMatrices();
GeometryUtility.CalculateFrustumPlanes( _camera , _frustum );
foreach( var batch in _batches )
{
var meshMaterialPair = batch.Key;
var matricesAabbPair = batch.Value;
var aabb = matricesAabbPair.aabb;
if( GeometryUtility.TestPlanesAABB(_frustum,aabb) )
{
Graphics.DrawMeshInstanced(
mesh: meshMaterialPair.mesh ,
submeshIndex: 0 ,
material: meshMaterialPair.material ,
matrices: matricesAabbPair.matrices
);
}
}
}
#if UNITY_EDITOR
// void OnDrawGizmosSelected ()
void OnDrawGizmos ()
{
Initialize();
Gizmos.color = Color.yellow;
foreach( var source in _sources )
{
var transformsAabbPair = source.Value;
var aabb = transformsAabbPair.aabb;
Gizmos.DrawWireCube( aabb.center , aabb.size );
if( Application.isPlaying && !GeometryUtility.TestPlanesAABB(_frustum,aabb) )
UnityEditor.Handles.Label( aabb.center , "(out of camera view)" );
}
}
#endif
void Initialize ()
{
_sources.Clear();
foreach( var meshRenderer in _meshRenderers )
{
if( meshRenderer==null ) continue;
var meshFilter = meshRenderer.GetComponent<MeshFilter>();
if( meshFilter==null ) continue;
var mesh = meshFilter.sharedMesh;
if( mesh==null ) continue;
foreach( var material in meshRenderer.sharedMaterials )
{
if( !material.enableInstancing && Application.isPlaying )
{
Debug.LogWarning($"\"{material.name}\" material won't be rendered as it's <b>GPU Instancing</b> is not enabled",meshRenderer);
continue;
}
if( material==null ) continue;
var aabb = meshRenderer.bounds;
var meshMaterialPair = ( mesh , material );
if( _sources.ContainsKey( meshMaterialPair ) )
{
var transforms = _sources[meshMaterialPair].transforms;
transforms.Add( meshRenderer.transform );
var newAabb = _sources[meshMaterialPair].aabb;
newAabb.Encapsulate( aabb );
_sources[meshMaterialPair] = ( transforms , newAabb );
}
else
{
_sources.Add( meshMaterialPair , ( new List<Transform>(){ meshRenderer.transform } , aabb ) );
}
}
if( Application.isPlaying )
meshRenderer.enabled = false;
}
}
void UpdateMatrices ()
{
foreach( var batch in _batches )
{
var matricesAabbPair = batch.Value;
var matrices = matricesAabbPair.matrices;
if( _freeMatrices.ContainsKey( matrices.Length ) )
{
_freeMatrices[matrices.Length].Push( matrices );
}
else
{
var stack = new Stack<Matrix4x4[]>();
stack.Push( matrices );
_freeMatrices.Add( matrices.Length , stack );
}
}
_batches.Clear();
foreach( var source in _sources )
{
var meshMaterialPair = source.Key;
var transformsAabbPair = source.Value;
var transforms = transformsAabbPair.transforms;
int numTransforms = transforms.Count;
Matrix4x4[] matrices = null;
if( _freeMatrices.ContainsKey(numTransforms) && _freeMatrices[numTransforms].Count!=0 )
{
matrices = _freeMatrices[numTransforms].Pop();
}
else matrices = new Matrix4x4[ numTransforms ];
for( int i=0 ; i<numTransforms ; i++ )
matrices[i] = transforms[i].localToWorldMatrix;
_batches.Add( meshMaterialPair , ( matrices , transformsAabbPair.aabb ) );
}
}
}
This solution provides AABB frustum culling - it is not enough to optimize your voxels-like case but a starting point. If you consider these boxes to represent voxels then your next step would be to implement a voxel occlusion culling here (to hide boxes that are inside this shape).

CKE change blockqoute style

When i use this code in CKE Editor:
<blockquote>test
<blockquote>test</blockquote>
</blockquote>
can i change this:
Image 1
to this:
Image 2
Problem: The PN Messenger in our CMS reply the last message with blockquote in blockquote. And with several replies this is very confusing.
Your Code
<blockquote>test
<blockquote>test</blockquote>
</blockquote>
Updated
<blockquote>test</blockquote>
<blockquote>test</blockquote>
You want to display every blockquote in a new line. Try this
var array = document.getElementsByTagName('blockquote');
for(var i = 0; i < array.length; i++) {
array[i].savedContent = array[i].innerHTML;
array[i].style.margin = 0;
}
<head>
<title>Page Title</title>
</head>
<body>
<blockquote>test
<blockquote>test</blockquote>
</blockquote>
</body>
I insert your code here (line 24) Is that correct? But it do not change.
1/**
* #license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
( function() {
function noBlockLeft( bqBlock ) {
for ( var i = 0, length = bqBlock.getChildCount(), child; i < length && ( child = bqBlock.getChild( i ) ); i++ ) {
if ( child.type == CKEDITOR.NODE_ELEMENT && child.isBlockBoundary() )
return false;
}
return true;
}
var commandObject = {
exec: function( editor ) {
var state = editor.getCommand( 'blockquote' ).state,
selection = editor.getSelection(),
range = selection && selection.getRanges()[ 0 ];
if ( !range )
return;
// Rakibul Islam
var array = document.getElementsByTagName('blockquote');
for(var i = 0; i < array.length; i++) {
array[i].savedContent = array[i].innerHTML;
array[i].style.margin = 0;
}
var bookmarks = selection.createBookmarks();
// Kludge for https://dev.ckeditor.com/ticket/1592: if the bookmark nodes are in the beginning of
// blockquote, then move them to the nearest block element in the
// blockquote.
if ( CKEDITOR.env.ie ) {
var bookmarkStart = bookmarks[ 0 ].startNode,
bookmarkEnd = bookmarks[ 0 ].endNode,
cursor;
if ( bookmarkStart && bookmarkStart.getParent().getName() == 'blockquote' ) {
cursor = bookmarkStart;
while ( ( cursor = cursor.getNext() ) ) {
if ( cursor.type == CKEDITOR.NODE_ELEMENT && cursor.isBlockBoundary() ) {
bookmarkStart.move( cursor, true );
break;
}
}
}
if ( bookmarkEnd && bookmarkEnd.getParent().getName() == 'blockquote' ) {
cursor = bookmarkEnd;
while ( ( cursor = cursor.getPrevious() ) ) {
if ( cursor.type == CKEDITOR.NODE_ELEMENT && cursor.isBlockBoundary() ) {
bookmarkEnd.move( cursor );
break;
}
}
}
}
var iterator = range.createIterator(),
block;
iterator.enlargeBr = editor.config.enterMode != CKEDITOR.ENTER_BR;
if ( state == CKEDITOR.TRISTATE_OFF ) {
var paragraphs = [];
while ( ( block = iterator.getNextParagraph() ) )
paragraphs.push( block );
// If no paragraphs, create one from the current selection position.
if ( paragraphs.length < 1 ) {
var para = editor.document.createElement( editor.config.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ),
firstBookmark = bookmarks.shift();
range.insertNode( para );
para.append( new CKEDITOR.dom.text( '\ufeff', editor.document ) );
range.moveToBookmark( firstBookmark );
range.selectNodeContents( para );
range.collapse( true );
firstBookmark = range.createBookmark();
paragraphs.push( para );
bookmarks.unshift( firstBookmark );
}
// Make sure all paragraphs have the same parent.
var commonParent = paragraphs[ 0 ].getParent(),
tmp = [];
for ( var i = 0; i < paragraphs.length; i++ ) {
block = paragraphs[ i ];
commonParent = commonParent.getCommonAncestor( block.getParent() );
}
// The common parent must not be the following tags: table, tbody, tr, ol, ul.
var denyTags = { table: 1, tbody: 1, tr: 1, ol: 1, ul: 1 };
while ( denyTags[ commonParent.getName() ] )
commonParent = commonParent.getParent();
// Reconstruct the block list to be processed such that all resulting blocks
// satisfy parentNode.equals( commonParent ).
var lastBlock = null;
while ( paragraphs.length > 0 ) {
block = paragraphs.shift();
while ( !block.getParent().equals( commonParent ) )
block = block.getParent();
if ( !block.equals( lastBlock ) )
tmp.push( block );
lastBlock = block;
}
// If any of the selected blocks is a blockquote, remove it to prevent
// nested blockquotes.
while ( tmp.length > 0 ) {
block = tmp.shift();
if ( block.getName() == 'blockquote' ) {
var docFrag = new CKEDITOR.dom.documentFragment( editor.document );
while ( block.getFirst() ) {
docFrag.append( block.getFirst().remove() );
paragraphs.push( docFrag.getLast() );
}
docFrag.replace( block );
} else {
paragraphs.push( block );
}
}
// Now we have all the blocks to be included in a new blockquote node.
var bqBlock = editor.document.createElement( 'blockquote' );
bqBlock.insertBefore( paragraphs[ 0 ] );
while ( paragraphs.length > 0 ) {
block = paragraphs.shift();
bqBlock.append( block );
}
} else if ( state == CKEDITOR.TRISTATE_ON ) {
var moveOutNodes = [],
database = {};
while ( ( block = iterator.getNextParagraph() ) ) {
var bqParent = null,
bqChild = null;
while ( block.getParent() ) {
if ( block.getParent().getName() == 'blockquote' ) {
bqParent = block.getParent();
bqChild = block;
break;
}
block = block.getParent();
}
// Remember the blocks that were recorded down in the moveOutNodes array
// to prevent duplicates.
if ( bqParent && bqChild && !bqChild.getCustomData( 'blockquote_moveout' ) ) {
moveOutNodes.push( bqChild );
CKEDITOR.dom.element.setMarker( database, bqChild, 'blockquote_moveout', true );
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
var movedNodes = [],
processedBlockquoteBlocks = [];
database = {};
while ( moveOutNodes.length > 0 ) {
var node = moveOutNodes.shift();
bqBlock = node.getParent();
// If the node is located at the beginning or the end, just take it out
// without splitting. Otherwise, split the blockquote node and move the
// paragraph in between the two blockquote nodes.
if ( !node.getPrevious() )
node.remove().insertBefore( bqBlock );
else if ( !node.getNext() )
node.remove().insertAfter( bqBlock );
else {
node.breakParent( node.getParent() );
processedBlockquoteBlocks.push( node.getNext() );
}
// Remember the blockquote node so we can clear it later (if it becomes empty).
if ( !bqBlock.getCustomData( 'blockquote_processed' ) ) {
processedBlockquoteBlocks.push( bqBlock );
CKEDITOR.dom.element.setMarker( database, bqBlock, 'blockquote_processed', true );
}
movedNodes.push( node );
}
CKEDITOR.dom.element.clearAllMarkers( database );
// Clear blockquote nodes that have become empty.
for ( i = processedBlockquoteBlocks.length - 1; i >= 0; i-- ) {
bqBlock = processedBlockquoteBlocks[ i ];
if ( noBlockLeft( bqBlock ) )
bqBlock.remove();
}
if ( editor.config.enterMode == CKEDITOR.ENTER_BR ) {
var firstTime = true;
while ( movedNodes.length ) {
node = movedNodes.shift();
if ( node.getName() == 'div' ) {
docFrag = new CKEDITOR.dom.documentFragment( editor.document );
var needBeginBr = firstTime && node.getPrevious() && !( node.getPrevious().type == CKEDITOR.NODE_ELEMENT && node.getPrevious().isBlockBoundary() );
if ( needBeginBr )
docFrag.append( editor.document.createElement( 'br' ) );
var needEndBr = node.getNext() && !( node.getNext().type == CKEDITOR.NODE_ELEMENT && node.getNext().isBlockBoundary() );
while ( node.getFirst() )
node.getFirst().remove().appendTo( docFrag );
if ( needEndBr )
docFrag.append( editor.document.createElement( 'br' ) );
docFrag.replace( node );
firstTime = false;
}
}
}
}
selection.selectBookmarks( bookmarks );
editor.focus();
},
refresh: function( editor, path ) {
// Check if inside of blockquote.
var firstBlock = path.block || path.blockLimit;
this.setState( editor.elementPath( firstBlock ).contains( 'blockquote', 1 ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
},
context: 'blockquote',
allowedContent: 'blockquote',
requiredContent: 'blockquote'
};
CKEDITOR.plugins.add( 'blockquote', {
// jscs:disable maximumLineLength
lang: 'af,ar,az,bg,bn,bs,ca,cs,cy,da,de,de-ch,el,en,en-au,en-ca,en-gb,eo,es,es-mx,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,oc,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
// jscs:enable maximumLineLength
icons: 'blockquote', // %REMOVE_LINE_CORE%
hidpi: true, // %REMOVE_LINE_CORE%
init: function( editor ) {
if ( editor.blockless )
return;
editor.addCommand( 'blockquote', commandObject );
editor.ui.addButton && editor.ui.addButton( 'Blockquote', {
label: editor.lang.blockquote.toolbar,
command: 'blockquote',
toolbar: 'blocks,10'
} );
}
} );
} )();

Data Binding to the Table error is not a fucntion

I have problem with binding the OData to the table. When i define a function in js file it says "is not a function"
odata.js
getBoM : function(iNumber){
var sNumber = iNumber.toString();
while (sNumber.length < 18) {
sNumber = "0" + sNumber
}
var vUriRead = "/ProductHeadSet('12345')/ProductHead2BOM";
var oResult;
this.initODataModel( );
this.oDataModel.read(vUriRead, null, null, false, function(oData, oResponse) {
oResult = oData;
}, function(oError) {
jQuery.sap.log.error("OData-Error in function getBoM (EntityBoMSet)");
xyz_homepage.xyz_homepage.src.odata.displayRequestFailedMessage(oError);
});
return oResult;
},
Controller.js
var oProductHead2BoM = xyz_homepage.xyz_homepage.src.odata.getBoM(iNumber);
this.oModelProductHead2BoM.setData(oProductHead2BoM);
at the .getBoM(iNumber) it says, "Uncaught TypeError: xyz_homepage.xyz_homepage.src.odata.getBoM is not a function"
Edit :
controller.js
handleRouteMatched : function(oEvent) {
if (oEvent.getParameter("name") === "page") {
var iNumber = oEvent.getParameter("arguments").number;
var oDataResult = xyz_homepage.xyz_homepage.src.odata
.getDetailsProd(iNumber);
this.oModelProdManag.setData(oDataResult);
var aDocuments = xyz_homepage.xyz_homepage.src.odata.getDocumentsProd(iNumber);
this.oModelDocuments.setData(aDocuments);
//Call bom routine and set data
var oProductHead2BoM = xyz_homepage.xyz_homepage.src.odata.getProductHead2BOM(iNumber);
this.oModelProductHead2BoM.setData(oProductHead2BoM);
So when i debug and click on function ".getDocumentsProd" i can find the function which is reference to odata.js
Odata.js
getDocumentsProd Function
getDocumentsProd : function(iNumber){
var sNumber = iNumber.toString();
while (sNumber.length < 18) {
sNumber = "0" + sNumber
}
var vUriRead = "/DocumentsSet/?$filter=Material%20eq%20'" + sNumber + "'";
var oResult;
this.initODataModel( );
this.oDataModel.read(vUriRead, null, null, false, function(oData, oResponse) {
oResult = oData.results;
}, function(oError) {
jQuery.sap.log.error("OData-Error in function getDocumentsProd (EntityDocumentsSet)");
xyz_homepage.xyz_homepage.src.odata.displayRequestFailedMessage(oError);
});
return oResult;
},
On the same note i have for the getProductHead2BOM function.
getProductHead2BOM : function(iNumber){
var sNumber = iNumber.toString();
while (sNumber.length < 18) {
sNumber = "0" + sNumber
}
var vUriRead = "/ProductHeadSet('5199182')/ProductHead2BOM";
var oResult;
this.initODataModel( );
this.oDataModel.read(vUriRead, null, null, false, function(oData, oResponse) {
oResult = oData;
}, function(oError) {
jQuery.sap.log.error("OData-Error in function getProductHead2BOM (EntityProductHead2BOM)");
zplm_homepage.zplm_homepage.src.odata.displayRequestFailedMessage(oError);
});
return oResult;
}
I could see documents Odata but not for ProductsHeadBom

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

How to add or inc to an array in a update query?

If I have a doc which has an array which contains a items which represents counts for a day, perhaps like :-
{
data : [ {'20141102' : 2 },{'20141103' : 4 } ]
}
when I do an update, and I have a string '20141103' and then later a '20141104' I want to either inc the array entry or add a new array entry. Is this possible with an update?
Yes, it's feasible. I tried like this:
(run on mongo shell; both client and server are V2.6.4)
function tryAndFine(coll, key, value) {
var entry = {};
entry[key] = value;
var parent = 'data';
var prefix = parent + '.';
function incrementOnly() {
var criteria = {};
criteria[prefix + key] = {$exists : true};
var update = {};
update[prefix + "$." + key] = value;
var result = coll.update(criteria, {$inc : update});
// if increment fails, try to add a new one
if (result.nModified == 0) {
addNewElement();
}
}
function addNewElement() {
var criteria = {};
criteria[prefix + key] = {$exists : false};
var update = {};
update[parent] = entry;
var result = coll.update(criteria, {$push : update}, {upsert : true});
// if exists, try to increment the count
if (result.upserted == 0 && result.nModified == 0) {
incrementOnly();
}
}
// run entry
incrementOnly();
}
// test
var c = db.c;
c.drop();
tryAndFine(c, '20141103', 1);
tryAndFine(c, '20141103', 1);
tryAndFine(c, '20141104', 1);
tryAndFine(c, '20141105', 1);
tryAndFine(c, '20141104', 1);
// output
{
"_id" : ObjectId("54577e1a3502852bd4ad2395"),
"data" : [ {
"20141103" : 2
}, {
"20141104" : 2
}, {
"20141105" : 1
} ]
}