jQuery Ajax PUT an attachment to CouchDB doc - ajax

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.

Related

Render a view while Ajax expects a response

I am building an express project, using ejs as a view engine, and AJAX for front-end http calls.
When I post a request such this:
$.ajax({
type: 'POST',
data: {'nickname' : $('#nickname').val()},
contentType: 'application/x-www-form-urlencoded',
url: 'http://localhost:5000/create',
success: function(data) {
$('#message').text("Unkwon error");
},
error: function(data){
$('#message').text('Something went wrong, check connection!');
}
The Ajax keeps waiting for a response, which I am not willing to give, as I just want to render a view as follows :
app.post('/create', urlencodedParser, (req, res)=>{
let code = unique.generate(rooms);
res.render('chat', {'nickname' : req.body.nickname, 'code' : code}
Any ideas how can I work around this?
After some research, I found a way to do it.
Basically, I can just tell the Ajax to attach the document sent from rendering to the html body
$('body').html(data);
Surprisingly, this works event with Ejs dynamic tags.
I know it's not the best way to do it, but it's the only one I found till now.
EDIT 1:
After few months, I realized the solution is simple as just changing the Location using javascript
window.location.replace(`http://localhost:5000/newRequest`);
Now, I could handle this new request separately on the server.
EDIT 2:
After couple years now, I realized a GET request might have solved the problem in a single round trip.

Accessing the information in build.settings through an ajax request

So I know you can use json files to load data into a store, but I was wondering if there exists a way to make a request to only access a single "variable", in a similar way Ux.Locale.Manager works.
To be more specific, I'm working with an app built on Sencha Architect, and I would like one of the views to contain the version of the app. While I could just hardcode that label and update it every time I make a build, I was wondering if it was possible to just access the information in the build.settings file, specifically the versionString and versionCode variables, to make things easier? And if possible, how would I go about making an ajax request without involving a Model and a Store?
I figured it out. I kept thinking I had to make a call with an AjaxProxy, but a simple Ext.Ajax.request did the trick:
Ext.Ajax.request({
url: 'build.settings',
method: 'GET',
success: function(response, opts){
var data = JSON.parse(response.responseText);
Ext.getCmp('appVersion').setHtml("version " + data.androidBuild.versionString + "." + data.androidBuild.versionCode);
}
});

Allow my Tumblr blog's content to be accessed by another page

I'm attempting to copy all of the actual content from my Tumblr blog using a script I wrote on a different web page, but I'm having a bit of trouble with gaining access to the content. My ajax call is as follows:
$.ajax({
url: "http://solacingsavant.tumblr.com/",
dataType: 'jsonp',
success: function(data) {
var elements = $("<div>").html(data)[0].getElementsByTagName("ul")[0].getElementsByTagName("li");
for(var i = 0; i < elements.length; i++) {
var theText = elements[i].firstChild.nodeValue;
alert(theText); // Alert if I got something
// This is where I'll strip the data for the items I want
}
}
});
but as it is the console gives me an error of "Resource interpreted as Script but transferred with MIME type text/html" which I looked into here and changed the corresponding meta tag in the HTML of my blog to <meta http-equiv="Content-Type" content="application/javascript; charset=utf-8" /> with no success
I also tried using dataType: 'html' (which makes more sense to me) but I was getting a console error of "Origin is not allowed by Access-Control-Allow-Origin" which I also looked into and added a meta tag to my Tumblr blog with <meta Access-Control-Allow-Origin="*" />, but again didn't succeed
Here is a jsFiddle to work with
Does my approach not work because Tumblr as a whole does not allow changes to Access-Control? If so, how might I work around the issue? If not, what am I doing wrong?
MAJOR EDIT (based on mikedidthis's helpful comments)
It seems that I am not able to do this without a Tubmlr API, so I obtained an API key and now have access to the json results that the API sends out. I am able to get a jsonp object using the API key to in the console. My javascript at the moment:
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/info?api_key=APIkeyGoesHeRe",
dataType: 'jsonp',
success: function(results){
console.log(results);
// Get data from posts here
}
});
This SO post was helpful in understanding how I can change data on my Tubmlr page from the source and find out basic information about the site, but not about how to obtain actual data from individual posts. I tried looking through the results object and was unable to find any data related to posts, nor was I able to append the results to the jsfiddle. So my questions now are, "Can I copy data (say the written text in a post) from individual posts using this approach? If so, how? If not, what other approach should I use?"
A really quick answer
The tumblr API documentation really covers using the API well, however, to give you a little start, lets grab all your Text Posts.
First you need to query the API for any of your post that are of the type Text.
The documentation states (http://www.tumblr.com/docs/en/api/v2#posts) that we should use the following url and specifying the type which we you will set to text:
api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts[/type]
And below is an example based on the OP fiddle.
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/text?api_key=XXXXXXX",
dataType: 'jsonp',
success: function(data){
posts = data.response.posts
$.each(posts, function(i) {
console.log( posts[i].title, posts[i].body )
});
}
});
So for each query of the API, we will receive back an object. You will need to filter this object to get the data you want from it.
In context of the post queries, you can get directly at your posts using data.response.posts object.
To find out what data is available for each post type, the documentation has it covered: http://www.tumblr.com/docs/en/api/v2#text-posts
To the content for each of the Text post types, you need to loop through the posts object and then grab the value for the key named title and body.
Example here: http://jsfiddle.net/ZpFwL/
Bonus Time
It is possible to get posts for all types, by dropping the type from the URL:
http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/?api_key=XXXXXXX"
Remember this is a really, quick example and not for the real world.

Send ONE Javascript variable to PHP via AJAX

I've been looking around the forums without a solution to my problem. It's pretty simple, really, and I'd appreciate it if you could explain your answer if you would be so kind.
I'm new to AJAX and Javascript, and I need to send one variable from my javascript code and basically "convert" it into php. Here's what I have so far:
var selected = rowData.ID
jQuery.ajax({
url: "test.php",
type: 'POST',
data: { selected },
cache: false
});
I use this selected value further down in the code. I use PHP to display the (value of selected).
"vars": [
"(value of selected)"
],
However, I can't seem to make my ajax request work and send the variable to my PHP file. Here's what my PHP file looks like:
$row = $_POST["selected"];
Thanks in advance for the help.
try replacing your "data:" with this:
data: { 'selected': selected },
So this is very delayed answer, but I was having trouble getting a variable to send too. I'm not using php, but saw loads of examples like vlscanner gave, but who knows why it didn't work.
I stumbled across this explanation of how to send multiple parameters, and it works just as lovely for sending one parameter.
http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods
multiple:
data: JSON.stringify({ Album: album, User: user, UserToken: userToken }),
or just one:
data: JSON.stringify({ Album: album}),
I'm no expert on timing,efficiency and all that, and it's possible that JSON.stringify adds unnecessary bulk and there is possibly some valid reason that sending data without the JSON.stringify didn't work. However, if you are in a bind and need something to work, this might help those of us still asking this question.
I'm suspecting that mine did not work because I was sending it to an asp method that likely requires the parameters to come as a JSON string. I have to research that next. Every step is a new discovery.

jQuery AJAX Form, cannot send array?

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 :)

Resources