Php - upload file with ajax - php

my 2form.php :
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript">
function test()
{
url = '2form.php';
var ajax = new Ajax(url, {
method: 'post',
onComplete: function(response) {
document.getElementById('error_upload_logo').innerHTML = response;
}
});
ajax.request();
}
</script>
<?php
if($_FILES)
{
echo "<div>";
foreach($_FILES['name'] as $v)
{
echo $v."<br/>";
}
echo "</div>";
}
else
{ ?>
<form action='' id='form1' name="form1" method="post" enctype="multipart/form-data">
<input type="file" name="name"/>
<input type="submit" name="submit" onclick='test(); return false;'/>
</form>
<?php
}
?>
<div id="error_upload_logo"></div>
if run code with out javascript , it 2form.php like simple php page, and
we can see information of $_FILES that was printed to scrreen
But if i have run with javascript by test() function ,
i don't get information in $_FILES ?
How to get $_FILES ? when click button run with javascript ?
i want to upload with ajax

You can't do file uploads using AJAX because you won't have access to the local file.
The most common workaround is what the JQuery Form plugin does, creating a temporary iframe and doing a normal form submit into it.
The other alternative is using a Flash-based uploader like SWFUpload or Uploadify.

Related

HTML prevent from redirect upload php

I need to prevent the page redirected to the upload php when click upload button.
How can I do this in below code.
<form id="myForm" action="http://example/DB_1/AccessWeb/file_upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
</form>
<button onclick="myFunction()"> Upload
</button>
<script>
function myFunction(){
document.getElementById("myForm").submit();
}
</script>
A very basic, quickly written example of how to send a file - using ajax to the same page so that the user doesn't get redirected. This is plain vanilla javascript rather than jQuery.
The callback function can do more than print the response - it could, for instance, be used to update the DOM with new content based upon the success/failure of the upload.
<?php
$field='fileToUpload';
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
$obj=(object)$_FILES[ $field ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
if( $error==UPLOAD_ERR_OK ){
/*
This is where you would process the uploaded file
with various tests to ensure the file is OK before
saving to disk.
What you send back to the user is up to you - it could
be json,text,html etc etc but here the ajax callback
function simply receives the name of the file chosen.
*/
echo $name;
} else {
echo "bad foo!";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>File Upload - using ajax</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var bttn=document.getElementById('bttn');
bttn.onclick=function(e){
/* Assign a new FormData object using the buttons parent ( the form ) as the argument */
var data=new FormData( e.target.parentNode );
var xhr=new XMLHttpRequest();
xhr.onload=function(e){
document.getElementById('status').innerHTML=this.response;
}
xhr.onerror=function(e){
alert(e);
}
xhr.open('POST',location.href,true);
xhr.send(data);
};
},false);
</script>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
Select image to upload:
<input type='file' name='fileToUpload'>
<input type='button' id='bttn' value='Upload' />
</form><div id='status'></div>
</body>
</html>
Using JQuery AJAX methods will allow you to send and receive information to a specified url without the need to refresh your page.
You will need to include the JQuery library in your HTML page aswell. You can either download it and put it in your project folder or include an online library here, like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
So your form will now look like this:
<form id="myForm" method="post" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
<input type="submit">
</form>
Then you can use this code to simply upload your image to your file upload page (tested and working for myself):
<script>
$(document).ready(function ()
{
$("#myForm").submit(function (e)
{
//Stops submit button from refreshing page.
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response)
{
alert('success');
},
error: function ()
{
alert('failure');
}
});
});
});
</script>
use AJAX With jQuery
$("#myForm").submit(function()
{
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(response) {
//Handle the response here
});
return false;
});

Passing data using Jquery Post method to the same page

I'm a newbie to Jquery , my question is simple , I'm trying to pass data using Jquery Post method, I have read a lot , but I can't figure it out:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="TestAd" id="TestAd">
<iframe data-aa='58593' src='https://ad.a-ads.com/58593?size=468x60' scrolling='no' style='width:468px; height:60px; border:0px; padding:0;overflow:hidden' allowtransparency='true' frameborder='0'></iframe>
</div>
<button>Send request</button>
<br>
<?php
if(!empty($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var height = $('.TestAd').height();
$("button").click(function()
{
if (height==0)
{
$.post("", {block:true});
}
}
</script>
</body>
</html>
The script is a simple AdBlocker checker, thanks for your help
<form method="post">
<input type="hidden" value="true" name="block">
<input type="submit" value="Send request">
</form>
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
if you want to redirect it to the same page why dont you use simple form tag to pass the block value.By default it will redirect it on the same page
Change your PHP to this:
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
And Change your jQuery to this:
<script>
var height = $('.TestAd').height();
$("button").click(function () {
if (height == 0) {
$.post("somepage.php",{block: true}, function (data) {
// data is the response
// do something with it here
alert(data);
});
}
}
</script>
Here are the docs for $.post(), essentially, the way you had it, ignores the response. You have to pass the anonymous function (function (data) {}) callback as the 3rd argument to be able to work with the response.
From the docs:
Examples:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post( "test.php", { name: "John", time: "2pm" } );

Run jQuery function via php on form submit

I am using a form to allow file download and to store the number of downloads but now I can't seem to find a way to fadeIn a subscribe div (#cover) on form success..
This is my form:
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" name="free-download" id="free-download">
<button class="download" type="submit" name="clicks" onclick="window.open('download/imagins_._ro_free_files_format_icons.rar')">download (<span class="small"><?php echo getClickCount(); ?> times</span>)</button>
</form>
Is there a jquery way of doing this?
This is what I tried:
$("#free-download").bind('ajax:complete', function() {
$('#cover').fadeIn(600);
$('body').addClass('hidescroll');
});
Update
By changing the form action to <?php echo $_SERVER['PHP_SELF']; ?>
and adding the following (below) I managed to add an echo to the page
on form success, but how do I have the #cover div fadeIn?
<?php
if(isset($_POST['clicks']))
{
echo "<p class='section-desc'>You just downloaded it</p>";
}
?>
Working solution
Use php to echo a script tag containing whatever you want to achieve
on submit success (in my case, a div fadeIn).
<?php
if(isset($_POST['clicks']))
{
echo '
<script type="text/javascript">
$(function() {
$( "#cover").fadeIn();
});
</script>';
}
?>

PHP file-upload using jquery post

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/

submit form using Jquery Ajax Form Plugin and php?

this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>

Categories