Display PDF file inside Magnific-Popup modal - javascript

I have a form on my website that the user needs to fill in order to generate a PDF file. If there are errors in the form, the server will respond with a json object with the list of errors, otherwise will respond with the PDF file (as a string). I'm trying to display that PDF file inside a Magnific-Popup (https://www.npmjs.com/package/magnific-popup).
$('.preview-button').on('click', function (e) {
event.preventDefault();
var theLink = $(this);
var formElement = theLink.closest("form");
$.ajax({
url: theLink.attr('href'),
method: 'GET',
data: formElement.serialize(),
success: function (response, textStatus, jqXHR) {
var contentType = jqXHR.getResponseHeader("content-type") || "";
if(contentType.indexOf('pdf') > -1){
// How can I tell to magnific popup to display the response as PDF?
$.magnificPopup.open({
// tell magnific popup to use the response...
type: 'iframe',
closeOnBgClick: false
});
}
else{
if (response.hasOwnProperty('errors')){
// Form has error, show them
alert(response.errors);
}
}
}
});
});

This might be useful for someone with the same problem: Instead of sending the pdf file as a response, I decided to generate a temporary pdf file in the server and send the path to that file as response. Then we can tell to magnificPopup to display it inside an iframe.

Related

sending array of edited array of files(images) to php script

I have a form containing an input of type file that can accept multiple files(images) as shown below:
<input type="file" id="fileupload" name="fileupload[]" multiple />
Once a user selects an image or multiple images they are added dynamically to the website and also the user can remove one or all of them if he wants to.
Is there a way I can update which files are chosen from the input element to send to php script?
If not how can I send only images the user chooses? I mean I can put what the user chose in another array in JavaScript but how can I send them to php script?
Edited
In more details for example when the user chooses three image files there is JavaScript code i use that appends them into screen as images and the user is given the option to remove one or all of them by clicking on them. So my problem is if the user for example removed one of the images how can I send only the other two images into the php script?
I am not looking for complete code. I am just looking for a hint on how to accomplish it.
I've understood what you want.
Combine Ajax with formData to get that.
$(document).ready(function(){
$("form#data").submit(function(){
// create your filtred list of files from your file input
var data = {};
$.each($('#fileupload')[0].files, function(i, file) {
// Keep only the files that the user has selected
if ( i % 2 == 0){ // <--- CHANGE THIS
data['file-'+i] = file;
}
});
// create a FormData (to send files with AJAX)
var formData = new FormData();
for (var key in data) {
formData.append(key, data[key]);
}
// send that formData
php_script_url = "your_script.php"
$.ajax({
url: php_script_url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Don't forget to include jQuery before this script
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

Run PHP, wait; run JavaScript, wait; then submit form?

What I need to do:
I have an upload form with a file input and hidden text inputs. The user uploads an image, the image gets manipulated and then sent to remote server for processing which takes a few seconds, then the remote server sends the finalized images back to the home server where they are saved in a new folder. JavaScript needs to reach these new images to do further data processing on the newly saved images (which also takes a second). Only after JavaScript has done its thing and updated the form's input variables can the form be submitted.
Right now I've got all of the separate pieces working, but executing everything in one click has proven to be a challenge.
My code for uploading the images:
PHP:
if(isset($_POST['submit'])){
//do image manipulation and save new files using PHP
}
JS:
function furtherProcessing() {
//do further processing on newly saved images in newly created directory,
//update hidden input variables for the form
}
PHP again:
if(isset($_POST['input_variables'])){
//send these variables to SQL database
}
I know trying to use JavaScript to get the newly saved images isn't an ideal approach, but the framework that I'm using is only available in JavaScript. Is this even possible with one click?
You can do this:
In your HTML, add data-processed="false" to your form like this:
<form action="upload.php" method="post" name="q_data" data-processed="false" enctype="multipart/form-data">
In your jQuery call this to submit the images via ajax:
$("form[name='q_data']").submit(function(e) {
var $this = $(this);
var processed = $this.data('processed')
if (processed == false) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: formData ,
async: false,
success: function(msg) {
//alert(msg);
if (msg !== 'success') {
$this.data('processed', true)
furtherProcessing();
}
},
cache: false,
contentType: false,
processData: false
});
}
});
function furtherProcessing() {
//do further processing on newly saved images in newly created directory,
//update hidden input variables for the form
$("form[name='q_data']").submit();
}
In some-page.php do this:
if(isset($_POST['some-image-input-name'])){
//do image manipulation and save new files using PHP
return 'success'
}
However, if it were me, I'd have that first ajax call (that saves the images) simply return the urls for the saved images, then there is no need for a second ajax call to retrieve them which I assume is what you are doing now

Cropping an image on rails

I have the following data both in my js file or as a param in rails. Togther there is an image that is to be sent to server, what I want to achieve is to crop the image based on the data such as below. I am not allowed to use gems :) just using ruby/js code if I can manipulate the image already in js side. I am using cropper js which generated the output to me. What should I do to achieve cropping ?
{"x":552.697358490566,"y":-72.49509433962258,"width":696.9599999999999,"height":696.9599999999999,"rotate":0,"scaleX":1,"scaleY":1}
Check out the fiddle: Link
This is the code you should be using, since your JSON is already formatted the same way Cropper takes its input:
//get the data from your rails framework and save it in a variable, below I just pasted the same data you put in your question
var data = {"x":552.697358490566,"y":-72.49509433962258,"width":696.9599999999999,"height":696.9599999999999,"rotate":0,"scaleX":1,"scaleY":1};
//remember to change my-picture to the id of your img
$('#my-picture').cropper('setData', data);
//also make sure to bind this to your own button
$('#crop-button').click(function(e){
//this will transform the image into a blob, so you can submit it in form data
$(this).href = $('#my-picture').cropper("getCroppedCanvas").toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
//this is where you put your Rails path to upload
//it's going to be a POST, so you should know how to handle it
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
});

Krajee file-input submit files on form submit

I am using this plugin for bootstrap to upload files which is stored in a form with submit button
http://plugins.krajee.com/file-input/
My question is -
a) is there a method or something to either check if there are files in the dropZone that are still not uploaded and notify a user after he submits a form that he didn't uploaded the files
b) is there a method that will trigger the upload when the submit button is fired?
Now it looks like this - if I submit my form it wont upload the files and just pass the form, I have to manually click upload files then submit the form
Maybe some of you came across this issue cause I am not able to figure it out myself due to poor documentation.
I found a work around for this issue.
<input id="input-photos" name="Photos" multiple type="file" class="file-loading">
Define a global variable in Javascript:
var formData = new FormData();
Append the selected files to formData on filePreUpload action.
$('#input-photos').on('filebatchpreupload', function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
$.each(files, function (key, value) {
if(value != null){
formData.append("Photos", value, value.name);
}
}); });
On form submission append all form fields and post the form through ajax.
$('#yourForm').submit(function() {
$('#input-photos').fileinput('upload');
var model_data = $("#yourForm").serializeArray();
$.each(model_data,function(key,input){
formData.append(input.name,input.value);
});
$.ajax({
url: "#Url.Action("Save", "Home")",
type: "POST",
datatype: "json",
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: (function (result){
window.location.href = '#Url.Action("Index", "Home")';
}),
error: function (xhr) {
alert("Error: " + xhr.statusText);
}
});
return false;
});
Validation of required property for form based upload (non ajax) scenario, which will enforce files to be selected and required before upload. This scenario includes custom form submit and reset buttons for upload (and default upload and remove buttons are hidden). The upload will force a file to be selected and required - else a validation error as set in msgRequired will be shown.
Try it:-
https://plugins.krajee.com/file-count-validation-demo#required-non-ajax-1

