PHP file-upload using jquery post - php

Let me know if anyone know what is the issue with this code.
Basically i want to upload a file using jQuery
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').submit(function(event) {
event.preventDefault();
$.post('post.php',function(data){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<form id="form1">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
and my php 'post.php'
<?php
echo $file['tmp_name'];
?>
Uploaded File name is not returned back. Issue is i couldn't access the uploaded file.
Thanks in advance!
Shiv

Basically i want to upload a file using jQuery
You cannot upload files using AJAX. You could use the jquery.form plugin which uses a hidden iframe:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').ajaxForm(function(data) {
$('#result').html(data);
});
});
</script>
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
Also notice the enctype="multipart/form-data" on the form.
Another possibility is to use the HTML5 File API which allows you to achieve that assuming the client browser supports it.

It's not possible to upload files with jQuery $.post, neverthless, with the file API and XMLHttpRequest, it's perfectly possible to upload a file in AJAX, and you can even know how much data have been uploaded yet…
$('input').change(function()
{
var fileInput = document.querySelector('#file');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/');
xhr.upload.onprogress = function(e)
{
/*
* values that indicate the progression
* e.loaded
* e.total
*/
};
xhr.onload = function()
{
alert('upload complete');
};
// upload success
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
// if your server sends a message on upload sucess,
// get it with xhr.responseText
alert(xhr.responseText);
}
var form = new FormData();
form.append('title', this.files[0].name);
form.append('pict', fileInput.files[0]);
xhr.send(form);
}

No no no, you should use a jQuery form plugin for async uploading files. You can't upload file with jQuery $.post method. The file will be uploaded with hidden iframe
Another way is to use HTML5 uploading with FileAPI/BlobApi

Your upload.php has some error.
you should change your this part.
echo $file['tmp_name'];
to:-
echo $_FILES['file']['tmp_name'];

Try uploading with an iframe because you can't send a file with $.post method.

You could also try jquery uploadify - http://www.uploadify.com/

Related

how to read FormData object in php

Hello everyone I am posting a sample code in which I am uploading a file using Ajax JQuery. All thing works fine but I want to read the file content in my php code. So what is the syntax to read it?
<?php
?>
<!--================================html==================================================-->
<html>
<head>
<title>AJAX UPLOAD</title>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#Button_').click(function(){
alert("hi");
var name= document.getElementById('File_');
var alpha=name.files[0];
console.log(alpha.name);
var data= new FormData();
data.append('file',alpha);
$.ajax({
url:'process.php',
data:data,
processData:false,
contentType:false,
type:'POST',
success:function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<input type="file" name="File" id="File_"/>
<input type="button" name="Button" id="Button_" value="UPLOAD">
</body>
</html>
Now I do not know how to read the file data sent via Ajax. So please let me know the code
The first argument you pass to FormData.append() is the name of the form element that is passed to the server. So data.append('file', alpha) in your case is equivalent to <input type="file" name="file"> - you passed 'file' to append() so 'file' is your input name.
You should find your stuff in $_POST['file'] and $_FILES['file']. Next time try var_dump($_POST); after submit to see the array. :)
Learn about file uploads in php here: http://php.net/manual/en/features.file-upload.php

Why can't a submit button send to PHP and jQuery at the same time?

I have this code.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<?
if (isset($_POST['submit2'])){
echo $_POST['text2'];
}
?>
<script>
$('#form').submit(function(e) {
$('#loading').show();
return false;
});
</script>
</body>
</html>
I want to store in my db the value written in the textbox using PHP, and while it's being saved, I want to show a gif using jQuery, once the page is loaded, this gif should be removed.
Then, If I don't comment nothing, gif appears when submit button is submitted but echo fails.
If I comment the jQuery script, PHP echoes the vale written.
If I comment the PHP script, gif is shown but no echo of course...
How could I do what i'm asking. I know that my full script does until only showing the gif, but this without this I can't continue.
You can achieve your desired behaviour, but you need to do it by submitting an AJAX request to the server and then handling the return value. So basically you'd add this ajax request to the click or submit event of the form, and handle the behaviour and request via javascript.
Perhaps something like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action = "formSubmitHandler.php" method = "POST" id = "form">
<img src = "circle.gif" id="loading" style="display:none; "/>
<input type="text" name = "text2">
<input type="submit" name="submit2" value="Send">
</form>
<script>
$(document).ready(function(){
$('#form').submit(function(){
// Show the loading icon before the processing begins
$('#loading').show();
// Send the query/form details to the server
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
success: function(results) {
// Now that the processing has finished, you
// can hide the loading icon
$('#loading').hide();
// perhaps display some other message etc
}
})
return false;
});
});
</script>
</body>
</html>

