Send file input to php with ajax - javascript

I want to send a file from an input to a php script, using ajax.
Here is what I've done so far:
HTML
<div id="inserting">
<button id="inserting_btn">Upload</button>
<input type="file" id="inserting_file"/>
</div>
JS
$('#inserting_btn').click(function(){
var file = $('#inserting_file').val();
$.ajax({
method: 'POST',
url: 'input_text/import.php',
data: 'file='+file,
success: function(data){
alert(data);
}
});
});
PHP file import.php
if ($_FILES['file']['tmp_name'] ){
echo 'yes';
}
else {
echo 'no';
}
(Sorry for my english.)

data: {file: file}
try replacing your data line with this
and in php
$file = $_POST['file'];

Try to change this in your code :
$('#inserting_btn').click(function(){
var file_rec = $('#inserting_file').prop("files")[0]; // get the file
var form_data = new FormData();
form_data.append('file', file_rec);
$.ajax({
method: 'POST',
url: 'input_text/import.php',
data: form_data,
success: function(data){
alert(data);
}
});
});
PHP file import.php
if ($_FILES['file']){
echo 'yes';
}
else {
echo 'no';
}

Related

How to get POST data using Jquery AJAX

I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>

$.ajax not uploading files using data: object array method

Ive searched on Stack overflow all over the place and could not find a solution or a post that is close to my problem.
So if this has been posted before I do apologies.
I am posting some information using a different method rather than posting a form which I will explain after I show you the code :)
Jquery:
$("#submit-add-cpos").on('click',function(){
var checkHowManyInstallments = $('#installment-ammount').val();
var checkCpoNumber = $('#addcponumber').val();
var checkCpoTotalPrice = $('#addcpoprice').val();
var checkCpoContactName = $('#addcpocontactname').val();
var form_data = new FormData();
form_data.append("type", 'addcpo');
form_data.append("quoteid", '<?php echo $_GET['id']; ?>');
form_data.append("installmentamount", checkHowManyInstallments);
form_data.append("cponumber", checkCpoNumber);
form_data.append("costcode", '<?php echo $quotecostcode; ?>');
form_data.append("cpocontactname", checkCpoContactName);
form_data.append("cpotitle", '<?php echo $quotetitle; ?>');
var checkDynamicValues = '';
var checkDynamicValue1 = '';
var checkDynamicValue2 = '';
var checkmakename1 = '';
var checkmakename2 = '';
if(checkHowManyInstallments != 'undefined' && checkHowManyInstallments != '' && checkHowManyInstallments != 0){
for(var makingi = 1; makingi <= checkHowManyInstallments; makingi++){
checkDynamicValue1 = $('#cpo-adddate-' + makingi).val();
checkDynamicValue2 = $('#cpo-addprice-' + makingi).val();
form_data.append('cposadddate' + makingi, checkDynamicValue1);
form_data.append('cposaddvalue' + makingi, checkDynamicValue2);
}
}
$.ajax({
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
$('body').html(data);
}
});
});
So from this script I get all the fields from within the form, including some dynamic ones.
The reason why I am doing it like this instead of the easier way of:
$("#formname").on('submit',function(){
$.ajax({
url: "xxxxxxxxxx/xxxxx/xxxx/xxxx.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
});
Is because for some reason it will not find the posted information no matter what I tried, so the only way I could do it is to find each id and get the value from it.
Now the issue is, uploading a file, you can not simply upload a file this way because nothing is posted.
How would I go about uploading a file if not posting a form?
Thanks
The reason why it was not posting the file is simply because I did not give it a file to post...
18 hours straight of work has not agreed with me here.
Basically I need to add the following code
var checkCpoFiles = $("#addcpofile").prop("files")[0];
form_data.append("cpofile", checkCpoFiles);
Now all works
:)
Please go through this page Ajax Upload image
Here's sample code, it might help
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form enctype="multipart/form-data" action="uploadfile.php" method="POST" id="imageUploadForm">
<input type="file" name="upload" />
<input type="submit"/>
</form>
</body>
<script>
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
</script>
uploadfile.php
<?php
if(move_uploaded_file($_FILES['upload']['tmp_name'],$_FILES['upload']['name'])) {
echo "File uploaded successfully";
} else {
echo "Unable to upload the file";
}
?>
Hope it helps! All the best!

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});

Jquery post both file and data with one ajax call

Hi I have a wordpress php class that receives my ajax and works good.
Now i have to upload a file in the same POST request i use to pass parameters to the PHP class ( i have a switch in the class that sends me to the proper function based on the parameters in the POST data ).
this is the code:
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <?php echo get_current_user_id(); ?>;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var data = {
'action': 'romme_call',
'whatever': 1234,
'userID': userID,
'function_call': 'upload_profile_photo',
**'form_data' : formData**
};
console.log(data);
jQuery.post(ajaxurl, data, function(response) {
console.log("done");
console.log(data);
});
this code will of course return a "Uncaught TypeError: Illegal invocation"
because it does not accept formData as parameter in data.
how can i handle this?
It returns Illegal invocation because jQuery is trying to parse the form data with $.param.
When submitting files with jQuery's ajax processing must be turned off
$('#imageUploadForm').on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <? php echo get_current_user_id(); ?> ;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
formData.append('action', 'romme_call');
formData.append('whatever', '1234');
formData.append('userID', userID);
formData.append('function_call', 'upload_profile_photo');
$.ajax({
url : ajaxurl,
type : 'POST',
data : formData,
contentType: false,
processData: false
}).done(function(response) {
console.log("done");
console.log(data);
});
});

jQuery AJAX file upload PHP

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>

Categories

Resources