Can I "namespace" an ajax POST request that uses FormData? - javascript

I found this answer explaining how to use a FormData object to upload a file over ajax. I'm wondering if it's possible to rearrange the data structure that's sent over in the POST request.
My backend is in rails, and the controller expects the data like this:
xmlFile: {
some_property: 1,
attachment: [the file]
}
However, if I use a solution similar to the one from the above link, something like
var data = new FormData();
data.append('some_property', id);
data.append('source', file);
(where file is a File object), and then submit that with $.ajax
$.ajax({
url: url,
data: data,
processData: false,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data'
});
the form submits, but the data isn't namespaced under xmlFile. If I try to do something like
$.ajax({
url: url,
data: {xmlFile: data},
processData: false,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data'
});
it doesn't work. The request data just shows [object Object].

Related

Sending FileList using Ajax to PHP script

I'm trying to send array files using JS. My code:
var formData = new FormData();
formData.append("files", files);
$.ajax({
url: './upload.php',
method: 'post',
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert('Files uploaded successfully. ');
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
In this image you can see the response(red) from php https://beta.ctrlv.cz/mUwx and also you can see the files array data. My php code is:
<?php
echo $_POST['files'][0]["name"];
?>
I want use php script for upload, but the ajax didn't sent the array of file, which is important for uploading.
Here's an answer that I found:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have a FormData object, ready to be sent along with the XMLHttpRequest.
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Here the source: https://stackoverflow.com/a/5976031/7282094
Hope that help.
Change contentType: false, to contentType: "multipart/form-data", possibly.
Taken from http://api.jquery.com/jquery.ajax/
contentType (default: 'application/x-www-form-urlencoded;
charset=UTF-8') Type: Boolean or String When sending data to the
server, use this content type. Default is
"application/x-www-form-urlencoded; charset=UTF-8", which is fine for
most cases. If you explicitly pass in a content-type to $.ajax(), then
it is always sent to the server (even if no data is sent). As of
jQuery 1.6 you can pass false to tell jQuery to not set any content
type header. Note: The W3C XMLHttpRequest specification dictates that
the charset is always UTF-8; specifying another charset will not force
the browser to change the encoding. Note: For cross-domain requests,
setting the content type to anything other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain
will trigger the browser to send a preflight OPTIONS request to the
server.

$.ajax post doesn't post data (JavaScript)

I can't figure out why this problem is arising. When I make an ajax post request in my javascript file, the url gets called, but the data wont get sent. Here's how I make a post request:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "/test",
dataType: "json",
data: {test: "test"},
contentType: "application/x-www-form-urlencoded",
});
</script>
And on my backend, here's the post method I'm using:
app.post('/test', function(req, res) {
console.log(req.body); // returns {}
console.log(req.params); // returns {}
});
Here's what I tried so far: XMLHttpRequest to Post HTML Form, AJAX Post not sending form data , Send POST data using XMLHttpRequest but unfortunately none of them worked for me.
dataType: "json" expects data in JSON, but contentType: "application/x-www-form-urlencoded" sends data in different way. Maybe you should write dataType: "json", contentType: "application/json" or dataType: "html", contentType: "application/x-www-form-urlencoded"?

How to get a file from local disk then pass that to a POST method to upload to server

I have an input tag of type file. I use this to get a file from my local disc. What I need is a way to get and hold that file so I can POST it to a server.
<input type='file'>
//I now want to hold this file and pass this to this ajax post method
$.ajax({
type: "POST",
url: url, //I have URL, this isn't a problem
data: data, // do I place response here ?
success: function(){ alert('file posted')
dataType: dataType // ?
})
You have to post form data to the server through ajax. Try Following.
$.ajax({
url: url,
type: "POST",
data: new FormData('#yourForm'),
contentType: false,
cache: false,
processData:false,
success : function(){
// success message.
}
});
#yourForm is your form. if you are using form submit event then replace this by 'this' keyword.
So the formData is your form's data. and fetch file input by name on server.

send json data to another url - after you've got it back from my own url

This is how the json I get from my page send when I clicked post, I throw a different URL.
That piece of data should like to come to look like this:
api.quickpay.net/subscriptions?currency=dkk&order_id=testworld&description=MB: 6-testworld
But when I get my json back watching it like this:
{"Prices":220,"HiddenIdMedlemskab":6,"ordre_id":"6-8315042016","currency":"DKK","description":"MB: 6-8315042016"}
The json should I have shed into a url that I added earlier.
My jquery code looks like this:
$.ajax({
type: 'post',
url: '/Medlem/medlemskabet',
dataType: 'json',
data: JSON.stringify(requestData),
contentType: 'application/json; charset=utf-8',
async: true,
processData: false
});
Over on my url /Medlem/medlemskabet
That gets the dates that I need for my json to specify package price orderid etc
So my question is How do I tag my json about throwing it over to the api URL and throws it into their system.
I've built since the MVC C #
You can pass the JSON object as an argument to $.get(), and jQuery will convert the properties into URL parameters.
$.ajax({
type: 'post',
url: '/Medlem/medlemskabet',
dataType: 'json',
data: JSON.stringify(requestData),
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
success: function(response) {
$.get('api.quickpay.net/subscriptions', response);
}
});

Stop jQuery.ajax() from passing parameters with "_json" as master parameter name?

Assume we use jQuery.ajax() to POST data with two parameters, game_id and player_id.
When we use jQuery.ajax(), the server receives parameters like this:{"_json"=>"game_id=4f6a593a8cb45b16c0000491&player_id=4f68ed4b8cb45b16c0000111"}
We would like the server to receive parameters like this:
{"game_id=4f6a593a8cb45b16c0000491&player_id=4f68ed4b8cb45b16c0000111"}
Essentially, ajax() makes "_json" the master key for all parameters. Is there a way to prevent this, or are we doing something wrong?
Here's some specific code:
$.ajax({
type: 'POST',
url: UPDATE_GAME_URL,
data: { "game_id" : game_id,
"player_id" : get_player_id(),
"turn_set" : JSON.stringify(turn_set) },
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
Thanks!
jQuery does not contain any code that prefixes fields with json_ so the problem is somewhere else.
However, you need to remove contentType: 'application/json; charset=utf-8' to ensure the server parses the POST data correctly - you are not posting JSON after all.
If your server does expect a JSON payload (according to the string you expect to receive it doesn't!), you would have to use data: JSON.stringify({...}) to ensure you actually send a JSON string instead of form-encoded key/value pairs.
$.ajax({
type: 'POST',
url: UPDATE_GAME_URL,
data: { "game_id" : game_id,
"player_id" : get_player_id(),
"turn_set" : turn_set },
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
You don't need to stringify the turn_set, jQuery will do it for you.

Categories

Resources