What is wrong with this piece of code - javascript

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.

Related

How can I combine two ajax functions in one function?

I have ajax code which can post name and I have another ajax which can post image I need to combine those two functions in order to have one function which can post both name and image
Below codes used to post image
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Please select a file.");
}
});
});
</script>
And below codes used to post name
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
$.ajax({
type:"post",
url:"upload.php",
data:
{
'name' :name
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
How can I combine above codes in order to use only one url "upload.php", this means upload.php will insert name in database and save image in folder while click save button, that's why I need to combine the codes
Please anyone can help me
You literally combine them.
You can use your first function and do the following:
var fd = new FormData();
var files = $('#file')[0].files;
fd.append('name', $("#name").val();
that is it. And on the other side (backend) you just ask for this name:
$name = $_POST['name'];

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

jQuery upload file not work with ajax

I try to upload file with below simple code , but i get error:
$("#register_to_buy_card").submit(function (event) {
event.preventDefault();
var $this = $(this);
var url = $this.attr('action');
var form = document.forms.namedItem($this);
var formdata = new FormData(form);
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: formData,
success: function (data) {
},
error: function (data) {
}
});
});
I get this error:
TypeError: Argument 1 of FormData.constructor is not an object.
var formdata = new FormData(form);
HTML:
<form id="register_to_buy_card" enctype="multipart/form-data" accept-charset="UTF-8" action="http://localhost/sample/registerToBuyCard" method="POST">
<label for="passport">Passport Image</label>
<input type="file" name="passport">
<div class="checkbox">
<button class="btn btn-default" type="submit">Submit</button>
</form>
The error you are getting is because:
var form = document.forms.namedItem($this);
namedItem expects a string. You are passing it var $this = $(this);, which is a jQuery object.
this is already a form object. So change:
var $this = $(this);
var url = $this.attr('action');
var form = document.forms.namedItem($this);
var formdata = new FormData(form);
to
var formdata = new FormData(this);
(Yes, those four lines should be replaced with a single line).
Then see this other question which covers the issues not directly related to your error message.
The issue is the element passed in the FormData is not the form but a jQuery object. You need to put the form which is this in the context.
You need to update this:
var formdata = new FormData(this);
and use :
contentType:false,
processData:false,
in the ajax options.
Updated code should be:
$("#register_to_buy_card").submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var formdata = new FormData(this); // <--------update with 'this'
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: formData,
contentType:false, //<-----------required
processData:false, //<-----------required
success: function (data) {
},
error: function (data) {
}
});
});

i can't upload images using Ajax

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

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