My form uses javascript alerts to communicate with the user as this is the preferred method in the company I work for (as opposed to constant redirects to and from the php handler file).
Because of this, I pass all my form data through some simple validation in jquery and send it on to the php handler via ajax. Here's a basic look at how I'm doing it...
var first_name = $(sender + ' #first_name');
var email = $(sender + ' #email');
var tel = $(sender + ' #telephone');
var comments = $(sender + ' #comments');
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: { first_name: first_name.val(),
email: email.val(),
telephone: tel.val(),
comments: comments.val(),
success: function clearFields() {
first_name.val('');
email.val('');
tel.val('');
comments.val('');
alert('Thank you. We will contact you as soon as possible.');
}
}
});
Having added an file input field to one such form as follows, I'm having trouble with the upload. While the email sends correctly, I don't think the ajax is sending any usable data for the upload on to the php file
<input type="file" name="upload" id="upload" />
<script>
var upload = $("#upload");
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: { first_name: first_name.val(),
email: email.val(),
telephone: tel.val(),
upload: upload.val(),
comments: comments.val(),
success: function clearFields() {
first_name.val('');
email.val('');
tel.val('');
upload.val('');
comments.val('');
alert('Thank you. We will contact you as soon as possible.');
}
}
});
</script>
I've found a number of options for this, but all the ones I've looked at such as this seem "hackish" to me.
Is there a simpler way to do this?
Ajax does not support file upload operation. But there are many plugins which make use of iframes to upload files asynchronously. You can read more about this technique here.
Few jQuery plugins which supports form uploads are
1. jQuery form
2. jQuery-File-Upload
There are a lot of question answers regarding this in many Q&A sites, like this one.
Another solution using html 5 is discussed here which uses FormData.
You have to do this through an IFrame
So you create a hidden iframe
<iframe id="upload_target" name="upload_target" style="display: none;" src="#"></iframe>
<!-- note the src="#" -->
Then you create a form with some button and all fields you wish to have
<form action="path/to/uploadscript.php" method="POST" enctype="multipart/form-data" target="upload_target">
<!--target will tell the browser to run it in the iFrame with name="upload_target" -->
then in uploadscript.php you can use all form values as if they are regular $_POST values:
<?php upload_file($_FILES['file'], $_POST['name'], $_POST['whatever']); ?>
This almost feels the same as using AJAX.
Related
I use the following code successfully (with different IDs, etc.) to preview a banner image in a div after PHP validates the upload, using AJAX. This works just fine. No issues.
I am having a problem doing the same with a video. The code below works well, except the video doesn't preview. Just echos back the alt tag value. I am passing the uploaded video ID to a hidden input for some back end PHP validation via ajax function. After validation, the video is moved to the folder I want it to move to without a problem. I also echo back an error if the video doesn't meet requirements. This is all good. The video just doesn't show on the page. Any help is appreciated.
<div>Upload Video</div>
<div><input type="file" id="banner-video"></div>
<div id="loading"></div>
<div class="padding-top-1" id="show-video"></div>
<script>
$(document).ready(function() {
$("#banner-video").change(function() {
var data = new FormData();
data.append("file", $("#banner-video")[0].files[0]);
$.ajax({
url: "create-promotions/video-banner-promotions/create-promotion.video.process-banner-video.php",
method: "POST",
data: data,
contentType: false,
processData: false,
cache: false,
beforeSend: function() {
$("#loading").load("../loading.php");
},
success: function(data) {
$('#loading').hide()
$('#show-video').html(data); // ********** This line seems to be the problem
if ($('#show-video').find('img').length) {
bannerVideo = $('#show-video').html(data);
document.getElementById("the-banner-video").value =
bannerVideo
}
}
});
});
});
</script>
<input type="hidden" id="the-banner-video" value="">
Nevermind. After 3 days of working on it, it was just using the wrong tag on my back end php echo. The code works. Feel free to use it if you ever come across it. Let me know if you would like the other pieces.
I was wondering how I could go about sending a .csv file from a file input container in HTML to another .php file in ajax.
Here's my code:
$(document).ready(function () {
$(".Rsubmit").click(function () {
?????What would I declare to contain the .csv file?
var checkurl = './CSVRemove/getAccountsCSV.php';
runCSVcheck(checkurl);
});
});
function runCSVcheck(checkurl)
{
$.ajax({
type: "POST",
//dataType: "json",
url: checkurl,
data:
{
???? what would I put here?
},
success: function(response) {
code....
});
}
HTML:
Input boxes.....
<span>Enter .csv File: </span><input type="file" name="file" value="" />
Please let me know if there is a solution!
David
If you're planning on sending a file upload via Ajax, I suggest using a jQuery form plugin that support file uploads.
There are a number of them available, but I've had good success with this one: http://www.malsup.com/jquery/form/
It allows you to post a form via Ajax, even if the form includes file upload fields. PHP will receive the form post exactly as it would have done normally if it had been posted via a regular form submit.
Alternatively, you could use HTML5's file API, but only if you don't need to support older browsers like IE8. The jQuery form plugin is probably the safer way to go for now.
hope that helps.
I desire to upload files asynchronous when the user select a file in a input file, with $.ajax. But the php that recive the call return index undefined.
The jquery code is the next:
$("#urlimatge").change(function(){
var filename = $("#urlimatge").val();
$.ajax({
type: "POST",
url: "utils/uploadtempimg.php",
enctype: 'multipart/form-data',
data: {'urlimatge' : filename },
success: function(response){
alert(response);
}
});
});
and the php that recibe the call:
$image = new gestorimatges();
$target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']);
Thanks
you cannot pass the $_FILE from AJAX to PHP.
I would suggest use a plugin
It will make your life easier :) Here is a video tutorial to help too
You might wanna use tools like uploadify for that.
You can't upload files with AJAX, but you can use an iframe so you don't have to refresh the current page.
Many people go strait to plugins but you can do this yourself pretty easily, and with all the functionality of an AJAX request.
Instead of using an AJAX function, have 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:
HTML --
<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>
JS --
$(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
});
});
I'd like to have a form that executes some php code without having to open a completely new php page. Right now, I'm familiar with "POST" so that I can execute a php file and call the variables from the HTML form using $_POST[variable] but, it takes time to open a new page, and I want to have a form that does the action right then and there.
For example, can someone write html code that creates a text box and a button, and when the user presses go, it displays the text that the user entered right next to the button.
Thanks!
Here's an HTML and PHP snippet to get you started. It uses jQuery and just writes the value of textarea beneath the submit button using AJAX.
HTML Snippet [file=so.html]
<!DOCTYPE html>
<html><head><title>SO Example</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js">
</script>
</head>
<body>
<form id="frm" name="frm">
<textarea id="txt" name="txt" rows="4" cols="40">
</textarea><br />
<input type="submit"><br />
<span id="result"></span>
</form>
<script type="text/javascript">
$('#frm').submit(function(e){
e.preventDefault();
$.ajax({
url:"/so.php",type:"post",dataType:"html",
data:$('#frm').serialize(),
success:function(obj){
$('#result').text(obj);
}
});
});
</script>
</body>
</html>
PHP Snippet [file=so.php]
<?php
echo $_POST['txt'];
If you want to execute php code after the page is loaded without opening a new page then you should be using a technology like AJAX. PHP is a pre-processor and is meant to be run to process a page, not for functions after that.
With AJAX you can use javascript to call a webpage that's processed by PHP. Then with that returned page/data you can do your page function.
For more info on ajax check here: http://en.wikipedia.org/wiki/Ajax_(programming)
I recommend looking at jQuery as an ajax wrapper: http://api.jquery.com/jQuery.ajax/
You can find a ton of tutorials online to get you started.
I'd look into AJAX, more specifically an AJAX call using jQuery. It looks a little bit like this for a POST request:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
});
And if I filled that out, it might look like this:
$.ajax({
type: 'POST', // Method of submission: POST or GET
url: 'processor.php', // The script to send to.
data: { id: 1, name: 'John' }, // The data to give to PHP.
success: function(data) { // Do something with what PHP gives back.
console.log(data);
}
});
For more info on jQuery's AJAX functions, head here: http://api.jquery.com/category/ajax/
You're interested in jQuery.ajax(), jQuery.post(), and jQuery.get() probably.
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