.uploadifySettings not working as expected - javascript

I'm using uploadify and the function to change the settings doesn't seem to be working.
I'm basing my code from the following example:
#(‘#someID’).uploadifySettings(’scriptData’, {‘name’ : some.val()});
So here's what I'm doing:
// INITIALIZATION
$("#"+elementId).uploadify({
// other data
"scriptData": {
"token": token
}
});
Later on I want to update the scriptData:
$("#"+elementId).uploadifySettings("scriptData",{"token": "pleasework"});
... but this is not working, it's still using the scriptData set during the initialization.
What am I doing wrong?
UPDATE: I need to do this because I need to handle tokens. Here's the worflow:
1- Get a token
2- Init uploadify with this token
3- Upload a file
4- Get another token asynchronously
5- Add the token to the already initialized uploadify (bugged)
6- Go to 3
I tried doing this on initialization:
"scriptData": {
"token": $(".token").val()
}
... and update .token on step 4
This doesn't work either
UPDATE 2: Also if I do:
"scriptData": {
"token": getAToken()
}
with
function getAToken(){
alert("abcd");
return "sometoken";
}
... I can see that the function getAToken only gets called once (only 1 alert)

This works for me, adding a unique nonce to every file upload
function setScriptData(){
$("#product_attachment").uploadifySettings("scriptData",
{
'_fsg_distro_session' : '<%= u cookies["_fsg_distro_session"] %>',
'authenticity_token' : '<%= u form_authenticity_token if protect_against_forgery? %>',
'nonce' : new Date().getTime() + "<%= #current_user.id %>"
}
);
console.debug($("#product_attachment").uploadifySettings("scriptData"));
}
$("#product_attachment").uploadify({
uploader : '/uploadify/uploadify.swf',
script : '/products/temp_upload',
cancelImg : '/uploadify/cancel.png',
fileDataName : 'asset[temp_file]',
'queueID' : 'fileQueue',
onComplete : function(event, ID, fileObj, response, data){ fileOnCompleteHandler(event,data); },
onSelect : setScriptData,
auto : true,
multi : false,
buttonImg : '/images/attach.png',
fileNameMaxLength : 30
});
I am using the latest Uploadify (2.1.0) and JQuery (1.4.1)

