Adding more data to Dropzone.js post - javascript

So I have my implementation of this tutorial here: http://www.dropzonejs.com/bootstrap.html
It is working great, and I'm uploading files just fine. What I want to do now is be able to send a user id along with the image in the POST data when Dropzone uploads the image. I did find enyo's tutorial here which explains how to add hidden form data to the dropzone, but using the bootstrap tutorial dropzone provides, there is no form and therefore no hidden post data can be sent.
How can I use the code from the bootstrap tutorial linked to above, and yet still send hidden input data to the upload script? Do I have to somehow convert the code provided into a form, and if so, how would I do that?

It's been a while since you asked this question but based on the dropzone website tips
http://www.dropzonejs.com/#tips
you should be able to do one of 3 things -
1. if there is a form add hidden params.
2. you can use params like so -
new Dropzone({
url: "/",
params: {
foo: "bar"
}
});
3. handle the on sending event like so -
myDropzone.on("sending", function(file, xhr, formData) {
// Will sendthe filesize along with the file as POST data.
formData.append("filesize", file.size);
});

I find the tutorial you're providing a bit confusing since, indeed, there's no form involved. Simply create a form with class="dropzone" and add hidden inputs. It only shows the default template for dropped files and some JS code for basic event handling. I recommend checking out the main Dropzone page for examples.
For instance, in our code, it looks somewhat like this (redacted a bit) :
<form action="myAction"
class="dropzone"
id="dropzoneId"
name="pictures">
<input type="hidden" name="id">
</form>
And, really, that's it. We have some Javascript code to handle the hidden id field and some fancier features but the id gets posted along with the picture data.

I know this is a pretty old post but I tried to make the answer of SolarBear to work and it worked for me when adding the parameter "value" to the hidden input like this;
<form action="/action.php" class="dropzone">
<input type="hidden" name="additionaldata" value="valueToPass" />
</form>
Thanks for your help!

Related

Controls Webpage with Knockout: Visible changes not saved

