jQuery and php file upload - php

I do not understand, and google does not give me the answer. I want to upload a file and the results show in the div without page relode, but I can not get it!!!!
html:
<form method="post" action="process/pic2.php" enctype="multipart/form-data" id="userpic">
<p>Izvēlies bildi: <input type="file" name="img_to_upload" /><input type="submit" name="upload" value="Augšupielādēt" /></p>
</form>
jquery:
jQuery(function(){
jQuery('#userpic').submit(function(){
jQuery.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jQuery('#userpic').attr('action'),
data: jQuery('#userpic').serialize(),
success: function(data){
if(data){
jQuery('#picinfo').html(data);
}else{
jQuery('#uerpic').fadeOut(500);
jQuery('#picinfo').html('<center><img src="img/loader.gif" /></center>');
window.location = 'index.php';
}
}
});
return false;
});
});
and my php:
if(isset($_FILES['img_to_upload']['name']) && !empty($_FILES['img_to_upload']['name'])){
echo 'Done!';
}else{
echo 'Error!';
}
all the time showing the "error" text..
P.S. Sorry for bad English.

Normally, to do a form-submission, and stay on the same page, you'll have to prevent the default form action with Javascript, something like this:
$("#userpic").submit(function(event) {
event.preventDefault();
...
});
But, uploading an image via Ajax is pretty tricky--see:
uploading files with jquery $.ajax and php

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;
});

Getting an AJAX call to return a result on the same page in a DIV

I have a simply AJAX call as a part of an image upload form. The page calls a PHP form which is supposed to then process the file upload and return a "successful" comment to the same page.
Currently, the script is working perfectly but when it returns the AJAX success string, it takes you to a new page and shows the AJAX output rather than showing it within the DIV on the same page.
To make it simpler, I've just cut out all of the PHP upload script and changed it to a simple echo output script - so I think it's a problem with the submit form page rather than the page that's called. I have jQuery included in the submission page.
Here's the submit form:
<div id="uploadFormLayer">
<form id="uploadForm" action="../uploadtesties.sparkle" method="post" enctype="multipart/form-data">
<input type="file" name="myFile">
<input type="submit" value="Upload">
<input type="hidden" name="EID" value="<? echo $ElectionID; ?>">
</form>
</div>
<div id="targetLayer"></div>
Here's the AJAX request:
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "uploadtesties.sparkle",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
The PHP page just says <?php echo "Testing output"; ?> for the moment.

Getting data from PHP page on form submit

I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)

Form submit using AJAX is not working

PHP/Ajax newbie here...I am trying to save the contents of a textarea into MySQL via Ajax. Although the data IS being saved correctly, Ajax isn't quite working. Basically, the page is "reloaded/refreshed" after the data is saved, unlike Ajax. Can you please tell me what is that I am doing wrong?
index.html:
<form action="save.php" method="post" id="source-form">
<span><input type="submit" value="Save" /></span>
<div>
<textarea id="editor" name="editor" >
</textarea>
</div>
</form>
javascript:
$(document).ready(function() {
$("#source-form").submit(function(){
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
});
save.php
<?php
// connect to the database
include('connect-db.php');
// get form data, making sure it is valid
$submit_date = date('Y-m-d H:i:s');
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
//build query
mysql_query("INSERT source SET submit_date='$submit_date',content='$content'")
or die(mysql_error());
header('Location: index.html');
?>
Any help on this is appreciated. Thank you.
EDIT:
For folks running into the same issue or something similar...here's a great solution from:
http://jquery.malsup.com/form/#getting-started
change your <form action="save.php" method="post" id="source-form">
to <form method="post" id="source-form">
remove the action you already declared your url in the ajax
remove header('Location: index.html'); since your should not redirect since your are using ajax. remember that if you are using ajax you dont need to refresh the page just let it receive a confirmation that the result was successful
Add a return false; to forum submit so that the form submit is cancelled:
$("#source-form").submit(function(){
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
return false;
});
You have to stop the default behavior of the submit button (form posting).Otherwise the form will be submitted again and you will see the page loading again. You use the preventDefault function
$("#source-form").submit(function(e){
e.preventDefault();
$.ajax({
url:"save.php",
type:"post",
data:$(this).serialize(),
success: alert('saved');
});
});
If you're only using the form for a ajax submit, I would suggest removing the form from the HTML completely and using a click event. I've stripped things down to a minimum in the HTML:
HTML
<input id="save-text" type="submit" value="Save" />
<textarea id="editor" name="editor" ></textarea>
JavaScript
$(document).ready(function() {
$("#save-text").click(function(){
$.ajax({
url:"save.php",
type:"post",
data: $("#editor").serialize(),
success: alert('saved');
});
});

Working with input type file AJAX/PHP

I have got this html/php in my index.php
if (isset($_POST['UploadMSub'])) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)) {
if ($fileP_error===0) {
if ($fileP_size<=2097152) {
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
$_SESSION['fileP']=$fileP;
$_SESSION['fileP_name']=$fileP_name;
$_SESSION['fileP_tmp']=$fileP_tmp;
$_SESSION['fileP_size']=$fileP_size;
$_SESSION['fileP_error']=$fileP_error;
$_SESSION['fileP_extension']=$fileP_extension;
$_SESSION['fileP_new_name']=$fileP_new_name;
}
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
And this ajax
$(".UploadMSub").click(function() {
var text=$(".Text").val();
var file=$("#Nameupload").val();
$.ajax({
type: "GET",
url: '../connect.php',
data: "Text=" + text+"&&file="+file,
success: function(data)
{
alert(data);
}
});
return false;
});
connect.php
if (isset($_GET['Text'])) {
$Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
$file=htmlspecialchars($_GET['file'],ENT_QUOTES);
echo $Text." ".$_SESSION['fileP_new_name'];
}
But when i submit form it returns(alerts)
"Undefine index ''fileP_new_name'"
Is there any other way of getting all information about file in my connect.php?
The problem is,
When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,
Undefine index: fileP_new_name
From your question,
Is there any other way of getting all information about file in my connect.php?
So the solution is as follows. You have to change few things in your code, such as:
Add a name attribute in your <textarea> element, like this:
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:
$(".UploadMSub").click(function(event){
event.preventDefault();
// your code
});
If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.
So your code should be like this:
HTML:
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
jQuery/AJAX:
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('form')[0]);
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data){
alert(data);
}
});
});
And on connect.php, process your form data like this:
<?php
if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
// both file and text input is submitted
$new_post = $_POST['new_post'];
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
// your code
//echo $fileP_new_name;
}
?>

Categories