send multipart form with ajax - send file and text - ajax

i need to send some data and an image file with ajax .
i know that must use multipart form and formdata but i don't know how - i googled it and i found some way for send file, but i need to send whole form.
this is my html form
<form id="formData" enctype="multipart/form-data">
<input type="file" id="uploader" name="image" accept="image/jpg, image/jpeg, image/png, image/bmp, image/raw"/>
<input type="hidden" name="action" id="action" value="receiver"/>
<input type="hidden" name="route" id="route" value="image"/>
</form>
thanks.

Hope something like this might do it for you mate... :)
html
//Include this script in head
<script src="http://malsup.github.com/jquery.form.js"></script>
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allows you to have full control over how the data is submitted
<div id='preview'></div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
<input type="file" name="photoimg" id="photoimg" />
</form>
Script File
$('#photoimg').on('change', function()
{
$("#imageform").ajaxForm({target: '#preview', //Shows the response image in the div named preview
success:function(){
},
error:function(){
}
}).submit();
});
ajaximage.php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
$tmp = $_FILES['photoimg']['tmp_name'];
$path = "uploads/";
move_uploaded_file($tmp, $path.$name) //Stores the image in the uploads folder
}
You could get the values of fields like action,route etc using $_POST inside the php file.For mare details check the below link mate.. :)
http://malsup.com/jquery/form/#ajaxForm

Related

How to use Filepond with PHP form and attach files with post

I'm using Filepond with the Laravel framework.
I need to send a file related to an article.
HTML code:
<form action="submit.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="post_id" value="2" />
<input type="file" class="filepond" name="filepond" data-max-files="1"/>
<input type="submit" value="Upload" name="submit" class="btn btn-info" />
</form>
<script>
// get a reference to the input element
const inputElement = document.querySelector('input[type="file"]');
// create a FilePond instance at the input element location
const pond = FilePond.create( inputElement, {
maxFiles: 1,
allowBrowse: false,
instantUpload: false,
});
</script>
How can I use the submit form button to download my files and get $_POST['post_id']?
Unfortunately that's not possible on most browsers because the value of a file input field cannot be set.
To work around this limitation you can:
Upload the file asynchronously (using the FilePond server.process property)
Encode the file as base64 data (using the FilePond encode plugin)
Use a DataTransfer object to set the file input value (at the moment this only works on Chrome / Firefox)
For more information on the DataTransfer solution see:
https://pqina.nl/blog/the-trouble-with-editing-and-uploading-files-in-the-browser/

Multiple file upload using prototype.js

Is there a way to upload file using pure prototype and ajax. I've searched for it on google but did't got any satisfactory result. Can anyone please help me out??
The easiest way to get an "Ajax" file upload to work is to use a keyhole iframe as the target for your form:
<form action="handler/url" enctype="multipart/form-data" target="keyhole" method="post">
<input type="file" multiple name="user_file[]" />
<input type="submit" id="upload" value="Upload">
</form>
<!-- style the following to be tiny/hidden -->
<iframe id="keyhole" src="about:blank"></iframe>
The trick with this is to show a waiting indicator, and hide it after the upload is complete.
<div id="waiting" style="display:none"></div>
<script type="text/javascript">
$('upload').observe('click', function(evt){
$('waiting').show();
});
</script>
In your file upload handler, return a text/javascript header and the following script after a successful upload:
var waiting = top.document.getElementById('waiting');
if(waiting) waiting.style.display = 'none';
Naturally, this will only work if both endpoints are on the same server, owing to Same Origin Policy.

Jquery Mobile - search input has no value on post after AJAX loaded content

I am having an issue where when a page is loaded via Ajax, I don't have a value in my search input. Here is my HTML:
<form id="searchForm" action="javascript:;" method="post">
<div>
<input type="search" name="search-mini" id="search-mini" value="" data-mini="true" />
<input type="submit" data-mini="true" value="Search" />
</div>
</form>
The reason we have an input button is because of a request from the client as they found people having scenarios where they would click "Done" on the IOS keyboard rather than "Search" which wouldn't submit the form. here is my Javascript that handles the submit:
$(document).on('submit', '#searchForm', function () {
var text = $("#search-mini").val();
text = encodeURIComponent(text);
window.location.href = "/Mobile/Browse/Text?text=" + text;
return true;
});
This all runs fine if I refresh the page so the content is not loaded via AJAX. It only fails when linking between pages and they are loaded by AJAX. Alerting out "text" has a blank value in this scenario.
I have read about using JQM initialization events such as 'PageInit' instead of DOM ready() I just need an example implementing this with my code if this is the correct approach?
Regards,
Danny

Load Dojo form from ajax call

