Here's my form code
html += `</div>
<div class="card-footer">
<form id="messageSendDashboardGroup" enctype="multipart/form-data">
<div class="image-upload">
<div class="input-group" >
<input type="hidden" name="id" value="${id}" />
<input type="hidden" name="name" value="${name}" />
<input type="hidden" name="prefix" value="${prefix}" />
<input type="text" name="message" class="form-control">
<span class="input-group-append">
<label for="file-input" style="margin-bottom: 0px;">
<span class="input-group-text" style="height: 100%;"><i class="fa
fa-upload"></i></span>
<span><input id="file-input" type="file" name="image"></span>
</label>
<button type="submit" class="btn btn-danger">Send</button>
</span>
</div>
</div>
</form>
</div>`;
$('.empChatMessagesShowHere').append(html);
It will generate the form
$('#messageSendDashboardGroup').on('submit', function (e)
{
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: base_url + 'dashboard/image_api',
data: formData,
type: 'post',
cache: false,
contentType: false,
processData: false,
success: function (data)
{
console.log(data);
}
});
In my controller when i debug $_FILES its returning emtpy array
function image_api()
{
debug($_FILES);
}
Array
(
[image] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
I have tried many things but still i am getting an empty $_FILES array kindly help me please, i am using this form to upload image.
I Just change my code to this and it works
html += `</div>
<div class="card-footer">
<form id="messageSendDashboardGroup" enctype="multipart/form-data">
<div class="image-upload">
<div class="input-group" >
<input type="hidden" name="id" value="${id}" />
<input type="hidden" name="name" value="${name}" />
<input type="hidden" name="prefix" value="${prefix}" />
<input type="text" name="message" class="form-control">
<button type="submit" class="btn btn-danger">Send</button>
<input type="file" name="image" class="mt-2" />
</div>
</div>
</form>
</div>`;
$('.empChatMessagesShowHere').append(html);
Before i am using input-prepend button for file upload now i am using default file upload button and it works.
Related
This question already has answers here:
Sending formdata for file upload using ajax
(3 answers)
Closed 9 months ago.
I have this HTML:
<form id="form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<div class="mb-3">
<label for="design_title" class="form-label">Ttile of the design</label>
<input type="text" name="design" class="form-control" id="design_title">
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="design" class="form-label">Upload a new design</label>
<input type="file" name="design" class="form-control" id="design">
</div>
</div>
</div>
<div class="mb-3">
<div class="row">
<div class="col">
<label for="fontsize" class="form-label">Enter the font size</label>
<input type="number" name="design_font_size" class="form-control" id="fontsize">
</div>
<div class="col">
<label for="position_x" class="form-label">Position X</label>
<input type="number" name="design_x" class="form-control" id="position_x">
</div>
<div class="col">
<label for="position_y" class="form-label">Position Y</label>
<input type="number" name="design_y" class="form-control" id="position_y">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="domain">Choose a domain</label>
<select name="domain" id="domain" class="form-control" data-form="design_output">
<option value="">--Choose--</option>
<?php
$get_domain = mysqli_query( $mysqli, "SELECT * FROM eg_domains");
if( mysqli_num_rows( $get_domain ) > 0 ) {
while( $get_result = mysqli_fetch_array( $get_domain, MYSQLI_ASSOC ) ) {
$domain_name = $get_result['domain_name'];
$company = $get_result['company_name'];
$domain_id = $get_result['domain_id'];
echo "<option value='$domain_id'>$domain_name ($company)</option>";
}
}
?>
</select>
</div>
<button type="button" class="btn btn-primary ajax-btn output-desing" data-form="output_design">Output Design</button>
<button type="submit" class="btn btn-success ajax-btn">Save Design</button>
<div class="mt-3">
<div class="result"></div>
</div>
</form>
Now, on Output Design button click I want to get all the data including image.
So, I am doing this in JQuery/Ajax:
$(document).on("click", ".output-desing", function (e) {
e.preventDefault();
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = $("#form").serialize() + "&form=" + form_name;
// var data = '1';
console.log(data);
$.ajax({
dataType: "html",
type: "GET",
url: 'helper/process.php',
data: data,
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$(".output-design").val("Please wait...");
},
success: function (data) {
$(".output-design").html(data);
}
});
});
But I can get only form data not image data.
How can I get all the data including image data on that button click?
Anyways, I fix it this way:
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = new FormData(document.getElementById("form"));
data.append('form', form_name);
I'm having a problem with my code.
When I submit the data, the form is not cleaned although the line to do this is present (as seen from the code below).
function easyHTTP() {
this.http = new XMLHttpRequest();
}
easyHTTP.prototype.put = function (url, data, callback) {
this.http.open('PUT', url, true);
this.http.setRequestHeader('Access-Control-Allow-Origin', '*');
this.http.setRequestHeader('access-control-allow-methods', 'PUT');
this.http.setRequestHeader('Content-type', 'application/json');
d1 = JSON.stringify(data);
console.log(d1)
this.http.send(d1);
}
function myFunction() {
const data = {
id: document.getElementById('id').value,
data: document.getElementById('date').value,
immagine: document.getElementById('image').value,
marca: document.getElementById('brand').value,
titolo: document.getElementById('title').value
};
const http = new easyHTTP;
// Put prototype method(url, data, response text)
http.put('https://2hgtrsoxk6.execute-api.us-east-2.amazonaws.com/articles',
data, function (err, post) {
if (err) {
console.log(err);
} else {
console.log(post);
}
});
document.getElementById("save").value = "";
}
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<div class="field">
<label for="id">ID :</label>
<input type="text" id="id" name="id" />
</div>
<div class="field">
<label for="data">Data:</label>
<input type="text" id="date" name="date" />
</div>
<div class="field">
<label for="immagine">Immagine:</label>
<input type="file" id="image" name="image" />
</div>
<div class="field">
<label for="marca">Marca:</label>
<input type="text" id="brand" name="brand" />
</div>
<div class="field">
<label for="titolo">Titolo:</label>
<input type="text" id="title" name="title" />
</div>
<div class="field">
<button type="submit" class="full">Save</button>
</div>
</form>
</div>
Can anyone explain to me why the form cleaning is not performed despite having put document.getElementById("save").value=""; in the function myFunction??
Replace
document.getElementById("save").value = ''
with
document.getElementById("save").reset();
.reset() is a method that allows you to trigger a "reset" event on a <form> programmatically. The standard "reset" event happens when the user clicks a reset button
<button type='reset'>CLEAR</button>
<!--- OR --->
<input type='reset' value='CLEAR'>
function easyHTTP() {
this.http = new XMLHttpRequest();
}
easyHTTP.prototype.put = function (url, data, callback) {
this.http.open('PUT', url, true);
this.http.setRequestHeader('Access-Control-Allow-Origin', '*');
this.http.setRequestHeader('access-control-allow-methods', 'PUT');
this.http.setRequestHeader('Content-type', 'application/json');
d1 = JSON.stringify(data);
console.log(d1)
this.http.send(d1);
}
function myFunction() {
const data = {
id: document.getElementById('id').value,
data: document.getElementById('date').value,
immagine: document.getElementById('image').value,
marca: document.getElementById('brand').value,
titolo: document.getElementById('title').value
};
const http = new easyHTTP;
// Put prototype method(url, data, response text)
http.put('https://2hgtrsoxk6.execute-api.us-east-2.amazonaws.com/articles',
data, function (err, post) {
if (err) {
console.log(err);
} else {
console.log(post);
}
});
document.getElementById("save").reset();
}
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<div class="field">
<label for="id">ID :</label>
<input type="text" id="id" name="id" />
</div>
<div class="field">
<label for="data">Data:</label>
<input type="text" id="date" name="date" />
</div>
<div class="field">
<label for="immagine">Immagine:</label>
<input type="file" id="image" name="image" />
</div>
<div class="field">
<label for="marca">Marca:</label>
<input type="text" id="brand" name="brand" />
</div>
<div class="field">
<label for="titolo">Titolo:</label>
<input type="text" id="title" name="title" />
</div>
<div class="field">
<button type="submit" class="full">Save</button>
</div>
</form>
</div>
The line document.getElementById("save").value = ""; isn't going to clean the form because forms don't have a value. The value is only in the inputs.
You would need something like this:
document.getElementById("save")
.querySelectorAll('input')
.forEach(function(input) {input.value = ""})
I am using Bootstrap/jquery for client side. On server side I am using node.js and express
The form is as follows:
<form id="signupform" action="">
<h2>Sign Up</h2>
<p>Please fill in this form to create an account!</p>
<hr>
<div class="form-group">
<input type="text" class="form-control" id="username" placeholder="Username" required="required">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" required="required">
</div>
<div class="form-group">
<input type="number" class="form-control" id="contact" placeholder="Contact" required="required">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password" required="required">
</div>
<div class="custom-file">
<label class="custom-file-label" for="cover">Profile Picture</label>
<input type="file" class="custom-file-input" id="cover">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg" id="sign-up">Sign Up</button>
</div>
</form>
My jquery is as follows:
$(document).ready(function(){
$("#sign-up").click(function(event){
event.preventDefault();
var formData = new FormData();
formData.append("username",$("#username").val())
formData.append("email",$("#email").val())
formData.append("contact",$("#contact").val())
formData.append("password",$("#password").val())
formData.append("cover",$("#cover")[0].files)
$.ajax({
url: "http://localhost:3000/users/",
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
});
On server side, when I view the incoming request I see this:
body: {
username: 'Sree',
email: 'example#gmail.com',
contact: '1',
password: '1',
cover: '[object FileList]'
},
On the server side I am using express-fileupload, but the image is being sent in the body instead of req.files. How to send formData's file to req.files instead of body?
You should be passing a File object to append(), to access the file object use the prop method to get access to the FileList and take the item at the first index
formData.append("cover", $("#cover").prop('files')[0])
I'm trying to upload 2 file which is in form with ajax but when i print_r($_POST) and print_r($_FILES) it showing me empty array.
here is my html code:
<form id="addFloorEntityTypeFrom" method="POST" action="api/apiRoute.php" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
</div>
</form>
here is my JavaScript code.
var formData = new FormData();
var formDataArray = $(form[0]).serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: baseUrl + 'newIFPAdmin/api/apiRoute.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
this is my server side code..
print_r(json_decode(file_get_contents('php://input'), true));
print_r($_POST);
print_r($_FILES);
exit;
response is:
Array
(
)
Array
(
)
Please try this code. It's working fine. Review screenshot.
https://ibb.co/wJWLfW5
<form id="addFloorEntityTypeFrom" method="POST" action="" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
<script>
function SaveEntity()
{
var formData = new FormData();
var formDataArray = $("form").serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: 'demo.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
}
</script>
I'm trying to post data from a form with an ajax post. Currently I am just debugging this by alerting the data sent, via a php script.
So my code html :
<form id="form_sewa">
<input type="hidden" name="penyewaan" id="penyewaan" value="">
<div class="form-group col-md-12">
<label for="nama_anak">Nama Anak:</label>
<input type="text" data-mini="true" name="nama_anak" id="nama_anak" value="">
</div>
<div class="form-group col-md-12">
<label for="jumlah_uang">Jumlah Uang:</label>
<input type="number" data-mini="true" name="jumlah_uang" pattern="[0-9]" id="jumlah_uang" value="">
</div>
<div class="form-group col-md-12">
<label for="harga_kamar"><b>Harga</b> Kamar:</label>
<input type="number" data-mini="true" name="harga_kamar" pattern="[0-9]" id="harga_kamar" value="">
</div>
<div class="form-group col-md-12">
<!-- Untuk tanggal -->
<label for="tanggal_masuk">Tanggal <b>Masuk:</b></label>
<input id="tanggal_masuk" name="tanggal_masuk" data-mini="true" />
</div>
<br>
<div class="form-group col-md-12">
<label for="tanggal_keluar">Tanggal <b>Keluar:</b></label>
<input id="tanggal_keluar" name="tanggal_keluar" data-mini="true" />
</div>
<br>
<div class="form-group col-md-12">
<label for="no_kamar"><b>Nomor</b> Kamar:</label>
<input type="number" data-mini="true" name="no_kamar" pattern="[0-9]" id="no_kamar" value="">
</div>
<input type="submit" data-role="button" data-theme="f" data-inline="true" data-icon="check" id="submitSwa" />
Kembali
</form>
In JavaScript
$(document).ready(function(){
$("#submitSwa").click(function(){
$.ajax({
url: "http://localhost/apri2/php/crudpenyewaan.php",
type: "post",
cache:false,
data: {
nama_anak: $('#nama_anak').val(),
jumlah_uang: $('#jumlah_uang').val(),
harga_kamar: $('#harga_kamar').val(),
tanggal_masuk: $('#tanggal_masuk').val(),
tanggal_keluar: $('#tanggal_keluar').val(),
no_kamar: $('#no_kamar').val()
},
success: function(response){
alert(response);
},
error: function(){
alert('Error while request..');
},
complete: function() {
$.mobile.loading("hide");
}
});
});
});
And in php
<?php
print_r($_POST);
?>
I have tried methods like submithandler, formdata serialize, but the alert doesn't show up and my url looks like this after clicking submit: