my problem is: I want to upload image/pdf with ajax. In my code i have multiple inputs but i do not use FormData() to pass data from input to my upload.php. All work perfect. So here for better imagine:
$('#addData').on('click', function(){
var c_zakazky = $('#c_zakazky').val();
var pozicia = $('#pozicia').val();
var p_cislo = $('#p_cislo').val();
var stav = $('#stav').val();
var tech = $('#tech').val();
var zar = $('#zar').val();
var operator = $('#op').val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;
//alert(dokument);
$.ajax({
url: 'add.php',
type: 'POST',
processData: false,
contentType: false,
data: {
otk: 1,
c_zakazky: c_zakazky,
pozicia: pozicia,
p_cislo: p_cislo,
stav: stav,
tech: tech,
zar: zar,
operator: operator,
datum: datum
},
success: function(data){
$('#live_data').html(data);
$('#modalInsert').modal('hide');
$('#c_zakazky').val();
$('#pozicia').val();
$('#p_cislo').val();
$('#stav').val();
$('#tech').val();
$('#zar').val();
$('#op').val();
$('#dokument').val();
fetch_data_otk();
alert(data);
}
});
});
And now if i want to iclude image to this how to do it? I tried add this:
var data = new FormData();
data.append('image', $('#image').prop('files')[0]);
console.log(data);
but when i select image/pdf and hit upload in console (data) is empty and i do not know hot to do it.
Please Try this, if you want console formdata object attributes.
// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
// Display the key/value pairs
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
Please take a look at the sample code to save your data and image/media files to form_data and then using AJAX to save the said data in the backend
<!DOCTYPE html>
<head>
<title>Example</title>
</head>
<body>
<form enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_img" name="img_url" multiple>
</div>
<input type="button" class="btn btn-primary" name="submit" value="Submit" onclick="myfunction();">
</form>
</body>
<script>
function myfunction(){
var form_data = new FormData();
var image = document.getElementById('upload_img').files.length;
for (var x = 0; x < image; x++) {
form_data.append("image", document.getElementById('upload_img1').files[x]);
}
$.ajax({
url : 'your-backend-file-with-DB-Query.php',
method : 'POST',// OR GET
data: form_data,
dataType: 'json',
success:function(data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
}
</script>
</html>
I unable to understand, what exactly you want but please try below code, it will submit all form elements data:
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize() + "&post1&post2",
success : function(){
},
error : function(){
}
}
OR
$.ajax({
url: 'url',
type: "POST",
data: new FormData(this),
success : function(){
},
error : function(){
}
});
this is what i do and works
append the formdata,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files is class, i use because i am creating form dynamically
add dynamic data also
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
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 (data) {
// success
}
});
So thank you for help. Now it works perfect. SOLUTION:
I changed only script (php code is still same)
//pridanie udajov
$('#addData').on('click', function(){
var fileInput = document.querySelector('form input[type=file]');
var attachment = fileInput.files[0];
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;
var formData = new FormData();
formData.append('otk', 1);
formData.append('c_zakazky', $('#c_zakazky').val());
formData.append('pozicia', $('#pozicia').val());
formData.append('p_cislo', $('#p_cislo').val());
formData.append('stav', $('#stav').val());
formData.append('tech', $('#tech').val());
formData.append('zar', $('#zar').val());
formData.append('op', $('#op').val());
formData.append('datum', datum);
formData.append('image', $('#image').prop('files')[0]);
console.log(formData);
$.ajax({
url: 'add.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data){
$('#live_data').html(data);
$('#modalInsert').modal('hide');
$('#c_zakazky').val();
$('#pozicia').val();
$('#p_cislo').val();
$('#stav').val();
$('#tech').val();
$('#zar').val();
$('#op').val();
$('#dokument').val();
fetch_data_otk();
alert(data);
}
});
});
Related
I wanna create array from ajax response. I took array from ajax and i have to create dynamic data for chips
materializecss autocomplete
response from ajax
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});
}
});
$('.chips-placeholder').chips({
placeholder: lang_('Your tag'),
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
// I need data like this from response
data: {
'Google', null
'Googol', null
},
limit: 5,
minLength: 2
}
});
<div class="chips chips-placeholder chips-autocomplete input-field" style="background:#fff">
<input class="input tags" placeholder="tag" autocomplete="off" />
</div>
that's my code
Finally, thanks to #Vel to find right answer.
jsfiddle - work code
You need to do like this.
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
/*$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});*/
// ['google', 'googol'] <- this array I take from ajax
tag = ['google', 'googol'];
var obj = {};
$(tag).each(function (index, value) {
obj[value] = null;
});
$('.chips').chips({
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
data:obj,
}
});
}
});
fiddle link
[SOLVED]
That was THE most difficult bug ever - all due to copy/paste stuff up.
This:
$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
should have been that:
$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');
The damn '+bUID+' was pasted AFTER the " , not BEFORE!
Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))
Here's the js:
$('form').submit(function(e){
bUID = $(this).find('input[name=bUID]').data("buid");
e.preventDefault();
submitForm(bUID);
alert(bUID);
});
function submitForm(bUID) {
var name = $('#name'+bUID).val();
var email = $('#email'+bUID).val();
var message = $('#message'+bUID).val();
var code = $('#code'+bUID).val();
alert(bUID);
// also tried this
var post_data = {
'name': $('#name'+bUID).val(),
'email': $('#email'+bUID).val(),
'message': $('#message'+bUID).val(),
'code': $('#code'+bUID).val(),
'buid': bUID,
};
alert(Object.keys(post_data).length);
// ALSO tried this instead of ajax:
//$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
alert(response);
$.ajax({
dataType: "json",
type: "post",
data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
//data: post_data,
url: $('#contact_form'+bUID).attr('action'),
success: function(response) {
if (typeof response !== 'undefined' && response.length > 0) {
if (response[0] == "success") {
$('#success'+bUID).append('<p>Success</p>');
}
else {
$('#errors'+bUID).append('<p>' + js_errors + '</p>');
$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
$.each(response, function(i, v){
if (i > 0) {
$('#error_list'+bUID).append('<li>' + v + '</li>');
}
});
}
}
}
});
}
here's the action in view.php:
<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>
<form id="contact_form<?php echo $bUID; ?>"
class="contact-form"
enctype="multipart/form-data"
action="<?php echo $formAction?>"
method="post"
accept-charset="utf-8">
<?php echo $bUID; ?><br />
<input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">
...etc.
and here's the controller.php:
public function action_submit($token = false, $bID = false)
{
$this->form_errors = array();
array_push($this->form_errors, "error");
array_push($this->form_errors, $_POST['name']);
array_push($this->form_errors, $_POST['email']);
array_push($this->form_errors, $_POST['message']);
array_push($this->form_errors, $_POST['code']);
array_push($this->form_errors, $_POST['buid']);
echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
exit;
}
it gets all data and shows it in alert but then trows the following error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg#gmail.commm","gggggggggggggggggggggggg","gggg","171"]
at r (jquery.js:2)
at Function.each (jquery.js:2)
at Object.success (view.js:132)
at j (jquery.js:2)
at Object.fireWith [as resolveWith] (jquery.js:2)
at x (jquery.js:5)
at XMLHttpRequest.b (jquery.js:5)
Line 132 of the js file is this: $.each(response, function(i, v){
I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg#gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!
What's wrong here? Why doesn't the form get posted?
Thank you very much.
Have you tried adding return false; to prevent your form from submitting to its desired action?
$('form').submit(function(e){
bUID = $(this).find('input[name=bUID]').data("buid");
//e.preventDefault();
//e.stopPropagation();
submitForm(bUID);
alert(bUID);
return false;
});
Try this way,
function submitForm(bUID) {
var name = $('#name'+bUID).val();
var email = $('#email'+bUID).val();
var message = $('#message'+bUID).val();
var code = $('#code'+bUID).val();
$.post($('#contact_form'+bUID).attr('action'), {name:name, email:email, message:message, code:code, buid:bUID}, function(result){
alert(result);
});
}
Your post_data variable was correct. As it is now your data attribute in your ajax is wrong - it's in GET format (a string), not POST. The correct way (json) is;
$.ajax({
dataType: "json",
type: "post",
data: {
name: nameVar,
email: emailVar,
message: messageVar
},
url: ...,
success: function(data) {
...
}
});
I "renamed" your variables to try and avoid variables with the same names as keys (e.g. you want to post "name", setting a variable "name" might conflict).
Just use
data: form.serializeArray()
Like this:
$.ajax({
url: 'url to post data',
dataType: "json",
method: "post",
data: form.serializeArray(),
success: function(data) {
// another staff here, you can write console.log(data) to see what server responded
},
fail: function(data) {
console.log(data) // if any error happens it will show in browsers console
}
});
Another tips: in server side you can use http_response_code(200) for success, http_response_code(400) for errors, http_response_code(403) if authorisation is required
I can retrieve input type text, textarea, select on Ajax / JQuery page. Then variable values are passed to PHP process page where data are retrieve using POST method and data inserted into database table. All things are working fine.
But when I try to retrieve value of input type file variable on Ajax / Query page, it is giving blank value. I tried different codes to do it which I found from internet.
Please advise so I can make necessary changes in my script to make it working.
personal_details.php
<form name="AddForm" id="AddForm" novalidate>
<div class="control-group form-group">
.
.
<input type="file" name="file_photo" id="file_photo">
.
.
other fields like Name, Mail etc
.
.
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary">Send Message</button>
</div>
</form>
personal_details.js
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
.
.
var file_photo = $("file#file_photo").val();
//var file_photo = $('#file_photo')[0].files[0];
//var file_photo = document.getElementById("file_photo").files[0];
$.ajax({
url: "./user/personal_details_p.php",
type: "POST",
data: {
name: name,
email: email,
file_photo: file_photo,
},
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});
personal_details_p.php
$str_name = "";
if (isset($_POST["name"])) { $str_name = trim($_POST["name"]); }
$str_email = "";
if (isset($_POST["email"])) { $str_email = trim($_POST["email"]); }
$str_photo = "";
if(isset($_FILES['file_photo'])) { $str_photo = trim($_FILES['file_photo']['name']); }
.
.
SQL Query to insert data
.
.
$response['status']='SUC';
$response['message']="Data inserted successfully";
echo json_encode($response);
return;
Easy Ajax Image Upload with jQuery, PHP
All textbox, textarea and file type variables will be available on PHP process page with the same name like they have on HTML form page.
I have made my own function for asynchronous upload with progress bar. I will try to write example for you. Also add enctype="multipart/form-data" attribute to your form.
var file_photo = $("file#file_photo").val();
var form = file_photo.parents('form');
file_photo.on('change', processUpload);
var processUpload = function() {
var formData = new FormData(form[0]);
$.ajax({
url: "./user/personal_details_p.php",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandling, false);
}
return myXhr;
},
success: function(json) {
file_photo.val(''); // Empty file input after upload
},
error: function() {
// Do whatever you want as error message
},
data: formData,
cache: false,
contentType: false,
processData: false
});
};
var progressHandling = function(e) {
if(e.lengthComputable) {
// Uploaded bytes: e.loaded / Maximum bytes: e.total
}
};
you can use https://github.com/blueimp/jQuery-File-Upload. It has various options and its documentation is also good. so if you can use plugin you can go with this
Please Try below code for file upload.
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
// my edit for File upload code starts here
var FileData = $('#file_photo').prop('files')[0];
var form_data = new FormData();
form_data.append('file', FileData);
// my edit for File upload code ends here
$.ajax({
url: "./user/personal_details_p.php",
type: "POST",
data: {
name: name,
email: email,
file_photo: file_photo,
},
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});
For accessing file you should have to do like this in jquery:
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var file_data = $("#file_photo").prop("files")[0];
var form_data = new FormData();
form_data.append("doc_upload", file_data)
var data_text=$('form').serializeArray();
$.each(data_text,function(key,input){
form_data.append(input.name,input.value);
});
$.ajax({
url: "./user/personal_details_p.php",
contentType: false,
processData: false,
data: form_data,
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});
jQuery for Updating Database table entry using PHP. after ajax code is not working for me please help.
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(this).parents(".success1").replaceWith(html);
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
You are trying to replace with parent, it must be child. Use below code
success: function (html) {
$("#dynamic-table .success1").replaceWith(html);
}
OR
success: function (html) {
$("#dynamic-table").find(".success1").replaceWith(html);
}
This code works great i have used similar.... try this one..
function FormSubmit() {
$.ajax(
type: "POST",
url: 'success1.php',
data: $("#attend_data").serialize(),
async: false
}).done(function( data ) {
$("#attend_response").html(data);
});
}
I have updated your code snippet below... tested offline and the code is working:
A few pointers:
Instead of this: request/allot_enrollmentNo_gov.php
Try this: /request/allot_enrollmentNo_gov.php
Notice the forward slash ( / ) This indicate that the Ajax path must start from the root directory depending on your server settings.
Use this: $(".success1").html(html); instead of $(this).parents(".success1").replaceWith(html);
Working code below:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "/request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(".success1").html(html);
alert('Response from the POST page = ' + html + ');
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
Now it is working Perfectly by setting parent:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var rowParent = $(this).parent('.success1');
var allottedValue = rowParent.find('input').val();
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
rowParent.replaceWith(html);
}
});
return false;
});
I am currently trying to upload a file through a form I made, using jQuery. This is what I am attempting to do:
function ajax_upload(){
var formData = new FormData($('form#userform'));
$.ajax({
url: location.protocol + "//" + location.host + "/profile/uploadPicture",
dataType: 'json',
data: formData,
type: 'post',
success: function(data, status){
if (data.status == 'error') {
$('#error').html(data.msg);
}
else {
var filename = location.protocol + "//" + location.host + "/data/profiles/" + data.msg;
$('input#filename').val(filename);
close_upload_form();
pop_profilechanger(filename);
}
}
});
return false;
}
the form appears to post to the backend, but while trying to return the filename from the uploaded file in a JSON object like:
echo json_encode(array('status' => $status, 'msg' => $msg));
Is there something wrong?
Please tell me
This is how I do it. If you want more information, rather than just my pasted code, check out this http://www.html5rocks.com/en/tutorials/file/dndfiles/ because my code was made for drag and drop files
handleFiles : function(files, evt, target)
{
console.log(target);
$.each(files, function(index, value)
{
var file = value;
reader = new FileReader();
reader.onload = function(evt)
{
var li = $("<li class='uploading'><img data-image-id='0' src='" + evt.target.result + "' /></li>");
target.find('.imagesList').append(li);
var request = new XMLHttpRequest();
var formData = new FormData();
formData.append('image', file);
request.open("Post", settings.uploadImageUrl);
request.addEventListener("load", function(evt)
{
var id = evt.target.responseText;
li.removeClass('uploading');
li.find('img').attr('data-image-id', id);
}, false);
request.send(formData);
};
reader.readAsDataURL(value);
});
},