Issue uploading file via PHP and Jquery - php

I'm trying to follow this answer to upload a file via Ajax and PHP using Jquery, but it isn't working.
This is (part of) my HTML form (I'm using bootstrap):
<form role="form" enctype="multipart/form-data" id="edit-company" method="POST">
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12 form-group">
<label for="field-name-company">Name:</label> <input id="field-name-company" name="nameCompany" class="form-control" type="text"/>
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<label for="field-street-social-emp">Street</label> <input id="field-street-social-emp" name="streetCompany" class="form-control" type="text"/>
</div>
</div>
<div class="col-md-12 form-group">
<div class="row">
<label for="foto-empresa">Foto/Logo:</label>
<div class="form-group">
<input type="file" name="fotoEmpresa"/>
</div>
<button class="btn btn-success pull-right" type="submit" value="Confirm" id="submit-edit-company"><span class="glyphicon glyphicon-ok"></span> Update</button>
</div>
</div>
</div>
</div>
</div>
</form>
This is my jquery snippet:
$('#submit-edit-company').click(function(e) {
e.preventDefault();
var formToSubmit = $(this).parents('form#edit-company');
var dataToSend = formToSubmit.serialize();
var fileInput = formToSubmit.find('input[type="file"]')[0];
var fileData = fileInput.attr('files')[0];
console.log(fileData);
$.ajax({
url: 'app/editCompanyService',
data: dataToSend,
type: 'POST',
dataType: 'JSON',
contentType: false,
cache: false,
processData:false,
beforeSend: function () {},
success: function (return) {},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error... " + textStatus + " " + errorThrown);
}
When I'm debugging the javascript and monitoring fileInput, I can see the file like Files: FilesList[1] 0: File..., but the script just stops and don't show anything in the console, even errors.
The $_FILES var in PHP is just empty. (All configurations pointed in this post already checked).
Also tried fileInput.prop('files')[0]; and new FormData(formToSubmit), but I'm having the same problem.
What I'm doing wrong?

Although is not the same problem, the answer for this SO POST (linked in the question comments by #u_mulder) solves my problem.
Here is the functional code:
$('#submit-edit-company').click(function(e) {
e.preventDefault();
var formToSubmit = $(this).parents('form#edit-company');
var dataToSend = new FormData(formToSubmit[0]);
var fileInput = formToSubmit.find('input[type="file"]')[0];
var fileData = fileInput.attr('files')[0];
console.log(fileData);
$.ajax({
url: 'app/editCompanyService',
data: dataToSend,
type: 'POST',
dataType: 'JSON',
contentType: false,
cache: false,
processData:false,
beforeSend: function () {},
success: function (return) {},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error... " + textStatus + " " + errorThrown);
}

Related

Send Image file with Google reCaptcha v2 token to PHP via jQuery + Ajax

I want to POST and upload image via AJAX with Google reCaptcha v2 validation. but I am facing an issue that I am not not able to send image with caption text with google recaptcha token in Ajax. I coded two function as I know but both was not working. The function I made is the code snippet.
Please help me how I send Image with text in Ajax with reCaptcha token in PHP / jQuery/ AJAX.
$(document).ready(function() {
$("form#addbanner").unbind("submit").bind("submit", function(e) {
//debugger;
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('MY_RECAPTCHA_CODE', {
action: 'add_web_banner'
}).then(function(token) {
/*let formData = {
imagehere : $('input[name="imagehere"]').val(),
bannertitle : $('input[name="bannertitle"]').val(),
action : 'add_web_banner',
type: 'add_web_banner'
};*/ //not working
/*let formData = {
var formData = new FormData($("form#addWeb-Banner")[0]);
formData.append('token': token);
};*/ //not working
//*POST Image sent in (binary way), I dont want to use JSON in types*//
$.ajax({
type: 'POST',
data: formData,
cache: false,
success: function(response) {
hide_loader();
if (response.status == "success") {
$("form#addWeb-Banner")[0].reset();
alert("Great");
} else {
alert("Ops!");
}
},
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="bs-example form-horizontal AddWebBanner" id="addbanner" enctype="multipart/form-data" method="POST">
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Upload Image</label>
<div class="col-lg-8">
<input type="file" class="form-control" title="Upload Photo" id="BannerImage" name="imagehere" accept="image/png,image/jpg,image/jpeg" />
</div>
</div>
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Caption of Banner</label>
<div class="col-lg-8">
<input type="text" class="form-control" title="Caption of Banner" name="bannertitle" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-lg-12">
<button type="submit" name="submit" class="btn btn-sm btn-default pull-right" id="addBannerBtn">POST</button>
</div>
</div>
</form>
Change your HTML and formData to the following
Give an id selector your caption banner.
<input type="text" class="form-control" id="caption_banner" title="Caption of Banner" name="bannertitle" />
Store using the formData like this and then sent formData via ajax
var formData = new FormData();
//Append Image
formData.append('file', $('#BannerImage')[0].files[0]);
//Append banner caption
formData.append('caption', $('#caption_banner').val());
You can also use jQuery .serialize method to send data to your backend via ajax
var formData = $('form#addbanner').serialize()
thank for #AlwaysHelping but there was one mistake but I has been fix that..below are the correct answer for future user troubles..
I not mentioned processData: false, contentType: false, in ajax.. so the final code will be..
var formData = new FormData();
formData.append('file', $('#BannerImage')[0].files[0]);
formData.append('caption', $('#caption_banner').val());
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (response) { ... }
peace :)

Problem in pass form and file data with ajax and jQuery

I want to pass some form data and file to a flask application from a form. but I can't pass it with ajax. There is a problem in data I guess. I've send data in ajax but in flask application I don't get any string or files.
Here is my html code:
<form id="user_vote" enctype = "multipart/form-data">
<br>
<br>
<div class="row">
<label class="col-sm-2">Name:</label>
<div class="col-sm-10">
<input type="text" name="name" id="name" rows="2" class="form-control" required>
</div>
</div>
<div class="row">
<label class="col-sm-2">National ID Image:</label>
<div class="col-sm-10">
<input type="file" name="national_id_image" id="national_id_image" rows="2" class="form-control" required>
</div>
</div>
<br>
<div class="row">
<label class="col-sm-2">Vote:</label>
<div class="col-sm-10">
<input type="number" name="vote" id="vote" rows="2" class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-lg-12 text-center">
<input type="button" id="submit_vote" class="btn btn-primary btn-lg"
value="Authenticate and Encrypt Vote">
</div>
</div>
And here is my ajax code::
$(function(){
var form = $('#user_vote')[0];
var data = new FormData(form);
//console.log('hello');
//console.log(document.getElementById('submit_vote'));
$('#submit_vote').click(function(){
//console.log(data);
//console.log('hello');
$.ajax({
url: '/encrypt/vote',
type: "POST",
dataType: 'json',
enctype: 'multipart/form-data',
data: data,
contentType: false,
cache: false,
processData:false,
success: function(response){
//console.log("SUCCESS : ", data);
document.getElementById("encrypted_vote").innerHTML = response['encrypted_vote'];
document.getElementById("public_key").innerHTML = response['signature'];
document.getElementById("warning").style.display = "block";
},
error: function(error){
console.log(error);
}
});
});
})
Flask codes::
app.route('/encrypt/vote', methods=['POST'])
def encrypt_vote():
print('test')
name = request.form['name']
print(name)
family_name = request.form['family_name']
birth_date = request.form['birth_date']
national_id = request.form['national_id']
file = request.files['national_id_image']
filename = str(name) + str(family_name)# + secure_filename(file.filename)
#file.save(os.path.join(app.root_path, UPLOAD_FOLDER, filename))
#voter_national_cart_hash = get_digest('files/uploads/' + filename)
print('test vote type')
print(request.form['vote'])
vote = int(float(request.form['vote']))
pk = int(float(request.form['public_key']))
encrypted_vote = encrypt(pk, vote)
response = {
'encrypted_vote': str(encrypted_vote)
}
return jsonify(response), 200
Anyone can help me??
Thanks
It seems that you set enctype: 'multipart/form-data', which is non-existent property of the $.ajax() method. You should correct this error and simplify the request:
$.ajax({
type: "POST",
data: data,
url: '/encrypt/vote',
cache: false,
contentType: false,
processData: false,
success: function(response) {
/*The rest of your code*/
},
error: function(error){
console.log(error);
}
});
There is no need to set dataType, the default is Intelligent Guess (xml, json, script, or html). Read more here.
EDIT: Make sure you are using correct full path in the url, try not to use relative address, use https://www.your-server.com/encrypt/vote instead.

How to send Form Input field into JSON Format using Jquery Ajax

I want to send data on the controller into JSON format. but getting into a string. so can I do this?
I used header that is being passed on ajax call but it not converting Form filed into JSON format .
due to string format Laravel not able to process this response.
My Browser Response.
HTML Code
<form id="NoeticeBoardGetAllFrm" name="NoeticeBoardGetAllFrm" role="form" method="post" >
<div class="row">
<div class="col-sm-6">
<label> URL </label>
<input type="text" name="NoeticeBoardGetAllUrl" id="NoeticeBoardGetAllUrl"
class="form-control" placeholder="URL"
value="https://XXXXXXXXXXXX/get-all-notice-board-information"/>
</div>
<div class="col-sm-4">
<label> Session Code </label>
<input type="text" name="scode" id="scode" class="form-control"
value="cFZnMVJUY0JNUUJsTXZBeVZhZmRHZz09"
maxlength="50" minlength="32" placeholder="Session Code"/>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">
<input type="submit" name="NoeticeBoardGetAllBtn" id="NoeticeBoardGetAllBtn"
class="btn btn-danger " value="Get Result" />
</div>
<div class="col-sm-3"> <i class="fa fa-reddit-square"></i>
<span class="inLine">Result :</span>
<div id="NoeticeBoardGetAllResult" class="inLine result_box">---</div>
</div>
</div>
</form>
My Javascript Code
$("#NoeticeBoardGetAllFrm").submit(function(e) {
e.preventDefault();
console.log( new FormData(this));
$.ajax({
url: $("#NoeticeBoardGetAllUrl").val(),
type: 'POST',
headers: {'Accept': 'application/json','Content-Type': 'application/json',
'DBAuth': $("#DBAuth").val(),'Authorization': $("#Authorization").val(),},
dataType: 'json',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
if (data.error == 0) {
$("#NoeticeBoardGetAllResult").html("Record fetched successfully!");
$("#NoeticeBoardGetAllResult").addClass("alert alert-success");
} else {
$("#NoeticeBoardGetAllResult").html(data.errmsg);
$("#NoeticeBoardGetAllResult").addClass("alert alert-warning");
}
}, statusCode: {
500: function (data) {
$("#NoeticeBoardGetAllResult").html("Something went wrong!");
$("#NoeticeBoardGetAllResult").addClass("alert alert-danger");
},
401: function (data) {
$("#NoeticeBoardGetAllResult").html("Login Failed");
$("#NoeticeBoardGetAllResult").addClass("alert alert-danger");
}
}
});
setTimeout(function(){ resetResult(); }, 3000);
});
You can use serialize method to send Data as Json
$('#NoeticeBoardGetAllFrm').serialize()
You should use this in place of
data: new FormData(this),
instead of data: new FormData(this);
use following
data: $(this).serializeArray();
It gets your form data and serialize into array that is ready of convert into JSON.

ajax submit form with file

I have form, with ajax, that contain textarea and upload file field
I can submit only one of them.
how can I fix that?
I want to send "info" + "filesData" to the server.
Please advise.
Thank you in advanced
AJAX :
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var files_data = form_data;
alert(files_data);
var act = 'add';
var $form = $("#addCommentForm");
var info = $form.serialize();
info += '&act=' + act ;
alert(info);
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: files_data,
success: function(data)
{
// alert(data); // show response from the php script.
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false;
});
});
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-8 col-xs-12">
<textarea class="form-control" name="post[text]"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-xs-12">
<input type="file" class="form-control" name="file" id="files">
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label" for="textinput"></label>
<div class="col-md-8 col-xs-12">
<a class="btn btn-primary" id="submit">submit</a>
</div>
</div>
</form>
PHP
print_r ($_FILES);
print_r ($_POST);
In $.ajax call, subtitute the value of data parameter (filesData) by:
{ field1 : field1value, field2 : field2value, .... }
use as many field/value pairs as you need
you also can get the values directly like this:
{ field1 : $('#commentsBox').text(), field2 : $('#yourinput').val(), .... }

how to find a parent?

i have a problem with finding parent for form in this code:
<li class="comment<?php echo $comment[id]?>">
<div class="comment-content">
<div class="comment-top">
<div class="comment-nme">
<?php echo $comment[name]?>
</div>
<div class="comment-dt">
<?php echo $comment[dt]?>
</div>
</div>
<div class="comment">
<?php echo $comment[comment]?>
</div>
<a class="reply" href="#comment<?php echo $comment[id]?>">Ответить</a>
</div>
<div class="answer-form">
<form method="post" name="answer-form" class="ans">
<textarea class="comment-textarea" name="comment"></textarea>
<div class="a-comment-inputs">
<input type="hidden" name="parent_id" value="<?php echo $comment[id]?>">
<input type="hidden" name="status" value="new">
<div class="a-comment-name">
Имя</br>
<input type="name" name="name" class="a-comment-name">
</div>
<div class="a-comment-email" >
Eмейл</br>
<input type="email" class="a-comment-email" name="email">
</div>
</div>
<div class="comment-apply">
<button value="submit" onclick="return sendDataChild();" class="answer-but">Добавить</button>
</div>
</form>
</div>
<?php if($comment[childs]){ ?>
<ul class="commentsRoot<?php echo $comment[id]?>">
<?php echo commentsString($comment[childs]) ?>
</ul>
<?php } ?>
</li>
i use this jQuery function:
function sendDataChild() {
var form = $('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form[0].reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};
but it select every form that find on button click.
Can somebody advise how to solve it?
one possible solution
<button value="submit" onclick="return sendDataChild(this);" class="answer-but">Добавить</button>
then
//pass the clicked button reference then find the parent form of the button
function sendDataChild(btn) {
var form = $(btn).closest('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form[0].reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};
Bind submit event on the form and pass the object to the form object to your method
$(document).ready(function(){
$("form[name='answer-form']").on('submit', function(){
sendDataChild($(this));
});
});
function sendDataChild(form) {
var data = form.serialize();
$.ajax({
type: "POST",
url: "req.php",
dataType: "json",
data: data,
cache: false,
success: function (data) {
form.reset();
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
//$("#messageModalDialog").text(resultStat).show();
});
return false;
};

Categories