i can't upload images using Ajax - javascript

I've been trying to add a new product using ajax and bootstrap (modal) and when I press the save changes button, I get Undefined index in all the fields.
Here's my ajax code:
$('#save').click(function(){
var nombre = $('#nombre').val();
var desc = $('#desc').val();
var precio = $('#precio').val();
var stock = $('#stock').val();
var tipo = $('#tipo').val();
var data = new FormData();
jQuery.each(jQuery('#imagen')[0].files, function(i, file) {
data.append('file-'+i, file);
});
var datas="nombre="+nombre+"&desc="+desc+"&precio="+precio+"&stock="+stock+"&tipo="+tipo;
$.ajax({
url: "php/newproduct.php",
data: {datas, data},
cache: false,
contentType: false,
processData: false,
type: "POST"
}).done(function( data ) {
$('#info').html(data);
viewdata();
setTimeout(function() {
$('#myModal').modal('hide');
}, 500);
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
});
});

data: {datas, data},
doesn't seem to be proper javascript syntax and I don't think you can mix different data object.
You can't mix FormData and an URL encoded string, which in your case isn't event properly encoded and you will have problems, if any of the values contains &.
The easiest way to upload using AJAX would be, if you initialized the FormData object with your form
var data = new FormData($("#form").get(0));
and then just used
data: data,
in your AJAX call
If you really need to add the fields manually, you need to add them to the FormData object
data.append("nombre", nombre);
data.append("desc ", desc);
data.append("precio ", precio);
data.append("stock ", stock);
data.append("tipo ", tipo);

Related

Create PDF with Ajax

I am using FPDF to create my report.
$pdf = new Report('P','mm','A4', $_POST);
$pdf->AddPage();
$pdf->Output('file.pdf','I');
And I use ajax to make requisition to the PHP.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
window.open(data);
})
I want to show the report in a new tab
I think you should success key. So it would be something like this
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id },
success: function(data){
var blob = new Blob([data]);
window.open(URL.createObjectURL(blob));
}
})
Resolved:
I did the different way:
In my report PHP, I generate one temporay file, passing the parameter 'F'.
$pdf->Output('file.pdf','F');
In Jquery Ajax I opne the file, rather than open the data retorned of ajax request.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
var fileName = "file.pdf";
$('#modalRel').modal('show');
var object = "<object data=\"{FileName}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
object += "If you are unable to view file, you can download from here";
object += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
object += "</object>";
object = object.replace(/{FileName}/g, "../Files/" + fileName);
$("#body-rel").html(object);
})
I hope to have helped who one day to need.

Retrieve file uploaded in Laravel using JavaScript FormData

Running into a bit of trouble trying to upload multiple files through a single AJAX request into a Laravel 5 back-end.
In the front-end, I am using the following code to prep the FormData object:
var fd = new FormData();
fd.append("data", JSON.stringify(values));
fd.append("page_id", page_id);
files.forEach(function(file, index){
fd.append("file_"+index, file);
});
Then this is my AJAX call:
$.ajax({
type: 'POST',
url: '/file_test',
data: fd,
contentType: false,
processData: false,
success: function(response){
alert(response);
},
failure: function(response){
alert(response);
}
});
In the back-end, I've tried to retrieve with $request->allFiles() and $request->file('file_0') as well as $_FILES but they are all turning up empty.
After #Pavel mentioned that the $_FILES array was empty, I went and checked what was being sent up in the XHRRequest. What I realized was that I was not appending the file itself to the FormData object and instead was appending the whole input containing the file.
var files = [];
if(this.type == "file"){
if(this.files.length == 1){
values[$(this).attr('name')] = this.files[0].name;
//files.push(this); // ORIGINAL CODE
files.push(this.files[0]); // WORKING CODE!
}
}

How to get FormData object and submit the form data by ajax use asp.net mvc

I would like to get a form object and submit the data to server with a button click in Asp.net MVC.
This is my HTML code:
<form method="post" form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
This is my JS code:
$(document).on("click", "[form-sync='ajax']", function() {
var formdata = new FormData($(this).closest("form")),
url = $(this).data("url");
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(response) {
alert(response.message);
return false;
},
});
});
This is my MVC code:
var data = Request["InvtId"];
The problem is the data variable is empty
Any help would be greatly appreciated, thanks.
Your form-sync attribute is non standard so your HTML is invalid. You should make that a data attribute.
You need to hook to the submit event of the form, not click.
The FormData constructor expects a DOMElement, not a jQuery object as you are currently passing to it. You can just give the this reference as that is the DOMElement.
The form has no data-url attribute. I assume you want the action property instead, which will default to the current page as you haven't provided one explicitly.
The return statement in your success handler is redundant.
You need to stop the standard form submission (as you're submitting via AJAX instead) by calling preventDefault() on the passed submit event.
Here's a complete example with all the above fixes:
<form method="post" data-form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
$(document).on('submit', '[data-form-sync="ajax"]', function(e) {
e.preventDefault();
$.ajax({
url: this.action,
type: 'post',
data: new FormData(this),
processData: false,
contentType: false,
success: function (result) {
alert(result.message);
},
});
})
The problem is that you are passing in a jQuery element and NOT a DOM element.
For the FormData to actually return what you expect, you need to pass in a DOM element to its constructor.
Here, try this instead:
var formdata = new FormData($(this).closest("form")[0]);
Another problem is that the form has no data-url attribute.
Use the action property instead, it will return the url of the current page if you have not given a url yourself.
Here, use this instead:
var url = this.action; // or $(this).prop('action');
HTML
< button type="button" class="btn btn-primary"
onclick="saveData()">Save</button>
JS Code
Inside of function saveData()
var formData = new FormData();
get values with serializeArray
var formulario = $("#miFormulario").serializeArray();
if there are extra data or files
formulario.push({ "name": fileName, "value": file });
add information to formData
formulario.forEach((d) => {
formData.append(d.name, d.value); });
ajax request
$.ajax({
timeout: 0,
url: "/InfoController/savingInfo",
method: "post",
data: formData,
contentType: false,
processData: false,
success: function (result) { //do something }
});
Controller
[HttpPost] public JsonResult savingInfo() {
if (Request.Files.Count > 0)
{ ... }
var data = Request.Form;
var valor1 = data["dato1"];
return Json(true);
}

What is wrong with this piece of code

This piece of code of a form submission is working perfectly in Google chrome meanwhile in Firefox it does not. Can somebody tell me what is wrong with my code?
$(document).ready(function(e){
/*sending post data to php script */
$("form[id='postForm']").submit(function(e){
e.preventDefault();
var text = $('#postText').val();
var formData = new FormData($(this)[0]);
formData.append('postText', text );
$.ajax({
url: "home.php?module=facebook&action=post-news&method=script",
type: "POST",
data: formData,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
window.location.reload();
}
});
e.preventDefault();
});
$('input:file').on('change', function () {
var formData = new FormData($(this)[0]);
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
formData.append('imageToPost[' + i + ']', file);
});
});
});
Quickly checked console:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
The problem is here:
$('input:file').on('change', function () {
var formData = new FormData($(this)[0]); <--- HERE
this is not a form, but input element. Not sure what you wanted to achieve here, but probably serialize your form. For this you need to do:
var form = $("#postForm")[0];
var formData = new FormData(form);
And then append your file.
Hope this helps.

how to get data in the success of ajax

I have the following ajax function:
reader.onload = function(event){
var fd = new FormData();
var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
console.log("name = " + Name);
fd.append('fname', Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
success: function(data){
//console.log(data);
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName},
success: function(data){
console.log(data);
}
});
}
});
};
first question: I want to retrieve the data from the second success function to use it later in the code.how could that happen?
second question: the data is an audio file.Is there is a special way to get audio data, or we can get it the same way as any data?In my php server side of the second ajax, I'm reading an audio file and want to use its data.I did simple file open and get contents.does that work for audio files?
server-side code:
<?php
$fileName=$_POST["fileName"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;
This is a bad practice in general, but what you could do is specify a global variable at the start, and then assign data to that variable inside the success. The issue with this is that you can't be certain that the ajax has completed and your variable has been set, before you need to use it.
var mySuccessVar = null;
...
success: function(data) {
mySuccessVar = data;
}
... // later in the code:
if (mySuccessVar != null) {
yourFunction(mySuccessVar);
}

Categories

Resources