This problem confused me. Why my code cannot run on the server (in local runs well). What is wrong with the uploaded code?
I did the first ajax setup for all ( my script )
$.ajaxSetup({
headers: { 'X-CSRF-Token' : tokenCsrf,
// 'Content-Type':'application/x-www-form-urlencoded; multipart/form-data; charset=UTF-8',
},
error: function(jqXHR, exception) {
var response = JSON.parse(jqXHR.responseText);
var message = '';
if(response.body){
message = (response.body.msg ? response.body.msg : response.body);
}else{
$.each(response, function (key, value) {
message += value[0] + '<br/>';
});
}
// scripts
},
beforeSend:function(){
// scripts
},
complete:function(){
// scripts
},
done:function(){
// scripts
}
});
and script ajax for uploading (cut)
var fd = new FormData($(this)[0]);
$.ajax({
url: url,
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
// scripts
}
});
so why in my bankend i use
dd($request->all()) // emtpy
if in my local work perfectly
UPDATE:
in my backend
public function myController(Request $request){
dd($request->all()); // <<--- empty ( nothing parameter from front)
}
in my case, why when submit form empty parameter, If in server, but work in local.
Solved
I got wrong config in PHP.ini
Related
I want to send FirstName, LastName and Image through Ajax Call to PHP. I am able to send the data without image, and I am able to send the image without text using formdata but the problem is I am not able to do both at a time. Kindly check my code what I am doing wrong:
<script>
function createBasicInfo() {
// For Image Send
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
// For Text Send
var data = {
'firstname' : jQuery('#firstname').val(),
'lastname' : jQuery('#lastname').val(),
};
**//Here Is the Problem, I am not able to append the data with Text**
formdata.append(data);
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
In above code if I comment
//formdata.append(data); // Then only image will send to php
And If I use in Ajax Call
data: data, // Then only FirstName & LastName will send to php without Image
I am not able to send text data and image both at the same time to php file.
Any idea or suggestion would be welcome.
You could just do this insted of formdata.append(data):
formdata.firstname = jQuery('#firstname').val();
formdata.lastname = jQuery('#lastname').val();
Just append your firstname and lastname into formdata. Then send full formdata.
<script>
function createBasicInfo() {
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
formdata.append('firstname', jQuery('#firstname').val());
formdata.append('lastname', jQuery('#lastname').val());
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
// ...
// ...
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp
So I have a basic controller accepting a post..
[HttpPost]
public ActionResult Submit(string postCost)
{
//Do stuff here before sending back redirect details...
return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") });
}
And I'm posting via jquery ajax method:
$.ajax({
url: partyURL,
dataType: 'json',
contentType: 'application/json', //charset=utf-8',
type: 'POST',
data: { postCost: postageCost}, //**This fails!**
//data: "{'postCost':'3.50'}", //**This works**
success: function (response) {
if (response.result == 'SoldOut') {
$("#soldOut").show();
}
else if (response.result == 'Redirect') {
//All good, onward to confirmation page
window.location = response.url;
}
},
error: function (xhr, status, error) {
// Error handling here
}
});
where the postageCost variable sent in when it fails returning status 500:
postageCost = '3.50';
postageCost = JSON.stringify(postageCost); //also fails with this
but if I hard-code the data definition as
data: "{'postCost':'3.50'}",
It works fine.
The key must therefore lie in what I'm doing with the data element?
you need to do
var datum = {'postCost': '3.50'};
data: JSON.stringify(datum), //Ajax call data
I want to build an application form where on can attach an image - it's just a couple of input elements - within a div (not an form element). The form shall be processed without an page redirect. So I use ajax. Everything works fine so far. But now I need to add an image.
$('#submit_application').click(function () {
//...
$.ajax({
url: 'submit.php',
type: 'post',
data: {
'action': 'submit',
'image': $('#image_upload').val(),
// ..
'someStringifiedJSON': JSON.stringify(foo)
},
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
});
How can I get my file into php's $_FILES variable? Or how can I pass the file to php so that I can upload it?
you can send files using formData.
var file = $('#image_upload')[0].files[0];
var fData = new FormData();
fData.append('action', 'submit');
fData.append('image', file);
fData.append('someStringifiedJSON', JSON.stringify(foo));
and your ajax request will be:
$.ajax({
url: 'submit.php',
type: 'post',
data: fData ,
contentType: false,
processData: false,
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
Explanation:
as specefied here.if you set processData to true it will pass it as query string.if you want to send non-processed data set it to false.
default for contentType is application/x-www-form-urlencoded; charset=UTF-8.which won't work for files (because it sends heder like multipart/form-data; boundary=---------------------------125911542220235) when you set it to false browser generate right content-type header automatically
Try this:
$('#submit_application').click(function () {
var formData=new FormData();
formData.append('action','submit');
formData.append('someStringifiedJSON', ''+JSON.stringify(foo));
formData.append($('#image_upload').files[0]);
$.ajax({
url: 'submit.php',
type: 'post',
contentType:false,
data: formData,
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
});
Make sure to add this contentType:false in ajax request.
I'm getting reports that a website I developed is not functioning as it should in IE 9 and IE 10. The problem occurs when attempting to submit a form:
$("form[name='signIn']").submit(function(e) {
var formData = new FormData($(this)[0]);
e.preventDefault();
$( "#return_status_sign_in" ).empty();
$.ajax({
url: "<?= SITE_URL ?>account/login",
type: "POST",
data: formData,
async: false,
success: function (msg) {
$('#return_status_sign_in').append(msg);
},
cache: false,
contentType: false,
processData: false
});
});
The above submits the form via AJAX in all other browsers and works perfectly. However, in IE 9 and 10, the page refreshes and the POST data appears as get variables in the URL. How come is this happening? Could it be that e.preventDefault(); is not triggering? If so, what's the alternative to that?
As I stated in my comment, IE 9 uses the 'xdomainrequest' object to make cross domain requests and 'xmlhttprequest' for other requests. Below is a sample of code that I use to work around this issue. 'xdomainrequests' only send 'plain/text.' They cannot send JSON:
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(),
data = JSON.stringify(jsonData);
xdr.open('POST', 'http://www.yourendpoint.com');
xdr.onload = function() {
// When data is recieved
};
// All of this below have to be present
xdr.onprogress = function() {};
xdr.ontimeout = function() {};
xdr.onerror = function() {};
// Send the request. If you do a post, this is how you send data
xdr.send(data);
} else {
$.ajax({
url: 'http://www.yourendpoint.com',
type: 'POST',
dataType: 'json',
data: {
// your data to send
},
cache: true
})
.done(function(data) {
// When done
})
.fail(function(data) {
// When fail
});
}