uploadify scriptData problem - uploadify

I'm having problems with scriptData on uploadify, I'm pretty sure the config syntax is fine but whatever I do, scriptData is not passed to the upload script.
I tested in both FF and Chrome with flash v. Shockwave Flash 9.0 r31
This is the config:
$(document).ready(function() {
$('#id_file').uploadify({
'uploader' : '/media/filebrowser/uploadify/uploadify.swf',
'script' : '/admin/filebrowser/upload_file/',
'scriptData' : {'session_key': 'e1b552afde044bdd188ad51af40cfa8e'},
'checkScript' : '/admin/filebrowser/check_file/',
'cancelImg' : '/media/filebrowser/uploadify/cancel.png',
'auto' : false,
'folder' : '',
'multi' : true,
'fileDesc' : '*.html;*.py;*.js;*.css;*.jpg;*.jpeg;*.gif;*.png;*.tif;*.tiff;*.mp3;*.mp4;*.wav;*.aiff;*.midi;*.m4p;*.mov;*.wmv;*.mpeg;*.mpg;*.avi;*.rm;*.pdf;*.doc;*.rtf;*.txt;*.xls;*.csv;',
'fileExt' : '*.html;*.py;*.js;*.css;*.jpg;*.jpeg;*.gif;*.png;*.tif;*.tiff;*.mp3;*.mp4;*.wav;*.aiff;*.midi;*.m4p;*.mov;*.wmv;*.mpeg;*.mpg;*.avi;*.rm;*.pdf;*.doc;*.rtf;*.txt;*.xls;*.csv;',
'sizeLimit' : 10485760,
'scriptAccess' : 'sameDomain',
'queueSizeLimit' : 50,
'simUploadLimit' : 1,
'width' : 300,
'height' : 30,
'hideButton' : false,
'wmode' : 'transparent',
translations : {
browseButton: 'BROWSE',
error: 'An Error occured',
completed: 'Completed',
replaceFile: 'Do you want to replace the file',
unitKb: 'KB',
unitMb: 'MB'
}
});
$('input:submit').click(function(){
$('#id_file').uploadifyUpload();
return false;
});
});
I checked that other values (file name) are passed correctly but session_key is not.
This is the decorator code from django-filebrowser, you can see it checks for
request.POST.get('session_key'), the problem is that request.POST is empty.
def flash_login_required(function):
"""
Decorator to recognize a user by its session.
Used for Flash-Uploading.
"""
def decorator(request, *args, **kwargs):
try:
engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
except:
import django.contrib.sessions.backends.db
engine = django.contrib.sessions.backends.db
print request.POST
session_data = engine.SessionStore(request.POST.get('session_key'))
user_id = session_data['_auth_user_id']
# will return 404 if the session ID does not resolve to a valid user
request.user = get_object_or_404(User, pk=user_id)
return function(request, *args, **kwargs)
return decorator

I found a solution without using scriptData. You can pass your data by passing through your URL:
$("#image_upload1").uploadify({
'method':'POST',
'buttonText':'Select',
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png',
'swf':'<?php echo base_url()?>resources/flash/uploadify.swf',
'uploader':'<?php echo site_url('item/update_item_images/'.$picid[0]); ?>',
'width': 40,
'multi':false,
'onUploadComplete':function(file)
{
$('.original').hide();
$('#image1').attr('style','background-image:url("../resources/uploads/<?php echo $id;?>/'+file.name+'");background-size: 140px 119px;');
$('#hidden_img_value1').attr('value',file.name)
}
});
Here I pass the value $picid[0] in uploader. This data you can access in your controller.

#Jimbo after removing inverted comma (') ,then also the value is not reciving in controller.
$("#image_upload1").uploadify({
'method':'POST',
'buttonText':'Select',
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png',
'swf':'<?php echo base_url()?>resources/flash/uploadify.swf',
'uploader':'<?php echo site_url('item/update_item_image1')?>',
'width': 40,
'multi':false,
'scriptData':{id:'<?=$picid[0]?>'},
'onUploadComplete':function(file)
{
//alert(response);
$('.original').hide();
$('#image1').attr('style','background-image:url("../resources/uploads/18/'+file.name+'")');
$('#hidden_img_value1').attr('value',file.name)
}
});