POST using XMLHttpRequest with existing source

What I am trying to do only using XMLHttpRequest, is this:
The script downloads a web page, that has only one form in it.
The script inserts text into a field.
The script submits the form, while keeping all details about input tags.
I did the first part, but I have no idea how to finish with the next two steps.
Note: I do not have control over the page downloaded, and it is not well-formed XML/HTML.
Could someone explain to me how I can get this done?
This is for a Google Chrome extension, so I have all permissions needed.
EDIT: this is my current code:
$.ajax({ url: "http://www.mysite.com/my/testpage.aspx",
type: "POST",
data: {
html: http0.responseText.between("<body>", "</body>")
},
success: function(data) {
var dom = $(data),
form = dom.filter('form');
form.attr('onsubmit', 'document.getElementById("error").value = "I\'m done!"; document.getElementById("helpmebutton").disabled = false;');
form.attr('action', 'http://www.mysite.com/my/testpage.aspx');
$('#tempdiv').append(form);
form.find('input[name="ctl00$ctl00$cphSite$cphMySiteContent$linkLocation"]').val(document.getElementById("result").value);
form.submit();
}
});
I would really use jQuery to save yourself time and headaches.
Create a temporary div with id tempdiv and put everything in that div. Then, fill in appropriate elements and submit the form, like this:
$.ajax({ url: "http://...",
success: function(data) {
var dom = $(data),
form = dom.filter('form');
$('#tempdiv').append(form);
form.find('input:text').val(123);
// all input[type=text] get value 123
form.submit();
}
});

Categories

Resources