I am trying to upload image to server in summernote. below script is success to submit the form but file not received at backend. am i doing something wrong here?
var edit = function() {
$('.click2edit').summernote({
focus: true,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0],editor,welEditable);
}
});
};
function sendFile(file,editor,welEditable) {
alert(file.size);
var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />');
$("body").append(iframe);
alert("1");
var form = $('#theuploadform');
form.attr("action", "UploadServlet");
form.attr("method", "post");
form.attr("enctype", "multipart/form-data");
form.attr("encoding", "multipart/form-data");
form.attr("target", "postiframe");
form.attr("file", file);
form.submit();
alert("2");
$("#postiframe").load(function () {
iframeContents = $("#postiframe")[0].contentWindow.document.body.innerHTML;
return iframeContent;
});
return false;
}
You can't set a default value to an HTML upload control.
You need to display the form for user choose the file, then you can post to server.
Some references:
http://www.w3schools.com/jsref/prop_fileupload_value.asp
How to set a value to a file input in HTML?
Set default value for a input file form
Thanks all. got an work around for this issue. I changed the summernote code to return a wrapping form and them posted that form. It posted successfully. I have some issue in loading the uploaded image to editor. but i will start another thread for that. thanks all.
Related
I have a form that contains article information and images that I submit using the DropZone library.
I have no problem with this library and it works very well, but when the submitted form had an error and I receive this error message on the client side via Ajax, the user fixes the problems and sends the form again, but unfortunately the form is not sent and no file is left. Not selected
While the files are available in the preview and are sent to the server only once.
What should I do to solve this problem?
Please enter simple codes.
Thanks
successmultiple function
myDropzone.on("successmultiple", function(file,serverResponse) {
/* None of the uploaded files are available in Drop Zone here anymore,
** and I had to delete the files so the user could choose again,
** which would not be a good user experience.
** Exactly what code should I write here so that there is no need to
** re-select files from the user's system?
*/
myDropzone.removeFile(file);
if(serverResponse.status)
{
// Success:: In this case, I have no problem
alert("Article saved successfully. Redirecting to the Articles page ...");
window.location.href = serverResponse.redirectedTo;
}
else
{
// Display errors received from the server to the user
alert("Please enter your name and resubmit the form.");
}
});
I think a possible solution is if you pass the event to your successhandler and prevent it from its default bahaviour.
Like so:
function successHandler(event){
event.preventDefault();
}
This should prevent it refreshing the page and loosing the file in the input.
Otherwise I would just save the file to a variable.
I found the answers to my questions myself and i will put it below for you too.
This code is written for Laravel blade file :
<script>
$("document").ready(()=>{
var path = "{{ $path }}";
var file = new File([path], "{{ $attach->file_name }}", {type: "{{ $attach->mime_type }}", lastModified: {{ $attach->updated_at}}})
file['status'] = "queued";
file['status'] = "queued";
file['previewElement'] = "div.dz-preview.dz-image-preview";
file['previewTemplate'] = "div.dz-preview.dz-image-preview";
file['_removeLink'] = "a.dz-remove";
file['webkitRelativePath'] = "";
file['width'] = 500;
file['height'] = 500;
file['accepted'] = true;
file['dataURL'] = path;
file['upload'] = {
bytesSent: 0 ,
filename: "{{ $attach->file_name }}" ,
progress: 0 ,
total: {{ $attach->file_size }} ,
uuid: "{{ md5($attach->id) }}" ,
};
myDropzone.emit("addedfile", file , path);
myDropzone.emit("thumbnail", file , path);
// myDropzone.emit("complete", itemInfo);
// myDropzone.options.maxFiles = myDropzone.options.maxFiles - 1;
myDropzone.files.push(file);
console.log(file);
});
</script>
I have configured my TinyMCE to use images_upload_url and images_upload_handler to post to a selected image to a server-side page which saves the image to a location on my server. In addition, this server-side page also saves the filename of the image as a record within a database.
I then have another server-side page which reads the database and constructs a JSON list of the images that have been uploaded. This JSON data is then pulled into my Tinymce instance using image_list, so that I can easily reuse previously uploaded images as opposed to having to reupload the same image more than once.
The specific lines of my tiny.init() are:
image_list: 'processes/image-list.php',
image_class_list: [
{title: 'None', value: ''},
{title: 'Full width image', value: 'img-responsive'}
],
images_upload_url: 'processes/upload-image.php',
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'processes/upload-image-free.asp');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
},
image_dimensions: false,
All of this works as expected.
What I would like to do is also save a description of the image to the database so this can be outputted as the title within the JSON data of previously uploaded images.
As the upload feature only allows an image to be selected from a file system I cannot utilise the upload feature:
So I thought I could utilise the alternate description field of the image feature/modal but this would have to be done via a JavaScript triggered event that is triggered upon submitting the image feature/modal, that takes the content in the alternative description input field and POST this to a serverside page that can update the database.
Unless there is another way does anybody know how I can target the 'click' on the 'save' button within the image feature to extract the alternate description before the image feature/modal disappears and extract the input field content?
From there I should be able to work out how to get this to a server-side page to update the database.
Many thanks in advance
I have managed to resolve this so posting a solution to help others - though this is more than a hack.
Firstly on my form page after the tiny.init is loaded I am using the following:
document.addEventListener('keyup', logKey);
function logKey(e) {
labels = document.querySelectorAll(".tox-label");
for (i = 0; i < labels.length; ++i) {
if (labels[i].textContent == "Alternative description"){
imageDescription = document.getElementById(labels[i].htmlFor).value;
}
}
};
This loops through all the elements (labels in this case) which have a class of .toxlabel and if the textContent matches "Alternative description" then to capture the value in in a variable called 'imageDescription'.
Then within my tiny.init I have the following:
editor.on('ExecCommand', function(e) {
if (e.command == "mceUpdateImage"){
var http = new XMLHttpRequest();
var params = encodeURI('desc=' + imageDescription);
http.open('POST', 'processes/upload-image-description.asp', true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
}
});
This code is actioned upon the mceUpdateImage modal closing, it takes the value stored within the imageDescription variable and posts it to a server-side page which updates the database.
I am sure there are cleaner ways but they would require more of a TinyMce understanding.
I'm using jQuery, AJAX and PHP to validate most of the forms on my website. The actual input validation is done via PHP (I thought this would be best to prevent users from bypassing validation using the browser source code inspector to edit scripts), but I use jQuery and AJAX to load errors into an error message div below the form's submit button.
All of this works fine, but when a form is successfully submitted I'd like to call header('Location: foo.php') to send my user back to a certain page. However, since I'm using preventDefault(), my new page is being loaded into the error message div, making the browser window look like it has two pages on top of each other (the current url doesn't change either).
Is there a fix to this? I thought I might be able to unbind the event in the PHP file by including a script after the PHP code is done, but I was not successful.
jQuery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
//this is where the PHP is loading the new page, along with error messages
$(".form-message").load("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
});
});
});
End of PHP file:
<?php
//if successful, exit the script and go to a new page
$submissionSuccessful = true;
exit(header('Location: /index.php'));
?>
<reference path="/javascript/jquery-3.3.1.min.js"></reference>
<script type="text/javascript">
var submissionSuccessful = "<?php echo $submissionSuccessful; ?>";
if (submissionSuccessful)
{
$("#title, #content").css(
{
"border": "2px solid #24367e"
}
);
$("#title, #content").val("");
}
</script>
The approach I talk about is similar to this
$(document).ready(function () {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
// AJAX POST request to PHP
$.post("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
}).done(function (response) {
// response is a JSON document
if (response.error) {
// Here you basically modify the UI to show errors
$(".form-message").text(response.error)
} else {
// Here you basically modify the UI to show success
$("#title, #content").css({ "border": "2px solid #24367e" });
$("#title, #content").val("");
location.href = '/index.php' // REDIRECT!
}
});
});
});
And in the server end
<?php
if ($someSuccessCondition) {
$response = ['success' => true];
} else {
$response = ['error' => 'The Error Message'];
}
echo json_encode($response);
exit();
<script>
function user_pro(useron){
$.post("userprofile.php", { useron:useron } );
document.location.href="userprofile.php";
}
$(document).on('click','#userprofile',function(){
var useron=$(this).data('id4');
user_pro(useron);
});
</script>
i am trying to send data to the page "userprofile.php" through the jquery ajax .post() when i click a button with id 'userprofile'. i have stored the username of the user(which i retrieved from my database in data-id4 attribute ). i want to send this username to my userprofile.php page and display his profile(like dp,status and all...). the .data('id4') method is working fine as i am able to store data in the variable useron . but i am not able to send the data to userprofile.php . and i also simultaneous want to be directed to that page when i click the button with id="userprofile".
<a data-id4='".$row['username']."' id='userprofile' class='w3-btn w3-teal w3-hover-indigo'>profile</a>
this is the html element. the html is inside the echo tag of of a php page(that is why those quotes).
can somebody plz help me out here . thanks in advance :) .
this code worked ...
function post(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
$(document).on('click','#userprofile',function(){
var useron=$(this).data('id4');
post("userprofile.php",{useron:useron});
});
thanks everyone.
Is there an easy solution to POST dynamically aggregated data into a new tab?
chrome.tabs.create does not have a 'POST' option. Normally I would use
chrome.browserAction.onClicked.addListener(function (t) {
chrome.tabs.create(
{
"url" : "http://super.url",
"method" : "POST" // oops.. no option.
});
});
You can simply combine these two techniques:
You may execute JavaScript commands by adding javascript: prefix at your address bar or in href values of <a> tags.
Only with JavaScript, you can create a form element and fill it with your data then POST it.
function fakePost() {
var form = document.createElement("form");
// Create a POST dump at ptsv2.com and change the code
form.setAttribute("action", "http://ptsv2.com/t/dcgex-1614815819/post");
form.setAttribute("method", "post");
var params = { userId: 2, action: "delete" };
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
// Appending the form might not be necessary
document.body.appendChild(form);
form.submit();
};
const
source = fakePost.toString().replace(/(\n|\t)/gm,'').replace(/\s\s/gm,' '),
url = `javascript:${source}; fakePost();`;
chrome.browserAction.onClicked.addListener(() => chrome.tabs.create({ url }));
Of course, that's just a dirty hack. If you need something more elaborate you can use a XHR Object or #Xan's answer.
The code in cvsguimaraes' answer works for short data strings, that can fit into a URL.
As evidenced by this question, it's not always the case.
Kenny Evitt's answer hints at the solution. I made an implementation for that question, and took time to generalize it. I present it here.
The idea is to open a page bundled with the extension (post.html), supply it with required information via messaging, and perform the POST from that page.
post.html
<html>
<head>
<title>Redirecting...</title>
</head>
<body>
<h1>Redirecting...</h1>
<!-- Decorate as you wish, this is a page that redirects to a final one -->
<script src="post.js"></script>
</body>
</html>
post.js
var onMessageHandler = function(message){
// Ensure it is run only once, as we will try to message twice
chrome.runtime.onMessage.removeListener(onMessageHandler);
// code from https://stackoverflow.com/a/7404033/934239
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", message.url);
for(var key in message.data) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", message.data[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
}
chrome.runtime.onMessage.addListener(onMessageHandler);
background.js (or other non-content script inside the extension)
function postData(url, data) {
chrome.tabs.create(
{ url: chrome.runtime.getURL("post.html") },
function(tab) {
var handler = function(tabId, changeInfo) {
if(tabId === tab.id && changeInfo.status === "complete"){
chrome.tabs.onUpdated.removeListener(handler);
chrome.tabs.sendMessage(tabId, {url: url, data: data});
}
}
// in case we're faster than page load (usually):
chrome.tabs.onUpdated.addListener(handler);
// just in case we're too late with the listener:
chrome.tabs.sendMessage(tab.id, {url: url, data: data});
}
);
}
// Usage:
postData("http://httpbin.org/post", {"hello": "world", "lorem": "ipsum"});
Note the double messaging: with chrome.tabs.create callback we can't be sure that the listener is ready, nor can we be sure it's not done loading yet (though in my testing, it's always still loading). But better safe than sorry.
From #Amman Cheval's comments on the question:
[send] your dynamic data to the background file, creating a new tab which includes a form. Fill up the form using your form using the content using the background file, and then submit the form.
Read up about content scripts on Google's docs first. Then read up on message passing. After you've understood all of that, it'd be fairly simple to send a message from the script, to the background, and to the script of a different tab.