Sending FileList using Ajax to PHP script - javascript

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.

Related

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);
}
});

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

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].

ajax response error(XML Parsing Error: no element found Location: moz-nullprincipal)

i am unable to get the response from ajax. please guide me how to resolve this error, i am getting successful data return from the server i have checked it in fiddle web debugger and still ajax is showing error.
XML Parsing Error: no element found Location: moz-nullprincipal:{6b0a1ac2-50ab-4053-9f71-8ae49202288d} Line Number 1, Column 1:
$j.ajax({
type:"POST",
url:'http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit',
data: 'Celsius=12',
crossDomain:true,
async: false,
success:function(response)
{
alert("Success Full Done"+response.string);
},
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
}
});
I've this problem with request:
$.ajax({
type: "POST",
url: ajaxUrl,
dataType : "json",
contentType: "application/json",
data: JSON.stringify(data),
success: function (data) {
...
}
});
Accept header in request is:
Accept application/json, text/javascript, */*; q=0.01
Response status is 200, but browser detect error and no success callback called
Fixed by remove dataType : "json":
$.ajax({
type: "POST",
url: ajaxUrl,
contentType: "application/json",
...
The only difference that accept header in request changed to:
Accept */*
But now success callback is called.
Add the "beforeSend" function into your AJAX call to override the acceptable response mime type.
Refer to the jQuery.ajax() documentation:
http://api.jquery.com/jquery.ajax/
As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
And:
Data Types
Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.
I had the same problem when I made GET XMLHttpRequest call.
var req = new XMLHttpRequest();
req.open('GET', '/exampleServlet', false);
req.send(null);
It was fixed by setting ContentType on the HttpServletResponse.
response.setContentType("text/plain");
This error may be caused due to two reason. One is when getting no response from java backend and other is when their is no #ResponseBody in java Controller method.
I added ContentType to ResponseEntity and problem solved. Try to add a valid ContentType to your controller response:
ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).build();
I just ran into the same problem with a simple request:
$.ajax({
type: "POST",
url: something,
data: JSON.stringify(data),
contentType: "application/json"
});
In my case, this was a fire-and-forget scenario - I don't care about the response. To solve it, it was a case of changing the server-side code to correctly return a 204: No content status code, instead of returning 200: OK.

Paraimpu HTTP POST REQUEST

I am trying to make a http POST request from my Jquery mobile application(hosted on Amazon S3) to "http://paraimpu.crs4.it/data/new" to insert data into my sensor on the Paraimpu site. This is the request I'm making:
data = "Test";
valueToSend = '{"token":"c9d1cee6-da40-4e97-afc8-209045786b04","content-type":"application/json","data":' + data + '}';
$.ajax({
url: "http://paraimpu.crs4.it/data/new",
type: "POST",
data: valueToSend,
dataType: "json",
crossDomain: true,
contentType:"application/json",
success: function(){
alert('Success');
}
});
I keep getting
XMLHttpRequest cannot load http://paraimpu.crs4.it/data/new. Origin
"http://webappz.s3-website-us-east-1.amazonaws.com" is not allowed by
Access-Control-Allow-Origin.
I know this is because of the cross domain policy, but how can I get around this? The instructions on the paraimpu page are pretty vague and just says:
Push new sensor data doing an HTTP POST to:
http://paraimpu.crs4.it/data/new
with content like: {"token":"c9d1cee6-da40-4e97-afc8-209045786b04",
"content-type":"text/plain", "data":RAW DATA}
data = "Test";
valueToSend = '{"token":"c9d1cee6-da40-4e97-afc8-209045786b04","content-type":"application/json","data":' + data + '}';
$.ajax({
url: "http://paraimpu.crs4.it/data/new",
type: "POST",
data: valueToSend,
dataType: "jsonp", //set datatype to jsonp
crossDomain: true,
jsonp: false,
contentType:"application/json",
success: function(){
alert('Success');
}
});​
These are the parts that you were missing:
dataType: "jsonp": The type of data that you're expecting back from the server. "jsonp", loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
jsonp: false: Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }
More on this here: jQuery.ajax()

Categories

Resources