I have a jQuery function on a separate functions.js file, that is in charge of making a SQL update by posting some info. This is working properly, here you can see it:
Function being called on my php file, passing just element's ID info:
$('.tableContent').on('click', '.discontinueIcon', function() {
turnId = $(this).attr('data-id');
discontinueRow();})
Function working properly on a separate functions.js file:
function discontinueRow(){
row = '#' + turnId;
$.post('config/forms/turn_conf/turn_discontinue.php', { tu_id:turnId }).success(messageOKKKK);}
As I will need to create many more functions updating info from many tables, I was trying to have a unique function, and provide it with needed info being sent with parameters from the php files. As I am new to this, do not even know if it is possible, and if it is I definitely can't get the way to.
I tried to store the needed values on several variables on my php file:
$('.tableContent').on('click', '.discontinueIcon', function() {
turnId = $(this).attr('data-id');
action = "'config/forms/turn_conf/turn_discontinue.php'";
elements = "tu_id:turnId";
discontinueRow(action,elements);})
And using these parameters on the separate functions.js file as this shows:
function discontinueRow(action,elements){
row = '#' + turnId;
$.post(+action+,{ +elements+ }).success(messageOKKKK);}
But this does not work. Is it possible to pass by this way parameters to a function? In this case, what is going wrong here?
You can do it like this:
$('.tableContent').on('click', '.discontinueIcon', function() {
turnId = $(this).attr('data-id');
discontinueRow('config/forms/turn_conf/turn_discontinue.php', { tu_id:turnId });
});
you also need to set up your function with input parameters:
function discontinueRow(url, params){
row = '#' + turnId;
$.post(url, params).success(messageOKKKK);}
}
Related
I'm building this website: http://collections.design
The way it works is by reading all tools data from a JSON, using jQuery (I don't know much javascript). Then, you can click on an item and a side panels opens with further information. But there's a lot of repeated code, so I'm trying to optimise it a bit.
First I parse the JSON:
// The data source
var data_source = "../data/tools/tools.json";
// Parsing the JSON
$.getJSON(data_source, function(data) {
$.each(data, function(key,val) {
// And I'm storing all of its values in variables, to make them easier to read:
var name = val.availability.name;
var linux = val.os.linux;
// Then I'm using all that to render each item on screen
…
});
});
Each of the items has a button that calls another function to create and open the side panel. The side panel reuses that item's data from the JSON. This function to create the side panel is using the name variable as parameter, but then inside is parsing the JSON again to get the rest of the values it needs.
My question is:
How can I "encapsulate" all variables when I do the JSON parsing, then pass it as a parameter to the other function; and finally, individually read each of those values in the other function?
I tried working with arrays. But didn't manage it to work, also keeping in mind that I'm trying to simplify things, not repeat myself, and keep short names…
Maybe I'm asking too much, but any pointers or links to doc will be appreciated.
I see two ways of doing this.
1) Save the JSON data outside the scope so you can reuse it and pass the index of the data you want.
Something like this
// The data source
var data_source = "../data/tools/tools.json";
var all_data;
// Parsing the JSON
$.getJSON(data_source, function(data) {
all_data = data;
$.each(data, function(key,val) {
$('.button').on('click', function() { callToOtherFunction(key) })
});
});
function callToOtherFunction(key) {
console.log(all_data[key]);
}
2) As Sam Axe said, pass the data directly to the function
// The data source
var data_source = "../data/tools/tools.json";
// Parsing the JSON
$.getJSON(data_source, function(data) {
$.each(data, function(key,val) {
$('.button').on('click', function() { callToOtherFunction(key) })
});
});
function callToOtherFunction(val) {
console.log(val);
}
Here's a working fiddle.
The data is already "encapsulated" in the data object. Pass that object to the function that you want to use the data in.
You could always construct a new object - but what's the point - it's already in the data object.
I want to pass multiple values to a function in uploadify.
The way you call a function is like this
$("#id").uploadify("upload", fileId);
here fileId is id of only one file to be uploaded.
I have a scenario where i itertate over a table to get file ids to upload then i want to pass those ids to this function call. How can i do that.
and here is currently what i am doing, which obviously isn't working.
var imagesToUpload = [];
$.each(data.validationResult, function (index, obj) {
var imageToUpload = GetFileToUpload(obj.ImageName);
if(imageToUpload){
imagesToUpload[imageToUpload] = imageToUpload;
}
});
$("#id").uploadify("upload", imagesToUpload);// this is not working
You can use Function.prototype.apply() to pass arguments to a function as an array.
$('#id').uploadify.apply(null, ['upload'].concat(imagesToUpload));
This assumes that imagesToUpload is an Array of the arguments you want to pass.
I'm using a countdown script from mike giesson to create some sort of Day Deal function. The script has an onComplete function. The product data comes from a json file.
I build the product html with a getJson query. This is functioning good. The only thing I try to achieve is that when the onComplete function is fired the second object in the json file is called. After that the third etc...
Is this even possible? I have other options, like building for example 5 products and hide and show when done. I thought it would be nicer to build it this way :)
So what I have done:
jQuery
function getDaydealProducts(){
$.getJSON('url/page1.ajax', function(data){
var productsHtml = [];
$.each(data.products, function(index, product){
var productHtml =
'<div class="item">' +
... etc .... + '</div>';
productsHtml.push(productHtml);
});
productsHtml = productsHtml.join('');
$('.clock').html(productsHtml);
});
)
var myCountdown1 = new Countdown({
onComplete : countdownComplete
});
function countdownComplete(){
getDaydealProducts(); //get second product.
}
So I tried to build a function that grabs the products, then start the counter. After that a new json call needs to be done with the second object.
Is that possible? And can somebody give me some directions?
thx
I'm trying to use the Ajax File Upload as featured here: http://valums.com/ajax-upload/
As you can see, I need to create a qq.FileUploader object to initialize the script. However, I need to be able to dynamically create this objects without knowing the IDs of the elements. I've tried creating something like this:
var uploader, i = 0;
$(".file-upload").each(function() {
$e = $(this);
i++;
uploader[i] = new qq.FileUploader({
element: $(this)[0],
action: 'uploadfile.php',
allowedExtensions: ['doc', 'docx', 'pdf'],
multiple: false,
onComplete: function(id, fileName, responseJSON) {
$($e).siblings('input').val(responseJSON.newfilename);
}
});
});
I've learned that the [i] part I have added breaks the script, because I cannot have objects inside of an array.
Is there another way I can create this objects dynamically? They need to all have a unique name, otherwise the onComplete function gets overwritten for all of them. I experimented with using eval(), but I can't seem to make it work correctly.
You have to declare uploader as an array first :
var uploader = [];
Because you declared the variable without defining it, it has the default value of undefined , and your code was translated into something like undefined[i] which triggers an error.
Has to be something like
var uploader = {};
or else uploader is null and you cannot assign anything to it.
EDIT:
So there're two opitions, in my opinion, if one wants to have an array than it makes sense to declare one, var uploader = []; and then use the uploader.push() method or define it as an object var uploader = {}; and just do uploader[i] = ....
It is also possible to do the latter with an a array, but in the latter case I see no point in maintaining the counter (i).
How do I map calls to a Grails controller from a Javascript method? I see a method using PHP, but not with grails:
function getSelected(checkList)
{
var idList = new Array();
var loopCounter = 0;
//find all the checked checkboxes
jQuery("input[name=" + checkList + "]:checked").each
(
function()
{
//fill the array with the values
idList[loopCounter] = jQuery(this).val();
loopCounter += 1;
}
);
//call here
}
Edit:
${remoteFunction(controller:"person", action:"runThroughAll", params:"[ids:idList]")}
So, I feel like there are sort of two things you're asking here. I'm going to tackle them both. First, how do you get the URL right for a call to a grails controller from JavaScript? In my GSP page (I do it in my main layout but whatever), I like to do this little trick:
<script>
myapp.url.root = "<g:resource dir='' file='' />" + "/";
</script>
That will give you the base root of your app wherever it's deployed. Then, you can build your URLs in JavaScript:
myurl = myapp.url.root + "path/to/controller"
Then make a jQuery ajax call using that url.
Then make sure that your controller is set up to respond to whatever URL pattern you've just expressed.
The second question appears to be, "how can I send back an HTML fragment"?
Inside the controller itself, take the parameters from the request, use it to figure out whatever you need, then render the gsp, passing in the model you've created. It will look something like this:
def show() {
def data = [hypothesis : metadataService.getHypothesis(params.id) as JSON]
render(view:"create", model:data)
}
Then in jQuery, your success handler will get as an argument the returned response, which you can then inspect/manipulate/add to the dom.
Hopefully all that made sense. If I glossed over something or didn't answer the question you were asking, let me know.
EDIT: For future reference, here is the javascript method rewritten which we arrived at in chat:
function getSelected(checkList){
var idList = $("input[name='" + checkList + "']:checked").map(function(){ return $(this).val(); });
$.ajax({
url: "/path/to/controller",
type:"POST",
data:{ids:JSON.stringify(idList)}
success:mySuccessFunction
});
}