ajax submit form with file - php

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(), .... }

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.

Getting a null value in my input file type field

I downloaded a web application and i found out that it is created using Smarty Template Engine. I want to add an avatar field when creating new company so i added enctype="multipart/form-data" and <input type="file" name="avatar"> to the existing <form> and i also added avatar to my companies table in my database. Here is the HTML code:
<form class="form-horizontal" id="ib_modal_form" enctype="multipart/form-data">
<div class="form-group"><label class="col-lg-4 control-label" for="company_name">{$_L['Company Name']}<small class="red">*</small></label>
<div class="col-lg-8"><input type="text" id="company_name" name="company_name" class="form-control" value="{$val['company_name']}"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="avatar">{$_L['Avatar']}</label>
<div class="col-lg-8"><input type="file" name="avatar"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="email">{$_L['Email']}</label>
<div class="col-lg-8"><input type="text" id="email" name="email" class="form-control" value="{$val['email']}"> </div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger">{$_L['Cancel']}</button>
<button class="btn btn-primary modal_submit" type="submit" id="modal_submit"><i class="fa fa-check"></i> {$_L['Save']}</button>
</div>
I found out that the form goes to this javascript code when clicking the Save Button:
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
$.post( _url + "contacts/add_company_post/", $("#ib_modal_form").serialize())
.done(function( data ) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
});
});
Here is the code in the Controller:
case 'add_company_post':
$data = ib_posted_data();
$company = Model::factory('Models_Company')->create();
$company->company_name = $data['company_name'];
$company->url = $data['url'];
$company->email = $data['email'];
$company->phone = $data['phone'];
$company->logo_url = $data['logo_url'];
$company->avatar = $_FILES['avatar']['name'];
$company->save();
break;
The problem is that it does not recognize $_FILES['avatar']['name']; in the Controller Whenever i add a new company, i get a NULL value in my database. I cant seem to solve this problem. Any help would be appreciated. Thanks.
Change
From
$("#ib_modal_form").serialize()
To
new FormData($("#ib_modal_form")[0])
You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value.
Can you change your ajax call below way
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
var formData = new FormData($("#ib_modal_form")[0]);
$.ajax({
url: _url + "contacts/add_company_post/",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
},
});
});

Codeigniter save ajax response

I want to save the ajax response I get into my database. The problem is that my ajax function doesn't allow my to put a insert query. When I Insert the insert query, my response doesn't work anymore and vice versa.
where ajax file is
public function submit() {
$data = array(
'user_id' => '1',
'swipedpicture' => $this->input->post()
);
$this->db->insert('tbl_results', $data);
print json_encode($data);
}
Ajax Jquery
var pic = $(this).find('input[name="inputcountry"]').attr('value');
jQuery.ajax({
type: "POST",
url: window.location.origin +"/swipr/index.php/preferences/submit",
dataType: 'json',
data: {swipedpic: pic},
success: function(res) {
if (res) {
console.log(res.swipedpicture);
}
}
});
Your javascript is setting a data element for posting that the submit function is not using.
The submit function should look like this.
$data = array(
'user_id' => '1',
'swipedpicture' => $this->security->xss_clean($this->input->post('swipedpicture'))
);
$this->db->insert('tbl_results', $data);
$response_array['status'] = 'success';
echo json_encode($response_array);
The javascript should look more like this. I used an form id of form1 and a form element of swipedpicture.
$('#form1').submit(function(e){
e.preventDefault();
$.ajax({
url: 'example_answer_submit',
type: 'POST',
data: $('#form1').serialize(),
success: function (msg) {
if (!msg) {
console.log('error');
} else {
console.log('success');
}
}
});
return false;
});
The form I used.
<h1 class="page-header text-center">Test Form</h1>
<form id="form1" class="form-horizontal" role="form" method="post" action="">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Swiped Picture</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="swipedpicture" name="swipedpicture" placeholder="Pic" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>

bootstrap modal cannot assign input value

I've my call to ajax
$("#box-modal").on("shown",function(event)
{
$("#selectproductname").change(function(){
var valueProduct = $(this).val();
event.preventDefault();
$.ajax({
type:'GET',
url:'/ajax/products_ajax.php?idProducto='+valueProduct+'&opcion=2',
async:true,
datatype:'text',
success: function(data)
{
$("#editor-panel").load("/ajax/order.html");
$("#editor-actions").removeClass("hidden");
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
if(debug)
{
inputs[0].value="holaaa";
}
}
first I get the data with php, I get
1#jeans*1.00**0#100
after I want to assign this data a my order.html,
example:
inputs[1].value = jeans
inputs[2].value = 1.00
inputs[3].value = null
I get with console.log(inputs)
[item: function, namedItem: function]
0: input#inputnombre
1: input#inputidproducto
2: input#inputprecio.form-control
3: input#inputcantidad.form-control
4: input#inputdescatalogado.form-control
inputcantidad: input#inputcantidad.form-control
inputdescatalogado: input#inputdescatalogado.form-control
inputidproducto: input#inputidproducto
inputnombre: input#inputnombre
inputprecio: input#inputprecio.form-control
length: 5
When I do inputs[0].value="hello";
I get the error:
Uncaught TypeError: Cannot set property 'value' of undefined
In ajax order I have:
<div class="panel panel-body">
<form role="form" class="form-horizontal" id="form_order">
<div class="form-group">
<label for="inputnombre" class="col-md-4 col-xs-4 control-label">Nombre producto</label>
<div class="col-md-4 col-xs-4 control-label">
<input id="inputnombre" name="inputnombre" required type="text" />
<input type="hidden" name="inputidproducto" id="inputidproducto"/>
</div>
</div>
<div class="form-group">
<label for="descripciontext" class="col-md-4 col-xs-4 control-label">Descripcion</label>
<div class="col-md-4 col-xs-4 control-label">
<textarea cols="30" rows="10" id="descripciontext" name="descripciontext"></textarea>
</div>
</div>
<div class="form-group">
<label for="inputprecio" class="col-md-4 col-xs-4 control-label">Precio</label>
<div class="col-md-4 col-xs-4 control-label">
<input id="inputprecio" name="inputprecio" class="form-control" required type="text" />
</div>
How could I make the code easier?
Ajax .load takes time, you need to assign your values when .load is completed
$("#box-modal").on("shown", function(event) {
$("#selectproductname").change(function() {
var valueProduct = $(this).val();
event.preventDefault();
$.ajax({
type: 'GET',
url: '/ajax/products_ajax.php?idProducto=' + valueProduct + '&opcion=2',
async: true,
datatype: 'text',
success: function(data) {
// Ajax load takes time, you need a complete function here
$("#editor-panel").load("/ajax/order.html", function() {
// do below when "/ajax/order.html" is loaded
$("#editor-actions").removeClass("hidden");
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
if (debug) {
inputs[0].value = "holaaa";
}
});
}
});
});
});
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
jquery
var inputs = $("#editor-panel input").eq(0).val("hello");

Categories