I am trying to implement something like this.
http://app.maqetta.org/mixloginstatic/LoginWindow.html
I want the login page to load but if you click the signup button then an ajax will replace the login form with the signup form.
I have got this to work using this code
dojo.xhrGet({
// The URL of the request
url: "'.$url.'",
// The success callback with result from server
load: function(newContent) {
dojo.byId("'.$contentNode.'").innerHTML = newContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});'
the only problem is the new form just loads up as a normal form, not a dojo form. I have tried to return some script with the phaser but it doesnt do anything.
<div id="loginBox"><div class="instructionBox">Please enter your details below and click <a><strong>signup</strong>
</a> to have an activation email sent to you.</div>
<form enctype="application/x-www-form-urlencoded" class="site-form login-form" action="/user/signup" method="post"><div>
<dt id="emailaddress-label"><label for="emailaddress" class="required">Email address</label></dt>
<dd>
<input 0="Errors" id="emailaddress" name="emailaddress" value="" type="text"></dd>
<dt id="password-label"><label for="password" class="required">Password</label></dt>
<dd>
<input 0="Errors" id="password" name="password" value="" type="password"></dd>
<dt id="captcha-input-label"><label for="captcha-input" class="required">Captcha Code</label></dt>
<dd id="captcha-element">
<img width="200" height="50" alt="" src="/captcha/d7849e6f0b95cad032db35e1a853c8f6.png">
<input type="hidden" name="captcha[id]" value="d7849e6f0b95cad032db35e1a853c8f6" id="captcha-id">
<input type="text" name="captcha[input]" id="captcha-input" value="">
<p class="description">Enter the characters shown into the field.</p></dd>
<dt id="submitButton-label"> </dt><dd id="submitButton-element">
<input id="submitButton" name="submitButton" value="Signup" type="submit"></dd>
<dt id="cancelButton-label"> </dt><dd id="cancelButton-element">
<button name="cancelButton" id="cancelButton" type="button">Cancel</button></dd>
</div></form>
<script type="text/javascript">
$(document).ready(function() {
var widget = dijit.byId("signup");
if (widget) {
widget.destroyRecursive(true);
}
dojo.parser.instantiate([dojo.byId("loginBox")]);
dojo.parser.parse(dojo.byId("loginBox"));
});
</script></div>
any advice on how i can get this to load as a dojo form. by the way i am using Zend_Dojo_Form, if i run the code directly then everything works find but through ajax it doesnt work. thanks.
update
I have discovered that if I load the form in my action and run the __toString() on it it works when i load the form from ajax. It must do preparation in __toString()
Firstly; You need to run the dojo parser on html, for it to accept the data-dojo-type (fka dojoType) attributes, like so:
dojo.parser.parse( dojo.byId("'.$contentNode.'") )
This will of course only instantiate dijits where the dojo type is set to something, for instance (for html5 1.7+ syntax) <form data-dojo-type="dijit.form.Form" action="index.php"> ... <button type="submit" data-dojo-type="dijit.form.Button">Send</button> ... </form>.
So you need to change the ajax contents which is set to innerHTML, so that the parser reckognizes the form of the type dijit.form.Form. That said, I urge people into using a complete set of dijit.form.* Elements as input fields.
In regards to:
$(document).ready(function() {});
This function will never get called. The document, youre adding innerHTML to, was ready perhaps a long time a go.
About Zend in this issue:
Youre most likely rendering the above output form from a Zend_ Dojo type form. If the renderer is set as programmatic, you will see above html a script containing a registry for ID=>dojoType mappings. The behavior when inserting <script> as an innerHTML attribute value, the script is not run under most circumstances (!).
You should try something similar to this pseudo for your form controller:
if request is ajax dojoHelper set layout declarative
else dojoHelper set layout programmatic

Uploading files with MVC 3 ajax style

Maybe it's just me but I'm trying to use a jQuery dialog to capture a file the user wants to upload. It must be supported by IE9. IE9 doesn't support the FormData object which is used in many examples and 3rd party tools I have came across. So in order to make my request not refresh the whole page I have to put my upload into an iFrame? Really? I know I can get some flash uploader but flash isn't supported on our site so that's out of the question right now.
Please.. please someone tell me I'm doing this wrong and there's an easier way because I can't seem to find it.. not one that will work on IE9 at least.
Form
<form action="/ControllerName/ActionName" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
Then into an iFrame like this
<iframe src="myUrl"></iframe>
View:
#using (Html.BeginForm("FileUpload","Message",FormMethod.Post,new { enctype="multipart/form-data"})) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Message</legend>
//your html here
<input type="file" name="files"/>
</fieldset>
Controller:
[HttpPost]
public ActionResult FileUpload(FormCollection values, IEnumerable<HttpPostedFileBase> files)
{
//do what you want with form values then for files
foreach (var file in files)
{
if (file.ContentLength > 0)
{
byte[] fileData = new byte[file.ContentLength];
file.InputStream.Read(fileData, 0, file.ContentLength);
//do what you want with fileData
}
}
}
I provide multiple files upload so i use
IEnumerable<HttpPostedFileBase> files
if you want only a single file then use only
HttpPostedFileBase file
and in your view change input type to
<input type="file" name="file"/>
Simple as that.
Regards
EDITED:
Take a look at more good examples:
http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/
http://css.dzone.com/articles/implementing-html5-drag-drop
Regards

Resources