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"/>
Related
I am doing a small php project. In this I have one page, which gets values from MySql and display it in HTML tables. Now there is generate pdf button,which generates PDF using MPDF in another php script. I need to send HTML table source code to the page containing php script to convert it into a pdf. I have used the below code to do this.
var html= $("#tblExport").html();
window.open('pdf.php?html='+html, '_blank', 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,fullscreen=yes,status=no');
Problem of above code is that, it is using GET and hence cannot send large string values to other php file.
I have tried to do this post using below code.
$(document).ready(function(){
$("#btnExportpdf").click(function(){
var html= $("#tblExport").html();
$.ajax({
type: "POST", // Methode POST or GET
url: "pdf.php", // PHP file to processing the data
data: { "html": html } // post variables that will handetover to php
})
.done(function( msg ) { // response
console.log(msg) // data retuned from php
});
});
});
Now I am stuck here. I am able to POST parameters, but how to open the php file,to which parameters are posted in a new window.
So the issue is that I want to open a new window with PDF of HTML table, on click of generate PDF button.
Please help me out. Thanks
You may need to use a form or JS.
Here is the form method.
http://www.w3schools.com/TAgs/att_form_target.asp
<form id="pdf_form" action="pdf.php" method="post" target="_blank">
<input id="pdf_html" type="hidden" name="html" value="" />
<input type="submit" value="Get PDF">
</form>
jQuery - you still need the form above, but the submit button may be hidden or removed.
$("#btnExportpdf").click(function(){
var html= $("#tblExport").html();
$("#pdf_html").val(html);
$("#pdf_form").submit();
});
I have a bit of a problem with my website. I have phpbb integrated into my website and a login form on the homepage. This form needs to execute two different actions. It first needs to run the ucp.php (to log into phpbb) and also the login.php (to hide the form and add control panel on home screen). They both work by themselves, I just need a way to have them together when a user logs in. i have researched this for a while and can't find a solution. Thanks in advances, Josh
I need to combine this
<form action="./forums/ucp.php?mode=login" method="post" enctype="multipart/form-data">
with this
<form action="login.php" method="post" enctype="multipart/form-data">
I think you have a serious design issue in your code if you have to "merge" stuff like that, but in any case:
Just create a new file ie. post_handler.php and toss this code in it:
<?php
include('forums/upc.php');
include('login.php');
?>
Place it in the same directory as login.php.
Then adjust your form to point to post_handler.php?mode=login.
Ofcourse merging files like that could result in crazy unexpected results..
Another option, though more complex, would be to use the login.php as your action and do a curl request to forums/ucp.php inside it. (search for Curl on php.net documentation)
Unfortunately I can not give more suggestions, because what you are trying to do is probably more complex then something that can easily be answered here.
Well you can try trick with ajax. Here is an example that should work with jquery:
Im not sure if preventDefaut() wont make us a problem here and we still be allowed to use .submit() on it. If it wont work. Try to put whole thing into function, remove preventDefault and bind this function into submit button.
<form id="form_id" action="login.php" method="post" enctype="multipart/form-data">
User name: <inputy type="text" id="username" name="username" />
</form>
<script type="text/javascript">
$(function() {
//we prevent normal form submit
$('#form_id').preventDefault();
var data = {} ;
//here u build data u want send by taking it from form field by field
//example
data['username'] = $('#username');
//and you send this data via ajax to your upc script
$.ajax({
type: "POST",
url: '/forums/ucp.php?mode=login',
data: data,
//in case of succes we send form normal way
success: function( xhr ) { $('#form_id').submit(); },
dataType: String
});
});
<script>
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
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/
I am attempting to submit a form via jQuery. My form contains fields and a file that must be uploaded. It is of type ENCTYPE="multipart/form-data".
I can receive all my field values using: post = $('#myForm').serialize();
But how do I receive the $_FILES array? I need this to process the uploaded file.
Is this possible using jQuery, and if so how? Or do I need to use a special upload plugin for jQuery?
jquery form is the best way to do it,
you can add it to any normal form,
<form method="post" action="URL">
<input type="file" name="file">
<input type="text" name"text">
<input type="submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
$(form).ajaxForm();
})
</script>
will work as expected, but with ajax.
http://malsup.com/jquery/form/#code-samples
You cannot upload files through javascript.
Check out this related question:
Is it possible to use Ajax to do file upload?
Essentially, the two most popular ways of "faking" AJAX for file uploads is using a Flash plugin such as SWFUpload or submitting the form to a hidden iframe that processes the request.
Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent
Use FormData
<form>
<label for="imageToSend">Cargar imagen a la galeria</label>
<input type="file" name="imageToSend" id="imageToSend" value="Cargar imagen" />
</form>
<script>
$('#imageToSend').on('change',function(event){
var dialog = $('#dialog');
var Data = new FormData();
Data.append('imageToSend',$('#imageToSend')[0].files);
$(this).val('');//Clear input file
$.ajax({
url: "/upload",
data: Data,
processData: false,
contentType: false,
type:'POST',
success: function(data){
if(data.success){
//success handler
}else if(!data.success){
//error backend handler
}
},
error: function(data){
//error handler Ej:404 status
}
})
});
</script>
If you can control the environment, like, say, you're writing an admin app for an intranet in which you recommend the browser, then real AJAX file uploads are possible with Firefox 3 and above. In all other cases, the iframe workaround or a Flash based uploader is the way to go.
It's possible, but not working in Google Chrome )
Look!
...
<form method='post' enctype='multipart/form-data'>
<input type="file" id="imf" name="imf"/>
<input type="button" id="Save"/>
</form>
...
$("#Save").live("click", function(){
var photo = document.getElementById("imf");
var file = photo.files[0];
$.post('/user/saveNewPhoto', {'imf':file.getAsDataURL(), fname:file.fileName }, function( data ){
alert ( data );
});
});
upload side script
need decode base64 ) and that is all
but i don't test this script on big size file