Uploading image with editable div - javascript

Hello I am trying to upload data to the database suing ajax call I have created a script but the problem is that I had a textarea but for some reasons i CHANGED that textarea to and editable div now my question is how do i get data from that div
<form method="POST" action="" id="post" enctype="multipart/form-data" onsubmit="return false;">
<ul>
<li>
<i class="fa fa-photo"></i> Upload A Photo / Document
<input type="file" name="image" />
</li>
</ul>
<div id='display'></div>
<div id="contentbox" contenteditable="true" name="post_dt">
</div>
<input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
</form>
And this is my ajax script created for uploading data
$(document).ready(function(e) {
$("#post").on('submit', (function(e) {
$(document).ajaxStart(function(){
$("#load").css("display", "block");
});
$(document).ajaxComplete(function(){
$("#load").css("display", "none");
});
var form = this;
var content = $("#contentbox").html();
$.ajax({
url : "url/demo/forums/post_forum",
type : "POST",
data : {new FormData(this), content: content},
contentType : false,
cache : false,
processData : false,
success : function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
form.reset();
}
});
}));
});

You're using the correct method to get the content from the editable element: html(). Your issue is how you're sending the data. When sending binary data through FormData you cannot place that inside an object to be encoded. Instead, the additional data must be added to the FormData using append(). Try this:
$("#post").on('submit', function(e) {
$("#load").show();
var form = this;
var formData = new FormData(this);
formData.append('content', $("#contentbox").html());
$.ajax({
url: "http://tfsquare.com/demo/forums/post_forum",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
form.reset();
$("#contentbox").empty();
},
complete: function() {
$("#load").hide();
}
});
});
Also note that I changed your use of ajaxStart() and ajaxComplete() to use the complete method. Defining new global AJAX handlers on every submit of the form is rather redundant.

Related

jQuery FormData and files

I'm attempting to do ajax file upload. When i check the variable form_data it is blank?
<form action='ajax_image_upload/process.php' method='post' enctype='multipart/form-data' class='upload_form'>
<textarea name='description' placeholder='Type Default Video Description'></textarea>
<span>
Channel Image: <input type='file' name='image' />
</span>
<input name='__submit__' type='submit' value='Upload'/>
</form>
var container = $(".upload_form");
var form_data = new FormData();
form_data.append('image', container.find("form > span").children("input[name='image']"));
var post_url = container.children("form").attr("action"); //get action URL of form
//jQuery Ajax to Post form data
$.ajax({
url : post_url,
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
mimeType: "multipart/form-data"
}).done(function(res){
});
How can I solve this?
The issue is because you need to append the binary data from the file input to the FormData, not the jQuery object. Try this:
var fileData = container.find("form > span").children("input[name='image']")[0].files[0];
form_data.append('image', fileData);
Obviously, if there are multiple inputs, or multiple files within the input, you'll need to loop through them and append them individually.

The page got through Ajax cannot use the input type = "file" label?