I've looked at the source and I notice that uploadifySettings() has an optional, undocumented (it does not appear here) third parameter. Apparently if you set it to true as in $("#"+elementId).uploadifySettings("scriptData",{"token": "pleasework"}, true); it will clobber the existing settings for scriptData and perhaps that will have some impact.
But based on the source I can't exactly tell what impact a change in settings necessarily has.
uploadifySettings:function(settingName, settingValue, resetObject) {
var returnValue = false;
jQuery(this).each(function() {
if (settingName == 'scriptData' && settingValue != null) {
if (resetObject) {
var scriptData = settingValue;
} else {
var scriptData = jQuery.extend(settings.scriptData, settingValue);
}
var scriptDataString = '';
for (var name in scriptData) {
scriptDataString += '&' + name + '=' + escape(scriptData[name]);
}
settingValue = scriptDataString.substr(1);
}
returnValue = document.getElementById(jQuery(this).attr('id') + 'Uploader').updateSettings(settingName, settingValue);
});
That code is from version 2.1.0.
Is there a way to potentially decide on the settings before initialization?
Also, I found this existing SO question: Uploadify updateSettings problems.

Try defining the function in-line at initialization? IE:
"scriptData": {
"token": function() { return $("#token").val(); }
}
I'm not sure why this would be different than some of your other solutions though.

FOUND THE SOLUTION:
I had a mistake in the "onSelect" function. I had misspelled the element id name, instead file_upload I had fileUpload and thats why it didnt update the scriptData parameter. I know its a silly mistake but easy to be made. Here is the whole onSelect function:
'onSelect' : function(event,data) {
$("#file_upload").uploadifySettings('scriptData', {'id' : $('#name_of_the_element').val()}
);
}
So check if this is the problem

Related

Shorthand property name are not supported by current Javascript version in PHPStorm

I have used Jquery getScript and generate html form by Javascript however I got
Shorthand property name are not supported by current Javascript version in PHPStorm but my function work as well.
Concern: Before I used PHP to generate html form within another PHP framework but I think I should not used Server script to do that I should use JS to do that but I don't know how is it going on and is it support all browser or not so please give me some idea of this technique because I not yet understand much more about suing DOM and its performance.
Security Concern: if I used Javascript to generate Html form as below script it will less security or bad performance or not?
Another hand if I keep this code inside of HTMl I will never got this errors types.
$(document).ready(function () {
returnTill('returnTill');
});
function returnTill(returnTill) {
var chief_opt = '';
var teller_opt = '';
$.ajax({
url:'/teller/return_till_data',
method:'get',
dataType:'json',
timeout:4000,
async: false,
success:function (data, status) {
$.each(data, function(ins, vals){
if(ins === 'chief') {
cheifs = data.chief;
for(var key in cheifs){
chief_opt += '<option value="'+vals[key].id+'"> '+vals[key].username+' / '+vals[key].account_no+' </option>';
}
}if(ins === 'teller') { /* Tellers*/
tellers = data.teller;
for(var key in tellers){
teller_opt = '<option value="'+vals[key].id+'"> '+vals[key].username+' / '+vals[key].account_no+' </option>';
}
loadModale({
idSelector: returnTill,
title: 'Return Till',
labels: ['From','To','Amount','Description'],
loadType:'returnTill',
forms: {
input: {
selection: {
from:{chief_opt,class:'form-control', name:'retn_chief', id:'retn_chief'},
to:{teller_opt, class:'form-control', name:'retn_teller', id:'retn_teller'},
},
Amount :{type: 'text', name: 'retn_amount', class: 'form-control', Id: 'retn_amount', placeholder: '', style: '', value:''},
token:{ type: 'hidden', name: '_token', class: 'form-control', Id: 'token', placeholder: '', style: '', value: '{{csrf_token()}}'},
},
textarea : {
description:{class:'form-control', name:'tran_descr', rows:10, id:'tran_descr'}
}
},script: [
'/theme/js/jquery.validate.min.js',
'/theme/js/bootstrap-datepicker/js/bootstrap-datepicker.js',
]
});
}
});
},error: errorCallback,
});
}
Errors:
I perform the following steps in Webstorm to solve the same problem, so it may also work in PHPStorm:
Go to Settings by pressing ALT + CNTRL + S
Click on "Languages and Frameworks"
Click on 'Javascript'
In the "Javascript language version" drop-down, select 'ECMAScript 6'.
Click 'OK'
Now re-open any *.js files you may have previously had open, and notice that the errors are no longer there.
Hope that helps someone.
You can fix it this way:
from:{chief_opt: chief_opt}
So, if you change your code to this:
from:{chief_opt: chief_opt, class:'form-control', name:'retn_chief', id:'retn_chief'},
to:{teller_opt: teller_opt, class:'form-control', name:'retn_teller', id:'retn_teller'},
You shouldn't get anymore the PHPStorm error.
Hope it helped or at least cleared a little bit. ;)
PHP STORM SOLUTION
The error is attributed to the version of your Javascript Setting in PHPSTORM
STEPS
Go to settings(preference on macbook)settings/preference and click
Expand the Languages and Frameworks by clicking it
click language & frameworks
Click Javascript and change the Javascript language version to the current or ECMAScript6 recommended.select ecmascript

How to pass selected value as extra parameter to ajax call

my coding part
$("#demo-input").tokenInput("data/autosuggest-search-city.php",
{
searchDelay: 2000,
minChars: 3,
tokenLimit: 10
});
I want to send the selected values as extra parameter to "data/autosuggest-search-city.php".
For example,
Initially I search and select one value from list
then again searching, this time I want to send the 1st selected value to server.
How to do this?
TokenInput plugin doesn't support that natively.
You can however make a simple workaround to update "AJAX url" whenever a token is added or removed from selection.
Use onAdd and onDelete callbacks to trigger "AJAX url" changes;
Get selected tokens using selector.tokenInput("get") method;
Set the new "AJAX url" by updating .data("settings").url of the element;
// cache the original url:
var token_url = "data/autosuggest-search-city.php";
$("#demo-input").tokenInput(token_url, {
searchDelay : 2000,
minChars : 3,
tokenLimit : 10,
onAdd : function(){
urlChange.call(this);
},
onDelete : function(){
urlChange.call(this);
}
});
function urlChange(){
var tokens = '', token_list = $(this).tokenInput("get");
// proceed if any token/s are selected:
if(token_list.length){
// loop through the selected tokens (if more than one is selected)
$.each(token_list, function(i, token){
// use token "id" (or "name" if you wish) and separate them with comma:
tokens += token.id + ',';
});
// update url:
$(this).data("settings").url = token_url + '?selected_tokens='+tokens.replace(/,+$/,'');
}else{
// leave original url if no tokens are selected:
$(this).data("settings").url = token_url;
}
};

