i'm a amateur programer. I'm coding upload and insert to database function with php and jquery ajax but it not work
my form
<form>
<input type="file" id='iputfile1' />
</form>
my jquery script
iputfile1 = $("#iputfile1").val();
jQuery.ajax({
type:"POST",
url:"ex.php", //goi toi file ajax.php
data:"filename"=filename+"&+"&iputfile1="
+iputfile1,
success:function(html){
jQuery("#responseDiv").show();
jQuery("#responseDiv").html(html);
}
});
my ex.php file
$iputfile1 = $_REQUEST['iputfile1'];
print_r($iputfile1)
after select file and submit my ex.php file not recivice $_file['tmp']
<input type="file" class="file">
$(".file").on("change",function(){
var file = new FormData();
file.append('file',$('.file')[0].files[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: file,
processData: false,
contentType: false,
beforeSend:function(){
$(".result").text("Loading ...");
},
success:function(data){
$(".result").html(data);
}
});
<div class="result"></div>
in upload.php
<?php
include("database.php");
$name = $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], "DESTINATION/".$name)){
// insert to data base
echo '<img src="DESTINATION/'.$name.'">';
}
?>
Related
I am using ajax to upload a file from a form. Everything works fine file is uploading, but when I click on the upload button to upload the file after upload the file page gets reloading. How do I prevent the page reloading after file upload?
HTML :
<form enctype="multipart/form-data">
<input type="file" accept=".xlsx" id="file-upload" name="file"/>
<input id="form_submit" value="Upload" type="submit" name="form_submit"/>
</form>
Jquery:
$('#form_submit').on('click', function() {
var file_data = $('#file-upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'file_upload_parser.php', // point to server-side PHP script
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
PHP:
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo "Sucess";
}
Just change the input type 'submit' to 'button'. Because the input type 'submit' does have the default behavior to submit the form. If you change the input type to 'button' and type button does not have the default behavior.
<input id="form_submit" value="Upload" type="submit" name="form_submit"/>
TO
<button id="form_submit" value="Upload" type="button" name="form_submit">Upload</button>
If you want to do this with jquery then just make some changes in jquery function and you can prevent the default behavior of the submit button like below.
$('#form_submit').on('click', function(e) {
e.preventDefault();
var file_data = $('#file-upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'file_upload_parser.php', // point to server-side PHP script
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
and you are free to use
<input id="form_submit" value="Upload" type="submit" name="form_submit"/>
Use jQuery event.preventDefault() Method.
Not like this
$("#form_submit").click(function(event){
// Your upload code here
event.preventDefault();
});
Use like this
$("#form_submit").click(function(event){
event.preventDefault();
// Your upload code here
});
Place event.preventDefault() in the top of the function to prevent the default behavior then write your code.
I have one form html then I have 2 input( input text and input file)
my problem input text cannot send post to upload php.
I using jquery ajax to post data
upload.php
<?php
$nama = $_POST['name'];
$filename = $_FILES['file']['name'];
var_dump($nama);
var_dump($filename);
form
<form method='post' action='' enctype="multipart/form-data">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter name" required />
Select file : <input type='file' name='file' id='file' class='form-control' ><br/>
<input type='button' class='btn btn-info' value='Upload' id='upload'>
</form>
<script type="text/javascript" >
$(function() {
$("#upload").click(function() {
var name = $('#name').val();
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
$.ajax({
type: "POST",
url: "upload.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: fd,
success: function(){
}
});
return false;
});
});
</script>
Just remove dataType:text. Or you can use dataType:"json" as per your requirement. Well, you can read more on this dataType here also: $.ajax - dataType
And for name parameter, you are missing to append that variable in fd variable.
So, your script should be like this:
<script type="text/javascript" >
$(function() {
$("#upload").click(function() {
var name = $('#name').val();
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
fd.append('name',name); // you were missing this, that's why $_POST['name'] was blank
$.ajax({
type: "post",
url: "upload.php",
cache: false,
contentType: false,
processData: false,
data: fd,
success: function(){
}
});
return false;
});
});
</script>
Now try by printing below code into your upload.php file:
<?php
echo $nama = $_POST['name'];
echo $filename = $_FILES['file']['name'];
?>
I have three type of inputs those are file input, text input and variable. I want to upload those inputs by sending data to PHP file by using Ajax JSON. Also I want to know how to capture these data in PHP file.
I am using HTML code without form syntax. variable data name as a val1 in JQuery code.
HTML Code:
<div class="container" id="post">
<textarea id="posttext" autocomplete="off"></textarea>
<input type="file" name="file" id="file" multiple accept=".mp4, .mov, .m4v, .MPEG-4, .gif, .jpg, .png"/>
<button type="button" id="submitpost">Submit</button>
</div>
JQuery Code:
$(document).on("click", "#submitpost", function(){
var val1 = "Some Datas";
$.ajax({
url: post.php,
type: 'POST',
data: VALUES,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
PHP Code:
<?php
if (!isset($_POST['VALUES']) && !empty($_POST['VALUES'])) {
$params = $_POST['VALUES'];
}
?>
How to get each values in PHP to Upload files and insert text and variable data to database.
Use this code:
Html:
<div class="container" id="post">
<form enctype="multipart/form-data" method="POST" id="myform">
<textarea id="posttext" name="posttext" autocomplete="off"></textarea>
<input type="file" name="file" id="file" multiple accept=".mp4, .mov, .m4v, .MPEG-4, .gif, .jpg, .png"/>
<button type="submit" name="submitpost" id="submitpost">Submit</button>
</form>
</div>
Jquery:
$(document).on("click", "#submitpost", function(e){
$("form#myform").submit();
});
$("form#myform").on('submit', function(e){
e.preventDefault();
var val1 = "Some Data";
var file = this.files[0];
var form = new FormData();
form.append('file', file);
form.append('val1', val1);
form.append('posttext', $('#posttext').val());
$.ajax({
url : "post.php",
type: "POST",
cache: false,
async: false,
contentType: false,
processData: false,
data : form,
success: function(response){
alert(response);
}
});
});
PHP Code:
<?php
if (isset($_POST) && !empty($_POST)) {
print_r($_POST);
print_r($_FILES);
}
?>
I have html form:
<form enctype="multipart/form-data" id="formUpload">
<input type="file" name="file" />
<button type="submit" id="sub">Click</button>
</form>
My script:
$(function() {
$("#sub").on("click",function () {
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
I try to upload file in upload.php, but all is wrong.
How can I get $_FILES variable?
Every time you click on submit button, your page will get refreshed and you won't see any output from this statement $("#res").html(data);. Use event.preventDefault() method to prevent your form from being submitted in the first place. So your Javascript code should be like this:
$(function() {
$("#sub").on("click",function (event){
event.preventDefault();
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
And in the backend upload.php page, you can access the uploaded file data using $_FILES, like this:
<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])){
$name = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
// ...
}
?>
I need to get the uploaded image using PHP via Ajax
My form fields are,
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="button" id="bidm" name="bidm" value="Next"/>
</form>
In ajax call I have following code :-
$.ajax({
url: './api/addspot.php',
data: $('#rent_details').serialize(),
type: 'POST',
contentType: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
Here I got only spottype value in Ajax success function .But I need to get
all form fields value.
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="submit" id="bidm" name="bidm" value="Next"/>
</form>
$(document).ready(function(){
$("#rent_details").submit(function(e){
e.preventDefault();
$.ajax({
method:'POST',
url: "./api/addspot.php",
data: new FormData( this ),
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
});
});
And get by name on your requested page. use $_FILES for upload files.
This will work.
$('#rent_details').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: './api/addspot.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}));
Need to use the FormData() for the ajax data. It took all the form variables and passed it to the ajax. Then in the ajax function, you can retrieve the file name and the temp file name and save the image file to the folder where you required to save.
You need to use the FormData();
Know that this code will not work on IE9 and lower.
This is for multiple file upload.
$(document).on('click', '#bidm', function(e) {
e.preventDefault();
var request = new FormData(this);
var my_files = $(this).closest('form').find('#fileToUpload').files;
$.each(my_files, function(j,file) {
` request.append('fileToUpload['+j+']', file);
});
$.ajax({
url: './api/addspot.php',
data: request,
dataType: "json",
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
Try this to get file field value:
$('input[type=file]').val()
This code is worked