I get form page through Ajax.
The following is a form of code:
enter code here
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group" style="margin-left:0px;">
<label for="file">注:选择头像文件尽量小于2M</label>
<input id="headPortraitFile" type="file" name="portrait">
</div>
<button id="headPortraitSubmit" type="button" class="btn-sm btn-primary">上传头像</button>
</form>
But the form of the input type = "file" in the browser cannot selected file directly, not to mention the submitted documents. I do not know what reason be? This two days have not been solved, for a great god!!!!!!
here is the Ajax code:
1.I get the form page by this:
$(Document).on("click", '#headPortrait', function() {
$.get("/headPortrait", function(data) {
$(".bodyPart").children().remove();
$(".bodyPart").html(data);
})
})
2.and then I post the form by this:
$(Document).on("click", '#headPortraitSubmit', function() {
var formData = new FormData();
formData.append("portrait", $('#headPortraitFile').get(0).files[0])
$.ajax({
url : "/headPortraitSubmit",
type : 'POST',
data : formData,
processData : false,
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
if (data = "success") {
$(".bodyPart").children().remove();
$(".bodyPart").load('/coding');
}
},
});
})
for attribute value should match id of <input type="file"> if expected result is for change event to be called for <input type="file"> element when <label> element is clicked. Substitute "submit" for "button" at type attribute of <button>.
Document is a function, not html document. Substitute document for Document at parameter passed to jQuery() : $().
if condition within success should use == or === to compare value of data to "success", instead of assigning "success" to data identifier.
$(document).on(/* event, selector, eventHandler */)
$(document).on("click", '#headPortraitSubmit', function() {
var formData = new FormData();
formData.append("portrait", $('#headPortraitFile').get(0).files[0]);
console.log(formData.get("portrait"));
/*
$.ajax({
url : "/headPortraitSubmit",
type : 'POST',
data : formData,
processData : false,
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
if (data === "success") {
$(".bodyPart").children().remove();
$(".bodyPart").load('/coding');
}
},
});
*/
});
document.querySelector("form")
.onsubmit = function(event) {
event.preventDefault();
}
document.querySelector("input[id=headPortraitFile]")
.onchange = function(event) {
console.log(this.files[0])
}
input[type=file] {
display: none;
}
[for=headPortraitFile]:before {
content: 'Label for #headPortraitFile ';
}
#headPortraitSubmit:before {
content: 'Sumbit form .form-horizontal ';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group" style="margin-left:0px;">
<label for="headPortraitFile">注:选择头像文件尽量小于2M</label>
<input id="headPortraitFile" type="file" name="portrait">
</div>
<button id="headPortraitSubmit" type="submit" class="btn-sm btn-primary">上传头像</button>
</form>

How can i post data and file by using ajax on event onclick

HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}

how can i upload file to server using FormData?

I try to file upload to spring server using FormData object. And I hide input for type="file". However, when I submit form, it is not working. I don't know where is incorrect.
This is part of html. when some button is clicked, saveFiles() is called.
<script src="http://malsup.github.com/jquery.form.js"></script>
<form name="fileForm" id="fileForm" method="post" enctype="multipart/form-data">
<input style="display:none" type="file" id="fileSelector" name="fileSelector" multiple="" />
<input type="hidden" id="docId" value="${doc.id}" />
<div id="files"></div>
</form>
(function (global, $) {
...
initFilehandler();
...
}
function initFilehandler() {
document.querySelector('#fileSelector').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#files");
}
function saveFiles() {
$("form#fileForm").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
console.log(formdata);
$.ajax({
url: "/rd/file/save",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert("success");
}
});
});
}
You can't just use formdata for uploading files. There's a lot of options for this one. But Im giving you a less complicated one.
Try using this plugin:
jQuery Form
I've been using that for years especially multiple file uploads. Good thing.. these plugin has callback for upload progress.. you can make a progress bar or something out of it..

Using JQuery and AJAX to pass data to a PHP script

I have an HTML form that Is only composed of a button with a value. I would like to leave it this way. I am using AJAX/JQuery to pass the form data to a PHP script. But, for some reason, the button value is not sent. What could I be doing wrong?
HTML:
<form id="friend-send" method="post" action="">
<button type="submit" class="foll" name="approve-friend" value="4"> Approve </button>
</form>
AJAX/JQUERY:
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = $this.serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});
JQuery won't serialize a button, use a hidden field instead
<form id="friend-send" method="post" action="">
<input type="hidden" name="approve-friend" value="4" />
<button type="submit" class="foll"> Approve </button>
</form>
Also, You need to serialze the form by id, not the button by id
Instead of this
$("#friend-request-buttons")
It should be this
$("#friend-send")
Lastly, since you are using ajax to post, you can simplfy your form open tag to this...
<form id="friend-send">
<button>
tags are not supported by serialize https://api.jquery.com/serialize/
You would need to use an input of some kind. A hidden one would work.
Don't use serialize, create the input data yourself:
var dataString = {};
var $button = $this.find("[type=submit]");
dataString[$button.attr('name')] = $button.val();
When you provide an object as the data: argument to $.ajax, jQuery will serialize it automatically.
This answer would be if you are set on using the button alone
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = "?" + $(this).find('button').attr('name') + "=" + $(this).find('button').attr('value');
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});

Categories