Trying to edit a website with Excel VBA. The edits appear to work, but when I use the save button, nothing is saved. Why isn't updated data, which is visible on the screen, being saved?
This code opens a web page in internet explorer, navigates where I want, fills out data, all which show on the screen, using various methods, such as:
For Each objElement In objElementColl
ExtractedName = objElement.outerHTML
If InStr(ExtractedName, "NewPermit") > 0 Then
objElement.Checked = True
and
Set DropDown = objHTML.getElementById("ProjectFile-AccreditedCertifierId")
DropDown.selectedIndex = 1
or
objHTML.getElementsByName(ElementName)(0).Value = ValueCheck
All work and changes appear on the screen. I click save by using:
Set objElementColl = objHTML.getElementsByClassName("btn")
For Each objElement In objElementColl
ExtractedName = objElement.outerHTML
If InStr(ExtractedName, "click: save, enable:") > 0 Then
objElement.Click
ExtractedName = 1
Exit For
End If
Next
Which runs. The issue is it doesn't save the changes from the three pieces above.
What I have tried
Pause my code and manually click save (same issue)
Pause my code, manually change a checkbox and run the code to save (does save the manual change, but not the coded ones
Pause the code and manually change a box and manually save (only manually changed box is saved)
From above, it appears my save click works, but although the boxes are visibly changed and filled out using the code, there is a gap between the visible and the background.
Some HTML source code. Is what Chrome shows me when Inspecting an element I am changing:
<fieldset>
<legend>Proposal</legend>
<div class="col-xs-12 col-sm-8 col-md-6">
<div class="row">
<div class="col-xs-2 form-group">
<label for="ProjectFile_ProposalLot">Lot</label><input class="form-control" data-bind="textInput: ProjectFile().ProposalLot" maxlength="100" name="ProjectFile-ProposalLot" type="text" />
</div>
<div class="col-xs-2 form-group" data-bind="visible: ProjectFile().StateId() != 7 && ProjectFile().StateId() != 5">
<label data-bind="text: ProjectFile().ProposalDpLabel()"></label>
<input class="form-control" data-bind="textInput: ProjectFile().ProposalDp" maxlength="100" name="ProjectFile-ProposalDp" type="text" />
</div>
I searched the source code for the page. I believe this might be important, but I am not a HTML coder. I have shortened it a bit
var ProjectFileEditViewModel=(function(){__extends(ProjectFileEditViewModel,ViewModel.Model);function ProjectFileEditViewModel(){ProjectFileEditViewModel.__super__.constructor.apply(this,arguments);};ProjectFileEditViewModel.prototype.fields=function(){return {"Id":new ViewModel.NumberField(0),"StateId":new ViewModel.NumberField(0),"DefaultOfficeAddressId":new ViewModel.ObservableField(),"Name":new ViewModel.ObservableField(),"ExistingApprovalDate":new ViewModel.DateField("DD/MM/YYYY"),"ProjectClosed":new ViewModel.ObservableField(),"ProposalAddress":new ViewModel.ObservableChildField(exports.AddressViewModel,this),"Zoning":new ViewModel.ObservableField(),"ProposalLot":new return ProjectFileEditViewModel;})();if(exports.ProjectFileEditViewModel==null)exports.ProjectFileEditViewModel=ProjectFileEditViewModel;
There is also this:
Buildaform.model=new Buildaform.ProjectPageViewModel({ ... ,"ProposalLot":null .... }
I think this last one has something to do with it. I do not know if I can change it.
I cannot release the website address or source code publicly.
As the regarding web site can not be shared, I can come up with a just set of hints to try out:
If the web site would implement a simple (pure) HTML form to send the POST request, your solution would be fine. But looking at the HTML you shared
<label data-bind="text: ProjectFile().ProposalDpLabel()"></label>
the data-bind is already suggesting that the data is getting collected/sent by a library. (E.g. Knockout is using that attribute). This library might now collect the data somewhere, and it might get triggered by a "click" or a "key" event in JavaScript. The collected information can then be stored in a hidden DOM element as suggested by GCSDC or directly in a JavaScript variable.
What I would suggest now is to find out which JavaScript framework is used on this page by inspecting the HTML source. At some point there should be a
<script src="<fancy js framework>.js"></script>
tag in the HTML, which should give you the name of the framework. (There can actually be multiple tags of this kind, including custom JavaScript files. These tags do not have to be at the beginning of the HTML document, and can be scattered all over it, so you might have to search for script in the HTML document. One of them should be the main framework, which is sending the request. If you are not sure which one it would be, you have to google all of them and find out.)
Then, research how the the POST (maybe Ajax) request is sent in the JavaScript code on this page, with help from the documentation of the Framework. And then, send the request by executing custom JavaScript from VBA on this page; how this could be done is shown in this post.
Alternatively, you could try to trigger a click (or key) event on the form inputs to make the framework believe you actually typed it in; how this could be done is shown in this post, but this might not work in all cases.
Per your comment that:
Pause my code, manually change a checkbox and run the code to save
(does save the manual change, but not the coded ones
It seems that the problem is with the code setting form controls and not with the code clicking the save button.
This seems to be a problem not related to VBA but with the behaviour of knockout - see this SO post. The pertinent comment is:
Your problem is that ko subscribes on the click event inside the checked binding:
The questioner in that post is having a similar problem to you - they are trying to check a checkbox (to change the view) but it is not updating either the viewmodel, or the underlying model itself. Knockout is a MVVM framework.
The give-away in your question is that your manual changes commit because you perform a click-and-change when performing the action via point-and-click in the browser, but your programmatic method only does the change to the form control, but not the click first.
So, how to solve this via VBA automation through IE?
Based on the solution in the post I referenced above, plus the method here I will hazard the code below as a possible solution, but please note it is untested ...
Basically you need to 'click' on the form element you want to change - and then update the control value. Hopefully the 'clicking' bit will mean that the knockout viewmodel updates per the 'change', and from there, the model data will be written to the database (or whatever):
Your checkbox example:
If InStr(ExtractedName, "NewPermit") > 0 Then
// hopefully this will get knockout to apply the required binding before your change the value
objElement.Click
objElement.Checked = True
Your dropdown example:
Set DropDown = objHTML.getElementById("ProjectFile-AccreditedCertifierId")
// hopefully this will get knockout to apply the required binding before your change the value
Dropdown.Click
DropDown.selectedIndex = 1
Hope that helps - quite the 3-pipe problem! Good luck.

Angular JS ng file upload

i'm using Angular's JS well known ng file upload directive (https://github.com/danialfarid/ng-file-upload) in a project i'm working on, but i'm having an issues regarding validations. I added the ngf-pattern directive, in order to prevent users from uploading certain file formats. This works well, and each invalid file is available in the $invalidFiles array. Is there anyway to clear this array?
I am using $invalidFiles array in order to detect when invalid file was used, and alert the user. The file is not displayed in the UI, and not added to my model, but still I cannot submit the form because the form is invalid. only after I add a valid file I can submit the form. Is there a way to detect invalid files but still be able to submit the form ?
Hope I was clear.. Thanks!
Is this what you need : JsFiddle
$scope.submit = function() {
alert('form is ready');
}
Probably the thing you really need is ngf-change rather then ngf-select. Based on the documentation, the handler function you assign to ngf-change directive would be called whenever you select, drop, or cleared.
If the only thing you want to achieve is to allow form submission regardless it's valid or invalid, another approach would be leveraged on ng-model-options. There is an option called allowInvalid, by default it's false, set it to true would do the trick.
So in your example:
<button name="bla" multiple accept="image/*"
ngf-keep="true"
ng-model="myFiles"
ngf-pattern="'image/*'"
ngf-max-size="1MB"
ngf-change="handleFiles($files, $invalidFiles)"
ngf-model-options="{allowInvalid: true}">
Select Files
</button>
Notice the last two directives we have changed here.
For full reference, you may check the official document at the section of Full reference - File select and drop

How to Send an Image from the DOM, as Part of a Form

SHORT VERSION:
How do I attach an image object from the Document Object Model, using JavaScript, to a form so it can be sent to the server, without the user having to manually attach it using the input type=file tag?
Description:
I need a user to be able to look at a series of pics on a web page that were pulled in as the preview of a link he pasted, choose one, and have it automatically attach to a form, to be sent with text he wrote and processed by existing PHP as part of a new post, exactly as if he'd used an input type="file" interface to attach it.
The problem is that the pic exists in the browser as part of the Document Object Model, and it needs to somehow become an attachment into his form, to submit with his text as a new post. I've tried making a hidden input and making its value equal to the image, but that seems not to work.
The solution can be in jQuery, or hand-coded, I've been using JavaScript for 18 years, so I can understand either one...I just don't know how to attach a DOM object as a file to post to the server and process as part of a form.
Example Code:
This is not the actual code, which is complex and involves using JSON to pull a preview of a URL in PHP and send it back to the user, but it summarizes the problem:
<img id="image[0]" src="images/image0.jpg" onclick="attachimage(0)"/>
<img id="image[1]" src="images/image1.jpg" onclick="attachimage(1)"/>
<img id="image[2]" src="images/image2.jpg" onclick="attachimage(2)"/>
<form method="post">
<input type="text" name="title"/>
<textarea name="description"></textarea>
<input type="hidden" name="theimage" id="theimage">
<input type="submit" name="post" value="save">
</form>
<script>
var attachimage = function(item) {
// So far, nothing like this next line has worked for me,
// the image never shows up in the saved post
$("#theimage").val(document.getElementById("image[" + item + "]"));
}
</script>
CONTEXT:
I am working on a Wordpress website, using BuddyPress, to allow users to post their own links (a-la Digg and Reddit) without having Editor permission and using the Dashboard. I'm using a plugin called BuddyBlog (which uses bp-simple-front-end-post) to let users do this, which works fine...
But the owner also wants a preview to come up when they paste in a URL, just like it does on Facebook. I found nothing that already integrates the two features (user posts AND preview), so I pulled some open source code from the web that takes the URL, sends it via JSON to the server, which grabs the title, description, and images via PHP and sends the results back as a formatted HTML block. I then grab the values of those results and insert them into the BuddyBlog form fields...but BuddyBlog's form anticipates the image coming to it via:
<input type="file" name="bp_simple_post_upload_0">
...and I don't think I can simply set the value of bp_simple_post_upload_0 to be equal to the source of image[0]
If you've already processed the images on the server and created the previews, it means they're already there. So just pass in some variable representing which picture was selected and get the corresponding image. It's already on the server.
If the images are generated dynamically, with canvases or whatnot, you could send a base64 hash of them.

Submit form values to a script without loading a new page

I have an issue regarding sending form values to a script. I have a form set up, and upon the user pressing a button I want the values in the form to display on another part of the page. I can easily do this with php or another web scripting language, but all I know is how to do this by sending it to the script in a form of
http://www.example.com/myScript.pbp?value1=VALUE
is there a way to do this without loading a new page? Like just show a loading overlay on the page until the script completes and displays the value on the page?
I'm guessing this would be accomplished using Javascript or Ajax or something like that.
If anyone could help me out, or even just say where I should start to look, I'd really appreciate it!
Indeed. Just attach an onsubmit event listener to your form that always returns false to prevent actual sending of your form via the usual GET or POST request.
In your event listener you can send the form values using XMLHttpRequest and let the callback function update the relevant part(s) of your page.
But remember to always create a fallback option (with the usual GET or POST request of the form) to handle your form in case JavaScript is not available (e.g., turned off, blocked, etc.).
Yes AJAX would be exactly how you would do it. Have a look at the tutorial over at Tizag: http://www.tizag.com/ajaxTutorial/index.php
That will get you started in no time at all.
If you just want the values in the form to display on the page again without any interaction with the server then something like jQuery would be the best approach.
Jquery has a nice form plugin that you can do the following:
var form_values = $('#form_name').formHash();
the form_values will then be a hashed array of your form values in the system i.e.
<form id="test">
<input id="test1" name="test1" type="text" value="Test Text"/>
</form>
So form_values['test1'] would hold the value Test Text in it
Once you have the values you could then use some other jquery functions to display them on the page i.e.
<div id="displayDiv"></div>
then your javascript could be
for (key in form_values) {
$('div#displayDiv').append('<div>Key: ' + key + ' Value: ' + form_values[key] + '</div>');
}
This would put your values in the display div
Here is a simple javascript ajax object. You can use without loading any library.

Non-AJAX jQuery POST request

I am trying to use the jQuery POST function but it is handling the request in AJAX style. I mean it's not actually going to the page I am telling it to go.
$("#see_comments").click(function() {
$.post(
"comments.php",
{aid: imgnum},
function (data) {
}
);
});
This function should go to comments.php page with the aid value in hand. It's posting fine but not redirecting to comments.php.
#Doug Neiner Clarification:
I have 15 links (images). I click on a link and it loads my JavaScript. The script knows what imgnum I opened. This imgnum I want in the comments.php. I have to use this JavaScript and no other means can do the trick. The JavaScript is mandatory
Your method successfully POSTs the aid value. But in the comments.php when I try to echo that value, it displays nothing.
I am using Firebug. In the Console, it shows the echo REQUEST I made in Step (2) successfully.
I know what you are trying to do, but its not what you want.
First, unless you are changing data on the server, don't use a POST request. Just have #see_comments be a normal <a href='/comments.php?aid=1'>...
If you have to use POST, then do this to get the page to follow your call:
$("#see_comments").click(function() {
$('<form action="comments.php" method="POST">' +
'<input type="hidden" name="aid" value="' + imgnum + '">' +
'</form>').submit();
});
How this would actually work.
First $.post is only an AJAX method and cannot be used to do a traditional form submit like you are describing. So, to be able to post a value and navigate to the new page, we need to simulate a form post.
So the flow is as follows:
You click on the image, and your JS code gets the imgnum
Next, someone clicks on #see_comments
We create a temporary form with the imgnum value in it as a hidden field
We submit that form, which posts the value and loads the comments.php page
Your comments.php page will have access to the posted variable (i.e. in PHP it would be $_POST['aid'])
$("#see_comments").click(function () {
$('<form action="comments.php" method="POST"/>')
.append($('<input type="hidden" name="aid">').val(imgnum))
.appendTo($(document.body)) //it has to be added somewhere into the <body>
.submit();
});
While the solution by Doug Neiner is not only correct but also the most comprehensively explained one, it has one big problem: it seems to only work at Chrome.
I fidgeted around for a while trying to determine a workaround, and then stumbled upon the second answer by devside. The only difference is the extra code appendTo($(document.body)). Then I tested it in firefox and it worked like a charm. Apparently, Firefox and IE need to have the temporary form attached somewhere in the DOM Body.
I had to do this implementation for a Symfony2 project, since the path generator inside the .twig templates would only work with GET parameters and messing with the query string was breaking havoc with the security of the app. (BTW, if anyone knows a way to get .twig templates to call pages with POST parameters, please let me know in the comments).
i think what you're asking is to get to 'comments.php' and posting aid with value imgnum. The only way to do this is to submit this value with a form.
However, you can make this form hidden, and submit it on an arbitrary click somewhere with jquery.
html necessary (put anywhere on page):
<form id='see_comments_form' action='comments.php' action='POST'>
<input id='see_comments_aid' type='hidden' name='aid' value=''>
</form>
js necessary:
$("#see_comments").click(function(){
$('#see_comments_aid').val(imgnum);
$('#see_comments_form').submit();
);
this will redirect to 'comments.php' and send the proper value imgnum (that i assume you are getting from somewhere else).
Actually, $.post() sends some data to the server. It does not cause any redirection unless you do it in your server side code which handles the POST request. I can suggest two solutions:
To go to comment page, instead of using JQuery post, you can simply use a 'anchor' tag - Show Comments.
Or if you are want to go through JQuery, you can use this code snippet: $(location).attr("href", "comments.php?aid=1");
didnt exactly solve the problem. but did manage to work around it. i had to do a lot modification to the JS to make this work, but the core problem of this question was solved by doing this:
$("#see_comments").attr({href: "comments.php?aid='"+imgnum+"'"});
this appended the aid value to the URL as #Doug Neiner initially suggested me to do.
Thanks a lot Doug for all the effort. I really appreciate. +1 and accept to your answer for the effort.

Categories