How to send an image with js from an input element? - javascript

How can I send an image from an input element with Javascript?
This is my image element:
<input type="file" name="imagefile" onChange="fileThumbnailHeader(this.files);" accept="image/*" id="header-img-upload" class="header-img-upload" />
And here is my function where I post other text fields with:
function registerDetails(){
var register_location = document.getElementById('register_location').value;
var register_country = document.getElementById('register_country').value;
var register_language = document.getElementById('register_language').value;
var register_interests = document.getElementById('register_interests').value;
var register_homepage = document.getElementById('register_homepage').value;
var register_music = document.getElementById('register_music').value;
var register_films = document.getElementById('register_films').value;
var register_books = document.getElementById('register_books').value;
var register_relationship = document.getElementById('register_relationship').value;
var register_age = document.getElementById('register_age').value;
var register_school = document.getElementById('register_school').value;
var register_phone = document.getElementById('register_phone').value;
var register_job = document.getElementById('register_job').value;
$.post( versionMode + "register_step_one_update.php",{city : register_location, country : register_country, language : register_language, tags : register_interests, website : register_homepage, music : register_music, movies : register_films, books : register_books, relation : register_relationship, age : register_age, school : register_school, phone : register_phone, job : register_job}, function( data ) {
alert(data);
});
}
How can I send the image with it?

<script>
$("form[name='uploader']").submit(function(e) {
// var file = $("#userfile")[0].files[0]; //try this too
// var fileName = file.name;
$.ajax({
url :"url_for_the_php_page",
type:"POST",
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success:function(msg){
// alert(msg);
}
});
return false;
});
</script>
<html>
<form id="uploader" name="uploader" accept-charset="utf-8" enctype="multipart/form-data"><!-- no action include in the form open -->
<input type="file" name="userfile" id="userfile" class="file" value="" > <!-- this is the file upload field -->
<input type="text" name="register_location" id="register_location" class="" value="" >
<input id= "submit_button" name = "submit_button" type="submit" value="Upload">
</form>
<html>
<?php
// in your php page you can access those fields as follows
$userfile = $_POST['userfile'];
$register_location = $_POST['register_location'];
?>

Related

How to send form-data as a JSON Object..?