This might sound silly, but are you sure it's a session_key problem?
I had an authentication problem with filebrowser+uploadify but the problem was not the session_key but that the site was protected by a HTTP digest authentication set in Apache and, although session_key was sent fine, uploadify does not send the HTTP authentication headers.
Is your web server requiring any form of authentication?

I had a a similar problem passing script data in the past. Removing the inverted comma (') around the key in the key/value pairs fixed my problem
Instead of:
'scriptData' : {'session_key': 'e1b552afde044bdd188ad51af40cfa8e'},
Use:
'scriptData' : {session_key: 'e1b552afde044bdd188ad51af40cfa8e'},
(useful Uploadify post here)

Related

Wordpress admin-ajax.php 400 bad request

I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'cart_clb',
id : 1
},
method : 'POST',
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
And inside my functions.php
add_action( 'wp_ajax_post_cart_clb', 'cart_clb' );
add_action( 'wp_ajax_nopriv_post_cart_clb', 'cart_clb' );
function cart_clb(){
echo json_encode($_POST);
die();
}
As said above when i execute the request :
mydomain.com/wp-admin/admin-ajax.php 400 (Bad Request)
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
Someone could help me to please? thank you.
First, use full and absolute url, with protocol (or at least protocol-independent form):
var ajaxscript = { ajax_url : '//mydomain.com/wp-admin/admin-ajax.php' }
Second, your ajax action name is not the php callback function name but the dynamic part of the hook wp_ajax_{action_name} / wp_ajax_nopriv_{action_name}, so in your case it should be:
data : {
action : 'post_cart_clb',
id : 1
},
I have modified your code and look at this :
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'post_cart_clb',
id : 1
},
method : 'POST', //Post method
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
This is the syntax of WordPress ajax :
wp_ajax_{Your_action_name}
wp_ajax_nopriv_{Your_action_name}
wp_ajax_nopriv_(action) executes for users that are not logged in.
So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:
add_action( 'wp_ajax_my_action', 'my_action' ); // for loggin users
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for non loggin users
admin-ajax.php returns Bad Request headers in 2 situations, when the action function is not registered, and when the action parameter is empty.
I had same error and the issue was that i forgot to add_action('wp_ajax_nopriv'...) i had only wp_ajax_nopriv set, so when i was logged in as admin nesting, it was not working.
In my case, I am using Class based approach. And I found the issue was because I was using wp_ajax_ request in constructor.
If you are using ajax methods inside class, move wp_ajax_ handles outside of class (write in main plugin file) and pass classname and method name. For example:
add_action( 'wp_ajax_your_handle', [ 'Class_Name', 'function_name' ] );
add_action( 'wp_ajax_nopriv_your_handle', [ 'Class_Name', 'function_name' ] );
Just Use
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
For more detail, check the below link
https://codex.wordpress.org/AJAX_in_Plugins
In Vanilla JavaScript You get a Bad Request if You don't append this header to the POST request:
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
So please be sure that jQuery appends as well that header.
in the url use /wp-admin/admin-ajax.php and try to have a local domain because with localhost or localhost/wordpress this might be weird, on the server this will work fine
try to use fetch or XMLHttpRequest to have more control over the request and don't send data as json send it in a formData object const formData = new FormData();
fetch(loader.ajax_url, {
method: "POST",
body: formData,
}).then((resp) => {
console.log(resp);
}).catch((resp) => {
console.log(resp);
});
it is possible to have it work with other combinations but i find this almost perfect

Filter param value(name value) is not sending in Ajax call

