$_POSt returns unexpected array - ajax

print_r($_POST) returns
Array ( [-----------------------------80612539230530
Content-Disposition:_form-data;_name] => "attach_doc" undefined
-----------------------------80612539230530 Content-Disposition: form-data; name="_token" M2gNgjdyAItV3aYLXRgz7DkR5uPDN16esKfeFtKL
-----------------------------80612539230530 Content-Disposition: form-data; name="_token" M2gNgjdyAItV3aYLXRgz7DkR5uPDN16esKfeFtKL
-----------------------------80612539230530 Content-Disposition: form-data; name="cl_shipment_id" 30
-----------------------------80612539230530 )
and not the formatted array.
Having the ajax post call as
var form_data= new FormData();
form_data.append('attach_doc',file);
form_data.append('_token', $("input[name=_token]").val());
var other_data = $("#store_shipment_frm").serializeArray();
$.each(other_data,function(key,input){
form_data.append(input.name,input.value);
});
$.ajax({ cache: false, dataType: 'text', contentType: false,
processData: false, url: common_ajax_url+"-----",
type: "post", data:form_data,
I am using this in Laravel, What wrong:(

$_POST is a PHP super global, "An associative array of variables passed to the current script via the HTTP POST".
You need to use the HTTP Request that comes with Laravel.
More info at https://laravel.com/docs/5.3/requests

If you look in the HTML-Source with the output of that array, you'll see that the array is very well formatted. If you want to see it like that on the HTML-page, you've to wrap it in pre-tags or other tags where you had to apply formatting corresponding to pre-tags.

Related

Laravel - AJAX file upload returning null

This is my ajax request:
var files = $('#imgur_attach')[0].files;
if(files.length > 0){
var fd = new FormData();
// Append data
fd.append('file',files[0]);
fd.append('_token',$globalToken);
$.ajax({
type: "POST",
dataType: "json",
contentType: false,
processData: false,
url: host + "/attach-comment-image/" ,
data: {fd},
Controller:
public function attach(Request $request) {
$this->validate($request, [
'file' => 'image|required',
]);
When sending this ajax request, the validator tells me that the "file" field is required. Trying to return request->get('file') returns null.
However, when I do console.log(fd); before the ajax request, it returns the following:
Why is this happening? I don't normally upload files with AJAX over a regular POST request, so I don't understand what I'm missing.
Try stringify data before sending like this:
$.ajax({
...
data: {fd: JSON.stringify(fd),
...
you need to add multipart form data
contentType: "multipart/form-data",
Wrapping the input around with a form tag like this did the trick:
<form method="POST" enctype="multipart/form-data">
Not sure why setting contentType: "multipart/form-data" in the ajax request doesn't work, but this solution works so I'll just use this instead.

Django-ajax: CSRF verification failed. Request aborted

I am working with django server side form to save details in DB.
<form id="form_save_file" enctype="multipart/form-data">
{% csrf_token %}
<label class="control-label col-md-4">File:</label>
<div class="col-md-8">
{{form.fa_file}}
</div>
<label class="control-label col-md-4">Name:</label>
<div class="col-md-8">
{{form.name}}
</div>
</form>
I am using ajax to post request.
$("#form_save_file").submit(function(e) {
$.ajax({
type: "POST",
url: '/url/',
data: $("#form_save_file").serialize(),
contentType: false,
processData: false,
success: function(data){}
});
I have included middleware classes in settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'request.middleware.RequestMiddleware'
)
When I removed contentType and processData in ajax request, request.FILES is empty in views.py and otherthings are working fine.
contentType option to false is used for multipart/form-data forms that
pass files.
When one sets the contentType option to false, it forces jQuery not to
add a Content-Type header, otherwise, the boundary string will be
missing from it. Also, when submitting files via multi-part/form one
must leave the processData flag set to false, otherwise, jQuery will
try to convert your FormData into a string, which will fail.
To try and fix your issue:
You are using jQuery's .serialize() method which creates a text string
in standard URL-encoded notation.
You need to pass un-encoded data when using "contentType: false".
Try using "new FormData" instead of .serialize():
Source: https://stackoverflow.com/a/20863123/3345051
Revised Code:
$("#form_save_file").submit(function(e) {
e.preventDefault();
var $this = $(this);
var postURL = '/url/';
var formData = new FormData(this);
$.ajax({
type: "POST",
url: postURL,
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false
})
.done(function(response) {
// Do something if POST is successful
})
.fail(function() {
// Do something if POST is unsuccessful
})
})
disabled csrf on particular view with #csrf_exempt decorator and build custom security with a random number/string

IE9 decline response of http server

IE9 decline response of below ajax request to local http server.
$.ajax({
type: 'GET',
url: "127.0.0.1",
data:{res:"pending"},
dataType: "text",
crossDomain: false,
cache: false,
success: success,
error: error
});
respone of server :
"HTTP/1.0 200 OK\r\n"
"Access-control-allow-methods: *\r\n"
"Access-control-allow-origin: *\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 0\r\n\r\n"
Is there any reason???? what IE9 expects??
I would recommend to take a look at the jQuery contentType parameter and dataType as well. Note that possible values are xml, json, jsonp, text, script, html. The default is Intelligent Guess by jQuery.
As stated in documentation:
dataType: The type of data that you're expecting back from the server.
contentType: When sending data to the server, use this content-type.
You should specify that you are sending HTML type data (by using html as dataType, because your server returns HTML in the response header (Content-Type: text/html), also if you have script tags in returned result - those will be evaluated when inserted in the DOM.

Why is ajax parsing json to the form "a=b&c=d"?

$.ajax({
url: '/metadata/hg_billing_cycle',
data: {"a":"b", "c":"d"},
datatype: "json",
contentType: "application/json",
type: 'POST',
error: handleError,
});
I'm using ruby on the server:
post "/" do
puts "ummm: #{request.body.read}"
end
I get the following output:
ummm: a=b&c=d instead of ummm : {"a":"b", "c":"d"}. Why is it doing this?
You are passing an object as the data parameter, from the $.ajax docs
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So your object is converted to a query string.
If you want to send json, then you'll have to well send json.
Convert your object to json (with JSON.stringify) and pass that as the data parameter.
$.ajax({
url: '/metadata/hg_billing_cycle',
data: JSON.stringify({"a":"b", "c":"d"}),
datatype: "json",
contentType: "application/json",
type: 'POST',
error: handleError,
});

How to POST a JSON request containing an array of objects?

On the server side, I have a method which looks like this:
#POST
#Path("/foods/{year}/{month}/{day}")
#Consumes("multipart/mixed")
#Produces("application/json; charset=UTF-8")
#Transactional
public boolean setFoodsForTheDay(#PathParam("year") int year, #PathParam("month") int month,
#PathParam("day") int day, #Multipart(value = "foodList", type = MediaType.APPLICATION_JSON) Food[] foodList) {
if (log.isDebugEnabled()) {
log.debug("list size={}", foodList.size());
}
doStuff(foodList);
}
If I send in the following POST request to /foods/2013/06/26 it will actually work and the array will get parsed correctly:
Host: localhost:7777
Accept: application/json
Content-Type: multipart/mixed; boundary=---------------------------25819220131967
Content-Length: 226
-----------------------------25819220131967\r\n
Content-Disposition: form-data; name="foodList"\r\n
Content-Type: application/json\r\n
\r\n
[ {"id":null,"name":"Banana","recipe":null} ]\r\n
-----------------------------25819220131967--\r\n
As you can see, it's important to send in a multipart/mixed (or perhaps multipart/form-data would work too) because then I can set the Content-Type of the part, and it will get parsed correctly.
This all works. Now the problem is, I need to send this request in with jQuery (or any other Ajax tool) and looks like it's not possible to send multipart/mixed? Or there's some trick with an iframe but it will still not be possible to set the Content-type of the part.
Does anyone know of a solution for this problem? How can I send in an array of objects to the server in JSON serialization?
Looks like this is not possibly with jQuery, however I did find a blog which shows how to do this with the old XMLHttpRequest.
This is my Javascript code now, it works perfectly! :)
function sendFoodRequest() {
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://localhost:7777/services/rest/foods/2013/06/25', true);
var boundary = '---------------------------';
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
xhr.setRequestHeader("Content-Type", 'multipart/mixed; boundary=' + boundary);
var body = '';
body += '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="foodList"' + '\r\n';
body += "Content-Type: application/json\r\n\r\n";
body += '[ {"id":null,"name":"Spinach","recipe":null} ]';
body += '\r\n'
body += '--' + boundary + '--';
xhr.setRequestHeader('Content-length', body.length);
xhr.onload = function() { }
xhr.send(body);
}
Yes you can send multipart/mixed through JQuery ajax, but must add extra stuff:
cache: false,
contentType: false,
processData: false,
$.ajax({
url: 'php/test.php',
data: {name: "test1", age 5},
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});

Resources