I have some text input and images on my server-side. and
I need to send this data as a JSON object. But I can not send images like this because of FormData.So I need to convert my form data to one single JSON object.
Please Help me...
Thank You..!
HTML part -
<form>
<div class="form-group">
<label for="txtcustomerImage"> <i class="tags icon"></i> Image Of Your NIC</label>
<input class="form-control-file" id="txtcustomerImage" type="file" name="txtcustomerImage">
</div>
</form>
Ajax Part -
$('#btnCreateNewAccount').click(function () {
var fileObject = $("#txtcustomerImage")[0].files[0];//access file object from input field
var fileName = $("#txtcustomerImage")[0].files[0].name; //get file name
var form = new FormData(); //setup form data object to send file data
form.append("custImage", fileObject, fileName); //append data
console.log('clicked..');
let customerNIC = $('txtcustomerNIC').val();
let customerName = $('txtcustomerName').val();
let customerAddress = $('txtcustomerAddress').val();
console.log(form)
$.ajax({
method: "post",
url: "http://localhost:8080/Sprinf_Final-Back-end/customer",
contentType: "application/json",
data: JSON.stringify({
customerNIC: customerNIC,
customerName: customerName,
customerAddress: customerAddress,
}),
success: function (res) {
if (res.massage == 'Success') {
alert('Your Account is Successfully Created!When You Log to Server Use Your User Name & Password..!');
console.log(res);
} else {
console.log('error');
}
}
});
});
It doesn't make sense to create a FormData object if you want to send the data as JSON. You can read the file content with fileObject.text() and send it:
$('#btnCreateNewAccount').click(async function() {
const fileObject = $("#txtcustomerImage")[0].files[0]; //access file object from input field
const fileName = fileObject.name; //get file name
const data = JSON.stringify({
fileObject: await fileObject.text(),
fileName
})
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="txtcustomerImage"> <i class="tags icon"></i> Image Of Your NIC</label>
<input class="form-control-file" id="txtcustomerImage" type="file" name="txtcustomerImage">
</div>
</form>
<button id="btnCreateNewAccount">
Click
</button>

Send file from AJAX and retreive from PHP

I have a form in which I retrieved the fields with ajax and send those as post to a PHP file. But one of the fields is a input type="file".
My question is as follow: how to properly send this file (an image) via ajax to the PHP file and read the file so I can upload it to a server.
Here's my code:
The form and fields
<form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
<div class="response" id="response"></div>
<div class="custom-file">
<input type="hidden"
name="<?php echo ini_get("session.upload_progress.name"); ?>"
value="video_upload">
<input type="file" name="lien_video" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choisir le logo</label>
</div>
<div class='progress' id="progress_div">
<div class='bar' id='bar1'></div>
<div class='percent' id='percent1'>0%</div>
</div>
...and some other stuffs
The script so far it's inside the same PHP file as the form
<script type="text/javascript">
$(document).ready(function () {
//upload data
$(document).on('click', '#enreg_ecole', function () {
let nom_ecole = $('#input-1').val();
let adresse = $('#input-2').val();
let nom_rep = $('#input-3').val();
let email_rep = $('#input-4').val();
let tel_rep = $('#input-5').val();
let poste = $('#input-6').val();
// let logo = $('#customFile').val();
let logo = document.getElementById("customFile").files[0];
var form = new FormData();
form.append('enreg_ecole', 1);
form.append('nom_ecole', nom_ecole);
form.append('adresse', adresse);
form.append('nom_rep', nom_rep);
form.append('email_rep', email_rep);
form.append('tel_rep', tel_rep);
form.append('poste', poste);
if(logo != null){
form.append('logo', logo);
}
$('#scroller').animate({scrollTop: 0}, 'fast');
var bar = $('#bar');
var percent = $('#percent');
$.ajax({
url: 'methods/enregistrer_ecole.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data:form,
enctype: 'multipart/form-data',
dataType: 'json',
beforeSubmit: function () {
document.getElementById("progress_div").style.display = "block";
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function (response) {
let status = response['status'];
let message = response['message'];
if (status === 'error') {
// window.alert(message);
document.getElementById("progress_div").style.display = "none";
document.getElementById("alert_div").style.display = "inline";
$('#alert_div').addClass('alert-danger');
$('#alert_title').html(status);
$('#alert_message').html(message +' ' +logo);
} else {
// window.alert(message);
document.getElementById("alert_div").style.display = "inline";
// $('#bar1').animate({width: "100%"}, 100);
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
$('#alert_div').addClass('alert-success');
$('#alert_title').html(status);
$('#alert_message').html(message);
}
},
// complete: function (xhr) {
//
// },
error: function (error, ajaxOptions, thrownError) {
// let error = JSON.parse(response);
// window.alert('Error happenned: ' + error);
// window.alert('Error happenned: ' + response.msg);
// var msg = $.parseJSON(error).msg;
window.alert(error);
window.alert(ajaxOptions);
window.alert(thrownError);
}
});
//window.alert('clicked');
});
});
</script>
I want to be able to do something like:
$target_file = $target_dir . basename($_FILES["lien_video"]["name"]);
----EDIT----
Okay, I tried some more codes and it looks like on my PHP file (enregistrer_ecole.php called from ajax), if I try to retrieve only the texts from the form, it's okay. If I try to retrieve only the file, it's okay. But trying to retrieve both the texts and the picture file (like $_POST['someText'] and $_POST['someFile']['tmp_name'] it throws an error.
Does anyone know a way to do this properly? Like get the texts first and then get the file. I don't know.
HTML
<div class="container">
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'>
<img src="" id="img" width="100" height="100">
</div>
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
</div>
PHP
<?php
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
/* Valid Extensions */
$valid_extensions = array("jpg","jpeg","png");
/* Check file extension */
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
$uploadOk = 0;
}
if($uploadOk == 0){
echo 0;
}else{
/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
}else{
echo 0;
}
}
One of the form attribute is missing in your HTML and that is enctype
<form class="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data">
</form>
and there can be one improvement: instead of writing each input field appended to form data object, you can write single line.
you can replace all these lines
var form = new FormData();
form.append('enreg_ecole', 1);
form.append('nom_ecole', nom_ecole);
form.append('adresse', adresse);
into a single line as below:
var form = new FormData($("form")[0]);

Why jQuery.ajax() is not sending any data?

Tell me please, there is a form for sending data to the database. Without a script it works fine, but nothing happens with the script. In the console — Form Data has all the data, and the 200th code arrives, but is not added to the database.
PHP:
<?php
$data = $_POST;
if (isset($data['add'])) {
$posts = R::dispense('posts');
$posts->head = $data['head'];
$posts->desc = $data['desc'];
R::store($posts);
}
?>
HTML:
<form method="POST" id="FormID">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
JS:
<script>
$("#FormID").submit(function(e)
{
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: $("#FormID").serialize(),
success: function(data)
{
c = "hello";
$('#FormStatus').text(c);
}
});
});
</script>
You said:
if (isset($data['add'])) {
So the code only does anything if add in the data.
<button type="submit" name="add">Добавить</button>
add is a submit button. It will be included in the data when you submit the form.
data: $("#FormID").serialize(),
You aren't submitting the form. jQuery serialize does not include submit buttons because they aren't successful controls when you aren't submitting the form.
Use some other mechanism to determine if there is data to process (such as the presence of head and desc.
You have forget the action for your form
Why don't simply use $data['name'] instead of R::dispense?
If you what to do a POST request why don't you use $.post()?
What you need is these:
PHP Code:
<?php
$data = $_POST;
if (isset($data['add'])) {
if(isset($data['head']) AND !empty($data['head']) AND isset($data['desc']) AND !empty($data['desc'])) {
$head = htmlspecialchars($data['head']);
$desc = htmlspecialchars($data['desc']);
echo "Hello from server";
}
else {
echo "Please fill the form";
}
}
?>
HTML:
<form method="POST" id="FormID" action="path_to_php_file.php">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
</form>
JS:
<script>
$("#FormID").submit(function(e)
{
e.preventDefault();
var form = $(this),
url = form.attr('action');
var data = {};
// To have post paramaters like
// { 'head' : 'Head value', 'desc' : 'Desc value' }
$.each(form.serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$.post(url, data, function(Responses) {
// Will write "Hello from server" in your console
console.log(Responses);
});
});
</script>

Ajax form set textbox value onsubmit

after submit the form using ajax i cant set the value on the multiple textbox correctly, here's my form
<form id="searchForm" action="process.php" method="post">
<input id="cust_code" name="cust_code" required>
<input id="cust_code1" name="cust_code1" disabled>
<input id="cust_name" name="cust_name" disabled>
<button type="submit">Search</button>
</form>
process.php
$cust_code = $_POST['cust_code'];
$result = mysql_query("SELECT code,cust_name FROM information WHERE code=$cust_code") or die(mysql_error());
$data = mysql_fetch_array($result);
javascript:
var formData = {
'cust_code': $('#cust_code').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true,
success: function(data) // recieved data from process.php
{
var code = data[0];
var cust_name = data[1];
// Update id value
document.getElementById('cust_code').value = code;
document.getElementById('cust_code1').value = code;
document.getElementById('cust_name').value = cust_name;
}
})
the value of cust_code and cust_code1 changed after submit, but not for cust_name
any ideas?
EDIT: the id's has been use on another page(php include) so that make the input wont change, solved!
You can assign value by this way also in JQuery:
document.getElementById('cust_code').val(code);
or
document.getElementById('cust_code').attr('value',code);
The same IDs have been used on another page(php include) so the input value won't change, changing the ID to cust_names seems to do the trick

flask ajax/jquery form submission

So I have this code below.
This is my jquery/ajax script
$(function() {
$(".reply").click(function(){
var id = $(this).attr("id");
var element = ".comment_replies#" + id;
$(element).show();
$(".submit_reply#" + id).click( function(event) {
event.preventDefault();
var reply_box = ".reply_box#" + id
var data = $(reply_box).val
$.ajax({
type : "POST",
url : "{{url_for('main.HomePage')}}",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
console.log(data)}
})
})
})
})
here is the form:
<form class = "reply_form" action="#" method="post">
<input class = "reply_box" type="text" placeholder ="write a reply" name="reply" id = "{{'id_' +com.id|string}}">
<input type="submit" class = "submit_reply" value = "reply" id = "{{'id_' +com.id|string}}">
<input type="hidden" value="{{com.id}}" name = "form_id">
</form>
and if I do:
if request.json["data"] in my HomePage view it somehow doesn't pass
because usually i'd just go if request.form when submitting the form the usual way. here is my homepage view
if request.json["data"] and request.method == "POST":
return request.json["data"]
it's only a test to see if it return what I want it too and it fails.
am I suppose to have extra imports for json? because I don't have any.
I also see this error on firebug:
POST http://127.0.0.1:5000/homepage
400 BAD REQUEST
11ms
I could submit the form the usual way but I wanna try submitting the form and appending the info without a page refresh.

Categories