Filter parameter value i.e name value is not included when i was performing filter operation in my API call as written below
_dc:1427270031651
counrtyId:2
custId:1
id:
name:
page:1
start:0
limit:10
sort:[{"property" : "id", "direction" : "desc"}]
This is my store
Ext.define('MyDesktop.store.DirectoriesStore', {
extend: 'Ext.data.Store',
requires:'MyDesktop.model.DirectoriesNumberModel',
model: 'MyDesktop.model.DirectoriesModel',
storeId:'DirectoriesStore',
autoLoad : {
params : {
start : 0,
limit : '10'
}
},
pageSize : 10,
remoteSort : true,
sorters : [{
property : 'id',
direction : 'desc'
}],
remoteFilter : true,
proxy:{
type:'ajax',
url:'./configuration/directory/get',
reader:{
type: 'json',
root: 'data',
totalProperty: 'total'
},
extraParams: {
'countryId': '',
'custId': ''
}
},
autoLoad:false
});
and this is my view
Ext.require([
'Ext.ux.grid.FiltersFeature'
]);
var filters = {
ftype: 'filters',
local: true,
features: [{type: 'integer',dataIndex: 'name'},
{type: 'string',dataIndex: 'description'},
{type: 'string',dataIndex: 'fileName'}]
};
and I added it grid as follows:
features: [filters],
Filters are working but In API call filters are not calling
Please anyone help me.
You have remote filtering disabled in your store.
Change remoteFilter: false to remoteFilter: true and try again.
From the docs:
remoteFilter : Boolean
true to defer any filtering operation to the server. If false,
filtering is done locally on the client.
It also appears that your specifically telling your application to apply the filters locally with the local:true config.
The problem is, the params are not being sent to the ajax call. But hey, try changing the page after you loaded your store. Then try sorting again. You will see that the params are now being sent along in the Ajax request.
My current workaround is to imitate a changepage via gridStore.loadPage(page, [options]). You should also change it back to first page again after that.
After you change the page, sort will be working for all following requests.
This of course is just a workaround and we may have different requirements. My grid is calling store.load() after render so I attached the change page there.
Hope you have some hints.
NOTE: THIS IS ONLY A WORKAROUND!

ajax Preloader is not working in chrome,safari while working in firefox

I have a problem in "Ajax Loader image". On Firefox it is working fine but on chrome that ajax loader image does not seems.
I have a some attributes on sidebar when I check any attribute Products changes according with it and a Preloader image generated before ajax completed.What I am doing is when I check on any attribute first I insert a gif image in div html and show it using .show() method and after success of ajax I set div html null and hide it.
You can see that div in firebug (<div id="ajax_loader_div" style="display:none;"></div>)
Code is really complicated that's why I am not posting code here.Really very Sorry for that.You can see it on http://vcompare4u.com/wpcompare/products/laptops/
I need help.Please
Thanks!!!
I've seen your code
It is well known a synchronous requests will lock the UI. So not surprisingly on chrome and safari, (it does in Firefox interestingly)
can you try something like this
jQuery('#customtag_widget-2 .compare_attribute').bind('change',
jQuery.filterProductsCompare2 = function () {
$.ajaxSetup({async:false});
jQuery('#ajax_loader_div').css('display', 'block');
jQuery('#ajax_loader_div').html('<img src="http://vcompare4u.com/wpcompare/wp-content/themes/compare/_assets/img/ajax-loader.gif" / >');
jQuery('#customtag_widget-2 .compare_attribute_group').each(function () {
jQuery(this).children().each(function () {
if (jQuery(this).children('.compare_attribute').attr('checked')) {
if (jQuery(this).children('.compare_attribute').attr('name').indexOf('b[') != -1) {
brands.push(jQuery(this).children('.compare_attribute').attr('value'));
}
if (jQuery(this).children('.compare_attribute').attr('name').indexOf('c[') != -1) {
categories.push(jQuery(this).children('.compare_attribute').attr('value'));
}
}
})
} else {
minmaxarr = jQuery(this).attr('value').split(';');
minPrice = minmaxarr[0];
maxPrice = minmaxarr[1];
}
if (!jQuery.support.placeholder) {
if (isEmptyPlaceholder == 1) {
jQuery(this).val('Search...');
}
}
})
if (jQuery('#dont_change_price').is(':checked')) {
minPrice = jQuery('#overall_min').val();
maxPrice = jQuery('#overall_max').val();
} else {}
jQuery.ajax({
url : file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
dont_change_price : dont_change_price,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (data) {
// Do stuff here
}
});
jQuery.ajax({
url : bracket_file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (bracket_data) {
// DO stuff here
}
});
if (!jQuery('#dont_change_price').is(':checked')) {
jQuery.ajax({
url : price_file_url,
data : {
ajaxsearch : '1',
s : 'compare',
ki : keywords_comparei,
product : '',
c : categories,
b : brands,
checked_id : checked_string,
min : minPrice,
max : maxPrice,
product_category : product_category
},
success : function (price_data) {
// DO stuff here
}
});
}
jQuery('#ajax_loader_div').hide();
jQuery('#ajax_loader_div').html('');
$.ajaxSetup({async:true});
});
What I am trying to do is to do synchronous request for each ajax request and instead of using success functions I am using ajax request separately. Due to synchronous nature each request will be processed one after another.
Inspecting your code in chrome console I've seen ajax loader for very little moment get hided immediately.
here is reference problem same like yours
Force UI repaint in Webkit (Safari & Chrome) right before Synchronous "Ajax" request
<div id="#ajax_loader_css" style="display:none;"></div>
should be
<div id="ajax_loader_css" style="display:none;"></div>
Based on the accepted answer here valid values for an id element are
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Firefox is obviously trying to fix it by removing the invalid character making the #ajax_loader_css css selector match something where as chrome is ignoring it so your selector matches nothing.

