jQuery AJAX Form, cannot send array? - ajax

I'm practicing my jQuery skills (ok, learning too) and experienced an issue. I got a file upload form with file input. I'm using this plugin (http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Uploading) to upload multiple files at once. So I'm using following form input:
<input type="file" class="multi" name="photo[]" accept="gif|jpg|jpeg|png" maxlength="5"/>
Now... I'm trying to send an AJAX request to php file that will handle upload and server-side validation:
$('#upload_photos_s').click(function(q){
var photo = $('[name=photo[]]').val();
// Process form
$.ajax({
type: "POST",
url: "upload.php",
data: 'photo[]='+photo,
success: function(html){
alert($('[name=photo[]]').val());
$("#photo_upload_form").html(html);
}
});
return false;
});
While using Firebug I can see that there's only one file in photo[].
Any suggestions why? Is there something I missed?
Regards,
Tom

As it stands, you are indeed querying the value of the first photo[] member only. photo[].val() will not return an array containing all the values.
You would have to run through each member of photo[], e.g. using each(), to build an array of values.
However, I'm not sure this is the right path to go for whatever you want to do. You are aware that what you are doing is uploading the file names only, not their data?
It is not possible to upload files using AJAX without the help of additional tools like Flash-based SWFUPload. This is for security purposes to prevent scripts from having direct access to local files.
Maybe what you're trying to do is best suited for an approach where the form's target property points at an <iframe>. That would not trigger a reload of the page, but still submit the form the "traditional" way, allowing for old-school file uploads.

Well on the link you provided, there is a part called Ajax specifying the simplest way is to use the jQuery Form Plugin.
Documentation of plugins help a lot usually ^^.
Have a nice day :)

Related

RoR - optionally filling form fields based on external data

I recently started with Rails, making some good progress but hit another snag now.
I have a form that users should fill out manually. An example would be something like a human resources pages where one can enter name, address, phone number of an employee.
What I would want to do is have another field "remote_id" that is optional and when filled out, will do a REST call to a remote resource to retrieve name/address/phone number and fill out the form on the fly but not immediately submit it. A time saver, if you will.
And I have no clear idea of what that would entail in terms of form filling (the controller action for the remote call is probably not a problem), but it seems to go beyond what rails will do "out of the box". JQuery, AJX, something else? A pointer would be really appreciated!
Cheers,
Marc
The most important thing you need to check out for is the url of the remote resource and possible need to authenticate your request before having access to the resource. You might then make an ajax request to the resource. Using jQuery
$("remote_id").click(function(event){
event.preventDefault()
$.ajax("http://externalresourceurl.com", {
success: function(data) {
// fill each form field with corresponding item in the data object
$('#first_name').html($(data).first_name);
...
},
error: function() {
$('#notification-bar').text('An error occurred');
}
}
);
});

How to get a HTTPRequest JSON response without using any kind of template?