How to add content via ajax using the popover boostrap

I tried to view different sources and also looked into the forums posting similar question, but it didnt quite help me with the issue that im facing.
I have a text input filed to which I'm adding a popover to show similar a list of names in the database. The inout field checks for validation, to see if the name entered is unique, if not it displays similar names available in the database that could be re-used.
here is the popover snippet:
$("#account_name_create").popover({
title: 'Twitter Bootstrap Popover',
content: function (process) {
this.accountCollection = new ipiadmin.collections.AccountCollection();
var newName = $("#new-account-form #account_name_create").val();
var userFilter = "accountName~'" + newName + "'";
this.accountCollection.fetch({
data: { "f": userFilter,
"sortby": null,
"type":"ipi",
"pageno":0,
"pagesize":2,
"reversesort" : true
},
cache: false,
success: function(model, response, options) {
var states = [];
map = {};
$.each(model.aDataSet, function (i, state) {
map[state.accountName] = state;
states.push(state.accountName);
});
process(states); //gives an error saying 'undefined is not a function (says process is undefined)'
},
error: function(model, response, options) {
console.log('error');
}
});
},
});
here is the html:
<input type="text" id="account_name_create" name="account_name" class="" size="40" />
I'm not sure how why it says 'process' as undefined. Also not sure if this would be the correct way of displaying the data in the popover.
Any ideas??
Thanks!
process doesn't have scope in the success function, only in the content function. If you want to call the process function from within the success function, you could define it somewhere outside of the jQuery call.

Javascript push Object to cookies using JSON

Hi All on click button I need to add object to array and then write array to cookies.
From the start this array can be not empty so I parse cookie first.
function addToBasket(){
var basket = $.parseJSON($.cookie("basket"))
if (basket.length==0||!basket){
var basket=[];
basket.push(
{ 'number' : this.getAttribute('number'),
'type' : this.getAttribute('product') }
);
}
else{
basket.push(
{ 'number' : this.getAttribute('number'),
'type' : this.getAttribute('product') }
);
}
$.cookie("basket", JSON.stringify(basket));
}
And HTML
<button type="button" class="btn btn-success btn-lg" number="12" product="accs" onclick="addToBasket()">Add</button>
Unfortunately I'm getting Uncaught ReferenceError: addToBasket is not defined onclick.
Can't understand what am I doing wrong?
Thanks!
I simplified your code a good deal, heres a fiddle: http://jsfiddle.net/yJ6gp/
I wired the click event using jQuery and simplified some of your code (see comments). Note I changed your html a little so I could select the add basket button by class - change as desired.
$(function () {//doc ready
$.cookie.json = true; //Turn on automatic storage of JSON objects passed as the cookie value. Assumes JSON.stringify and JSON.parse:
$('.add-basket').click(function() {
var basket = $.cookie("basket") || []; //if not defined use an empty array
var $this = $(this);
basket.push({
'number': $this.attr('number'),
'type': $this.attr('product')
});
console.log(basket);
$.cookie("basket", basket);
});
});

Changing JavaScript variable dynamically

This is my program skeleton http://jsfiddle.net/zhwzY/
$(document).ready(function(){
$("#btnSend").click(function(){
var option = {
'delay' : false,
'helpSpanDisplay' : 'help-block',
'disableSubmitBtn' : false
};
if($('#agree').is(':checked')){
form_input = 'input:not("#reason")';
}else{
form_input = 'input';
}
var metric = [
[ form_input, 'presence', 'Please fill this textbox!']
];
$("#frm").nod(metric, option);
});
});
From the snippet, I try to make variable "form_input" to switch to a new value depend on the checkbox. With this method, I can prevent NOD (validation plugins) from validating unecessary input. But the variable "form_input" is not changing to the new value upon updating.
Please help.
P/s : No external reference to the NOD library in jsFiddle.

Categories