php form javascript onSubmit won't work

Once again a question...it's almost driving me crazy for hrs :-/
My problem:
I have an upload form on my website and the upload works fine. But I want to give the user a feedback while uploading, cuz it can take a few seconds depending on the file size.
I thought about showing a gif animated progress bar in a div and show it with javascript. I tried it, but it just won't show up when I'm hitting the submit button...and when I'm adding onSubmit=".... return false;" the upload won't work anymore...
here is my code:
in the head:
<script type="text/javascript">
function showHide() {
var div = document.getElementById('progressBar');
if (div.style.display == 'none') {
div.style.display = 'block';
}
else {
div.style.display = 'none';
}
}
</script>
body:
<div id="progressBar" style="display:none;height:40px;width:250px;margin:0px auto;">
<img src="img/progressbar.gif" alt="Progress Bar">
</div>
<form name="photo" id="upload_big" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" onsubmit="showHide();">
<input class="linkinput" type="file" name="image" size="20"/>
<input type="submit" name="upload" id="uploadbutton" value="Upload image"/>
I would appreciate any help...and since I'm a rookie -> please help me to get better instead of judging ;-)
Thanks out there!
It's because when the submit event has triggered, the browser already sent the form and will go to another page.
Use jQuery:
$(function() {
$('#upload_big').submit(function() {
showHide();
});
});
Sometimes, the form submission prohibits you from casting anymore JavaScript functionality on the page. To be on the safe side, you should also base functionality not on the form submission event, but on the <input type="submit"> click:
$(function() {
$('input#uploadbutton').click(function(e) {
showHide();
e.preventDefault();
});
});

PHP file upload with iframe - announce start and end of upload

so I have a PHP iframe (ajax) file uploader. I would like to display a loading message when submit is clicked (easy on click event) and then once the file is uploaded, so when the iframe is loaded with the PHP response, vanish (jquery fadeOut) and an alert box pop up saying the file is uploaded. what would be the easiest way to go about this?
You can attach an event handler to load on the iframe and put your fade out logic in there.
Edit 2: Some sample code (changed from ready to load)
<iframe name="process"></iframe>
<form method="post" action="upload.php" target="process" enctype="multipart/form-data" onsubmit="Upload.start()">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
<script>
var Upload = function() {
$(function() {
$('iframe[name=process]').load(function() {
// finished uploading file
$('.loading-div').hide('slow', function() {
alert('Your file has been successfully uploaded.');
});
});
});
return {
start: function() {
$('.loading-div').show();
}
}
}();
</script>

Inserting upload script into existing form page does not process upload?

I have a file upload script which works great when opened from the calling page via window.open(). However, I'm trying to avoid the popup window and load the script into the calling page itself (via jQuery.load()).
However, although everything appears to work fine, the file does not actually get transferred. The calling page is itself a form. Could that cause the problem?
<form id="myParentPage">
<div id="myUploadPlaceholder"></div>
<input type="button" id="loadScript" value="Test" />
<script type="text/javascript">
$(document).ready(function()
{
$('#loadScript').click(function() {
$('#myUploadPlaceholder').load('myUploadScript.php?action=test' );
});
});
</script>
</form>
Try using a hidden iframe instead:
<iframe id="myUploadPlaceholder" src="_blank"></iframe>
<input type="button" id="loadScript" value="Test" />
<script type="text/javascript">
$(document).ready(function()
{
$('#loadScript').click(function() {
$('#myUploadPlaceholder').attr('src','myUploadScript.php?action=test');
});
});
</script>

Categories