PHP jQuery .ajax() file upload server side understanding - php

I have an HTML form that previously was only used for text attributes for users, that was all using AJAX to call a PHP controller functions via URLs to refresh page content via database and server-side calls (abridged version)
<input type="text" id="firstname" name="FIRSTNAME"/>
<input type="text" id="lastname" name="LASTNAME"/>
<input name="Submit"type="submit" value="Submit" />
This "create user" form now needs to incorporate a file uploading mechanism, for user images
<input type="file" name="userImage" />
The problem is that the form is being submitted via .serialize in the .ajax #create form submit
$.ajax({
url: 'controller.php?command=create',
type: 'POST',
data: $( form ).serialize(),
create URL calls the PHP controller echo $dmv->create(); , which is the model public function create(){ //execute database insert and execute
I have read that serialize does not make sense for files, which is true, but I also want to try to figure out how to update my existing form to incorporate file upload functionality to it
I have tried to understand the jquery.form.js plugin ( http://malsup.com/jquery/form/#file-upload ) but cannot understand how to tie it all together.
I believe what I need to do is have the file upload execute as a separate logic, then tie back with the original logic for file name , this is file storage with the unique image name stored in the database under the record, not BLOB image storage.
Let me know if I can provide any further info, and thanks to any help that can be given.

You can't upload files via AJAX. The only possibilites you have are using Flash (such as Uploadify: http://www.uploadify.com/), an iFrame, or just submitting the form. The form must have an enctype set to multipart.
<form action="script.php" method="post" enctype="multipart/form-data">
Plugins may mimic AJAX file uploads by creating a "hidden" iframe.
Example: http://valums.com/ajax-upload/

You can mimic an AJAX call by using a hidden iframe. You can even achieve a callback function and get the server response just like an AJAX call:
HTML --
<form enctype="multipart/form-data" target="workFrame"></form>
<iframe id="workFrame" style="display:none;"></iframe>
JS--
//bind an event handler to the form with the file input
$('form').on('submit', function () {
//check to make sure the user has selected an image, if not then stop the form from submitting
if ($('#userImage').val().length == 0) return false;
//bind an event handler to the `load` event for the iframe so we will have a callback for the form submission
$('#workFrame').on('load', function () {
var $this = $(this);
//remove this event handler
$this.off('load');
//get the response from the server
var response = $this.contents().find('body').html();
//you can now access the server response in the `response` variable
});
//return true so the form submits normally
return true;
});
Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.

Here is a example of what Michael is talking about. http://www.phpletter.com/Our-Projects/AjaxFileUpload/

Related

Send Form data with Cordova InAppBrowser

I'm trying to send a POST request to a PHP server using a form. The form is filled at runtime and stored inside a .js file. I can access the form by using $('#form') anytime.
My problem is here:
I have to send this form using the Cordova InAppBrowser. I'm loading the page, but I'm not able to pass the form.submit() to the InAppBrowser page.
I'm using the following code:
javascript
var ref = window.open('https://www.paypal.com/it/cgi-bin/webscr', '_blank');
ref.addEventListener('loadstop', function (event) {
ref.executeScript({
file: "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"
},
function () {
ref.executeScript({
code: "jQuery('#payform').submit();"
});
});
});
ref.show();
form
<form id="payform" action="https://www.paypal.com/it/cgi-bin/webscr" method="post" target="_self">;
<input type="hidden" ...
...
</form>
The page loads at the given url, but I'm not able to pass input elements.
What am I doing wrong?
Thank you :)

How to see the Files uploaded in a form with ajax?

I'm trying to upload a file send in a form. I'm trying it with php, but between html and php I use JS and Jquery and ajax (because I don't want the page to reload). And I'm having troubles with the $_FILES.
Here it is, I'm using a form (which contains a file input) with a javascript action (action="javascript: SendPresupMail();").
In that JS function I use a little Jquery and ajax, inside it, there is a call to a php function.
The problem is that inside that php function the $_FILES is empty, and I need to upload the file send in the form.
Here is the code:
HTML form, calling to JS:
<form action="javascript: sendPresupMail();" method="post" id="formId" enctype="multipart/form-data">
<input type="text" id="mail" name="mail" />
<input type="file" id="file_selected" name="file_selected" />
<input type="submit" value="Submit" />
JS function, and call to PHP with AJAX and JQUERY:
function sendPresupMail() {
$.ajax({
url: 'remote.php',
type: 'post',
data: {
'w': 'sendPresupMail',
'mail': document.getElementById('mail').value
},
success: function(data) {
if(data != "ok" && data != ""){alert(data);}
if(data == "ok"){alert("mail send.");}
}
});
}
Finally, the PHP code:
private function sendPresupMail(){
$filename = ($_FILES['file_selected']['name']);
...
...
}
The code there is irrelevant, the issue is that $filename is not receiving anything because $_FILES it's empty (I checked it with a var_dump, and it's empty). So I can not upload the file, what should I do?
SOLVED
Here is the solution:
Actually it was a lot simplier than I thought. First, I create an iframe, so now all the form, javascript, ajax, etc. is hapenning inside the iframe. So it seems like the page is not refreshing, because the iframe is doing it.
Thanks all for your answers anyway!
You can't do it with pure Ajax/jQuery, but you can do it in combination with the JavaScript FormData object which is supported in all latest versions of the major browsers.
A really simple jQuery example can be found here: https://coderwall.com/p/p-n7eq
A more detailed, yet pure JavaScript, can be found here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects?redirectlocale=en-US&redirectslug=Web%2FAPI%2FFormData%2FUsing_FormData_Objects
The $_POST variable on the page you are posting to is populated from the data you are submitting in the $.ajax call. That data has no file inputs, and I'm not sure it can. Take a look around for some handy plugins.
This recommends using the jQuery Form Plugin: jQuery AJAX post with fileupload
I've personally used Uploadify previously: http://www.uploadify.com/
Or manually do it: http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
Check if $_POST is also empty. $_POST and $_FILES tend to be empty when the file uploaded exceeds upload_max_filesize or post_max_size

is there size limitation for jquery-ajax form submission

I want to submit a form without loading a new php page. My form contains a file upload and textarea fields. Basically the data can like blog i.e large data size has to be submitted
I was going through some tutorial on jquery-ajax form submission
none of the tutorial show how to upload a file. can anyone help me with this and
since get method is used, is there a limitation on the size of data that can be submitted with jquery-ajax. If yes how should i handle it?
You can use an iframe so you don't have to refresh the current page.
Many people go straight to plugins. But you can do this yourself pretty easily, and with all the functionality of an AJAX request.
Make a form submit to a hidden iframe that has a load event handler attached to it so when the form is submitted, you have a callback function that actually includes the server response (the HTML of the iframe after it loads).
Example:
<form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" >
<input type="file" name="file" />
<input type="submit" />
</form>
<iframe id="workFrame" src="about:blank" style="display:none;"></iframe>
and the Javascript code is:
(function () {
$('form').on('submit', function () {
//check if the form submission is valid, if so just let it submit
//otherwise you could call `return false;` to stop the submission
});
$('#workFrame').on('load', function () {
//get the response from the server
var response = $(this).contents().find('body').html();
//you can now access the server response in the `response` variable
//this is the same as the success callback for a jQuery AJAX request
});
});
As you know, limits are set not browsers.
And according to many well-known directives, for example in Apache This paragraph defines the parameter LimitRequestBody. This parameter can take values ​​from 0 bytes to 2 GB. In PHP, there is also a directive called post_max_size. Specifies the size of a POST request.

Drupal 7 file upload (without hook_form)

Here is a conundrum that's had me stumped for the past few days. I am using a modal form in Drupal 7, so working outside of the hook_form system, trying to upload an image. The form is submitted through an ajax post, which prevents me from submitting the file along with the post. what I've done is in the ajax callback, create a new form element with the file input and then trigger a submit, posting to my module-defined page.
Original input element:
<input type="file" id="chooseImage" name"someImage" class="form-file">
js triggering submit:
$.ajax({
type:'POST',
url:$('#originalForm').attr('action'),
data: data,
success: function(response) {
if (response.success) {
$('<form id="imageForm" method="POST" action="upload/image/'+response.data.nid+'"></form>').appendTo($('#imageSubmit'));
$('#chooseImage').appendTo($('#imageForm'));
console.log($('#imageForm'));
$('#imageForm').submit(function(e){
console.log(e);
alert('freeze! hammertime...');
});
//This should post the file but it isn't...
$('#imageForm').trigger('submit');
}
},
dataType:'json'
});
The submit event shows the file properties just fine. However, on the backend, where my page callbacks end...
function myModule_image_upload($param){
error_log('number of files = '.sizeof($_FILES));
}
I am showing no files posted. I am guessing that the browser is removing the file data in the post after .submit() runs and if that is the case, I'm probably powerless to do anything about it, so I'll have to implement a separate menu within the hook system for image uploads.
Also, whatever it is that this is really doing, it seems to permanently break watchdog, forcing me to re-import a fresh dump.
Try this:
$('<form id="imageForm" enctype="multipart/form-data" method="POST" action="upload/image/'+response.data.nid+'"></form>').appendTo($('#imageSubmit'));
So you forgot to set the enctype.
Another error:
<input type="file" id="chooseImage" name"someImage" class="form-file">
Should be
<input type="file" id="chooseImage" name="someImage" class="form-file"/>

adding tow events

i have an form which will send some data to an php file , then return some results as example:
<form action"<?php $_SERVER['PHP_SELF']?>" method="post" id="data">
<input type"text" name="first_name"/>
<input type="text" name="last_name"/>
</form>
then in javascript i want catch clcik event in submit form as example :
$("#data").submit(function(){
some code .....
});
which that will prevent the default action for submitting inputs form to the php file , the question is can i send data of a form for php file and same time catch event for the same form ?
NOTE the returned data from php file will be needed by another php
function
To prevent the default behavior of form submit(Which is Page reload) you need to use event.preventDefault() like this
$("#data").submit(function(event){
event.preventDefault();
//some code .....
});
And to post the form data into php without refreshing page you need to use any of the jQuery's available ajax methods like .post() (Which will send form values using HTTP POST Method) like
$("#data").submit(function(event){
event.preventDefault();// prevent page reload
// Now post the form using Ajax
// $(this).serialize() will return an array of all form fields as
// name value pair
$.post('some_script.php',$(this).serialize(),function(data){
// Just to check if everything is working well
console.log('Form Submitted Successfully.');
// do whatever you want with the data
});
});
If your php script returns the data in json format the you can either set the content-Type header using php or force jQuery to treat the return data as JSON by specifying the dataType as JSON in the 4th parameter like
$.post('some_script.php',$(this).serialize(),function(data){
// Just to check if everything is working well
console.log('Form Submitted Successfully.');
// do whatever you want with the data
},'json');
$("#data").submit(function(e){
e.preventDefault();
$.post("<?php echo $_SERVER['PHP_SELF'] ?>",$(this).serialize(),function(r){ //Do Some Action });
});

Categories