I am new to Django but i am advanced programmer in other frameworks.
What i intend to do:
Press a form button, triggering Javascript that fires a Ajax request which is processed by a Django View (creates a file) that return plain simple JSON data (the name of the file) - and that is appended as a link to a DOM-Element named 'downloads'.
What i achieved so far instead:
Press the button, triggering js that fires a ajax request which is process by a Django view (creates a file) that return the whole page appended as a duplicate to the DOM-Element named 'downloads' (instead of simple JSON data).
here is the extracted code from the corresponding Django view:
context = {
'filename': filename
}
data['filename'] = render_to_string(current_app+'/json_download_link.html', context)
return HttpResponse(json.dumps(data), content_type="application/json")
I tried several variants (like https://stackoverflow.com/a/2428119/850547), with and without RequestContext object; different rendering strats.. i am out of ideas now..
It seems to me that there is NO possibility to make ajax requests without using a template in the response.. :-/ (but i hope i am wrong)
But even then: Why is Django return the main template (with full DOM) that i have NOT passed to the context...
I just want JSON data - not more!
I hope my problem is understandable... if you need more informations let me know and i will add them.
EDIT:
for the upcoming questions - json_download_link.html looks like this:
Download
But i don't even want to use that!
corresponding jquery:
$.post(url, form_data)
.done(function(result){
$('#downloads').append(' Download CSV')
})
I don't understand your question. Of course you can make an Ajax request without using a template. If you don't want to use a template, don't use a template. If you just want to return JSON, then do that.
Without having any details of what's going wrong, I would imagine that your Ajax request is not hitting the view you think it is, but is going to the original full-page view. Try adding some logging in the view to see what's going on.
There is no need to return the full template. You can return parts of template and render/append them at the frontend.
A template can be as small as you want. For example this is a template:
name.html
<p>My name is {{name}}</p>
You can return only this template with json.dumps() and append it on the front end.
What is your json_download_link.html?
assuming example.csv is string
data ={}
data['filename'] = u'example.csv'
return HttpResponse(simplejson.dumps(data), content_type="application/json")
Is this what you are looking for?

jQuery Ajax PUT an attachment to CouchDB doc

I have code that does POST attachments to Couch docs using jquery.form.js. That's all good, but I really need to allow the user to enter multiple files in the form, let's say 5 files for now, then in code iterate the five files in the form, creating one new Couch doc and attachment for each file. This is veeeery difficult if not impossible using only jQuery. It could be done using Couch "inline attachments" but then you would need a server-side (PHP probably) script to Base64 encode the binary image data. This really isn't an option for me because this is a Couchapp.
So the following code doesn't work, it generates an "invocation" error in jQuery. My assumption is that you can't simply add the reference to a binary file in the data attrib...
var url= _.couchUrl() + me.photoArgs.db +"/" +
couchDoc._id + "/attachment?rev=" + couchDoc._rev;
$.ajax({
type: "PUT",
url: url,
headers: {
"Content-Length": file.size,
"Content-Type": file.type
},
data: file,
success: function (response) {
console.log("Attachment was uploaded");
me.fileCnt--;
if (me.fileCnt == 0) console.log("Attachment(s) uploaded");
},
error: function (response) {
_.flashError('Attachment ajaxSubmit failed',me,response);
}
});
The code is clipped from inside a larger function. I've logged the url and the file, they both have correct data so they're not the issue.
Does anyone think the above should work? If so, what am I doing wrong?
Thanks a lot for your advice :-)
You have two options there:
Use inline attachments. You don't have to use PHP to decode base64 data: just add to your CouchApp /_utils/script/base64.js file (yes, it ships with CouchDB Futon) as CommonJS module and you'll be fine.
Use Multipart API (scroll a bit down for an example). I haven't much experience with jQuery to quick make a working prototype, but this question you may found helpful.
Update: found good working example how to upload multiple binary attachments to CouchDB using multipart API.

ajax url for jstree on couchdb (via list function)

I have a CouchDB list function returning the html for the jstree. I am not sure if the url in my HTML form, to invoke the list is correct, since the jstree doesn't render. (with the same html pasted locally, it does). CouchDB is running on localhost.
The location of my list function is standard, "appname/app/lists/myList.js". I have tried several combinations of url, on the lines of "/appname/_design/appname/_list/listname/viewname".
What should be the correct form ?
Thanks.
The format should be as follows:
GET /db/_design/design-doc/_list/list-name/view-name
I copied this directly from the CouchOne Documentation.
OK, since I couldn't find a definite answer for rendering jstree with dynamic data using a CouchDB list, I went the other way and used after.js functionality in evently.
This is for anyone who might find it useful. This is what worked for me,
get the data using data.js
render it as <ul><li/></ul> in mustache.html
in after.js write the function for jstree as shown in the jstree documentation for html_data plugin
(after.js looks like this
function (e) {
$('.mytree').jstree({
"plugins" : [ "themes", "html_data", "checkbox" ]
});
}

Is it possible to send a form and a html request with same Event by Mootools?

$('submitbutton').addEvent( 'submit', function(e){
e.stop();
$('fuss').send();
req2.send();
});
trying to get this working but not sure if it is possible and had no success so far.
Mootools docs doesnt helped me either.
Will the multiple usage of .send() work?
Do i have to specify the data beeing send for the html request or does it take automatical the data beeing send by the form ?
It's in the documentation: http://mootools.net/docs/core/Request/Request#Element:send
This shorthand method will do a request using the post-processed data from all of the fields.
You can do as many requests in a specific event as you wish, as long as they're all asynchronous.
In your specific example it would seem you want to do two requests using two different methods, one with setting up a new Request class manually and the second doing it via the Element Method.
Based on your last comment, I wrote a little example in jsFiddle.
Basically I think you don't need two request for your goal. Just override onRequest method to update the html.

Resources