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

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

Related

What is the jquery data parameter for php file upload in this example?

I have an html page with a section that collects basic customer information: email, first and last name, etc. The form ends with a button for the end-user to click, and I'm using an onClick event to call a jquery script. The jquery script calls a php file to send the data to the server.
For example:
function postData() {
return $.ajax({
url : 'upload.php',
type: 'POST'
});
}
function sendReply() {
// autoresponder
}
postData().done(sendReply);
In some examples, I have seen a "data" parameter that would go in the postData function. For example:
function myAjax() {
$.ajax({
type: "POST",
url: 'your_url/ajax.php',
data:{action:'call_this'},
});
}
My question is: if I'm calling upload.php, will that automatically take the form data and process it in the php file, provded that the php file is coded correctly for form data upload (using $_POST['variable_name'];)? In other words, is the data parameter in this jquery code irrelevant when I'm calling a php file with html data?
I'm sorry if this question is very elementary, but I'm new to php and I've never done this before.

Return variable from PHP after AJAX Post

I've read countless examples but I just can't get the following to work. I want to submit a form, process it on the server side then decide which php script to load into a div (dynamic loading I can do).
The head:
$.ajax({
type: "POST",
url: url, // passed with onclick
data: $("#" + formName).serialize(),
success: function(data) {
// Some JSON? to go here to store variable returned from PHP ($thisVariable)
}
});
return false; // avoid to execute the actual submit of the form.
The php:
// Process the request (add to database e.g.)
$thisVariable back to ajax

load php page from jquery ajax post unloading the current page

I need to generate a report showing in a php page which will be called by a jquery ajax call. Can any body help me on how to do this.
The jquery ajax post is as following:
$('#report_condition #Submit_rpt_betn_dates').on('click', function(){
var start_dt = $('#report_condition').find('.rpt_betn_dates').find('.start_search_date').val();
var end_dt = $('#report_condition').find('.rpt_betn_dates').find('.end_search_date').val();
alert('you want to generate report between '+start_dt+' and '+end_dt);
$.ajax({
type: "POST",
url: "./report-betn-dates.php",
data: {'startdt':start_dt, 'enddt':end_dt}, //the first parameter in the pair is actually the key for $_POST in PHP
//and it must be withing quotes for ajax to run!!
crossdomain: true,
success: function(response) {
}
});
});
I tried with $('body').html(response); within success parameter of the ajax call. But by this I cannot access the separate css file for the php page. Hence I would like to unload the page containing the ajax call and load the php page with the data sent through $_POST[].
Ajax is for partial content load, asyncronous interactions , etc.. Since what you're trying to achieve is complete new page loaded with its own static resources (css, js) this is the perfect "syncronous" scenario.
So, why wouldn't you use a simpler setup like a form which sends the required vars in post and moves the user to the correct php page?
$('#report_condition #Submit_rpt_betn_dates').on('click', function(){
var fake_form = $('<form method="post" action="report-betn-dates.php">');
var input_start = $('<input type="hidden" name="startdt">');
var input_end = $('<input type="hidden" name="enddt">');
$(fake_form).append(input_start);
$(fake_form).append(input_end):
$(fake_form).submit();
});

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>

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

Categories

Resources