AJAX request parameters for JSON store. ExtJS

I want to string together some parameters into an address where I can view an AJAX request in browser... I think this is what I mean, though I am not comfortable talking about AJAX. I am only a novice front-end web application programmer.
So to start, I have an ExtJS application with a combobox. It is populated by items in a JSON file, from what I can tell. Here is the application code snippet:
items: [{
xtype : 'combobox',
queryMode : 'remote',
fieldLabel: 'twittersearch',
typeAhead : true,
allowBlank : applicationtype === 'relatedanalysis' ? true : false,
hideTrigger : false,
editable : false,
multiSelect : true,
minChars : 1,
store : 'smcc.TwitterSearch',
displayField : 'id',
name : 'twittersearch',
listConfig: {
getInnerTpl: function() {
return '<div><img src="../media/com_concilium/images/twitter/{sn}-logo-med.png" />{id}</div>';
}
}
}
So I understand how store's work in the extJS MVC setup. Documentation here: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.field.ComboBox-cfg-store
So I searched 'twittersearch' at the root of my all component files with windows explorer to find the proper twittersearch.js store file. Here it is:
Ext.define('Container.store.smcc.TwitterSearch', {
extend : 'Ext.data.Store',
model : 'Container.model.smcc.TwitterSearch',
autoLoad : false,
proxy : {
type : 'ajax',
url : './',
extraParams : {
option : 'com_concilium',
view : 'smcc',
format : 'raw',
controller : 'smcc',
task : 'getSocalMediaStream'
},
reader : {
type : 'json',
root : 'rows',
totalProperty: 'row_count'
}
},
});
So is this enough information to create an address and perhaps look at the data? I assume it is something like urlbase/index.php?option=com_concilium&view=smcc&format=raw&controller=smcc&task=getSocialMediaStream
You should be able to create the store
var store = Ext.create('Container.store.smcc.TwitterSearch');
and then call
store.load();
If you use Chrome browser, you should see the network request in the Chrome Developer Tools network panel.
https://developers.google.com/chrome-developer-tools/docs/network
I would recommend trying to replicate the sencha examples, using jsfiddle.net, which lets you "fiddle" with the code easily.

Scala Lift - AJAX uploader (valums) not accepting IE9 file upload

I have the following:
new qq.FileUploader({
element: $('#' + domid + ' #upload')[0],
action: '/api/panel/upload_file',
debug: true,
allowedExtensions: [
'jpg',
'jpeg',
'gif',
'png',
'bmp',
'pdf'
],
params: {
room : 'a_room',
module : 'a_module'
},
onSubmit: function(id, fileName) {
this.params.name = fileName;
},
onProgress: function(id, fileName, loaded, total) { },
onComplete : function(id, fileName, data) {
/* FINISH */
}
});
Which sends the upload request to:
case "api" :: "panel" :: "upload_file" :: Nil Post req => {
var response = true
req.body match {
case Full(file) =>
/* DO SOMETHING */
case _ => response = false
}
}
This works fine in both Firefox and Chrome, but when uploading with IE9 the file doesnt seem to get past:
req.body match {
case Full(file) =>
}
Is there something I'm missing or need to do to get this working properly?
Thanks in advance for any help, much appreciated :)
Firstly, req.body will give you an array of bytes, not a file. Lift will automatically detect if you're uploading a file or an arbitrary payload. Its not a good idea to put files into memory, especially if they might be large.
Look into req.uploadedFiles, and req.rawInputStream with OnDiskFileParamHolder.apply - if i recall how vallums uploader works, you have to manually push the input stream into the FileParamHolder, from which you can just call .file and then have a direct java.io.File instance to work with.

Resources