Javascript pass input file to PHP - javascript

I don't want to upload a file using Javascript, I just want to pass by Ajax the file to a PHP file, and in the PHP make the validations I want, plus use the move_uploaded_file function. Is it possible?
$('#the_button').on("click", function(){
var image = $('#image').val() == "" ? null : $('#image').files;
$.ajax({
type: "POST",
url: "insert.php?type=image",
data: image,
enctype: 'multipart/form-data',
success: function(data) {
alert(data);
}
});
}
This returns 'undefined' for the #image.
$('#image').files[0] also returns undefined.
$('#image')[0].files returns [object FileList] -> is it correct?

try this plugin
http://blueimp.github.io/jQuery-File-Upload/
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});

You can not upload files via AJAX.
Usual way is to set the target of your form to a hidden iframe.
Something like this.
<form target="myHiddenIframe" method="post" enctype="multipart/form-data">
//your form elements here.
</form>
<iframe name="myHiddenIframe" id="myHiddenIframe" style="display: none;" />
Submit the form to achieve what you want.

Related

Getting data sent with Ajax from php?

sorry if this has been asked many times but I can't get it to work.
I'm trying to build a restful website, I have a simple form:
<form action="/my/path" method="post" id="myformid">
Name <input type="text" name="name">
<input type="submit" value="Test">
</form>
I convert the data the user inputs using Javascript and I send them to my php file using Ajax:
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
const json = JSON.stringify($("#myformid").serializeArray());
$.ajax({
type: "POST",
url: "/my/path",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And I tried reading the data on php like:
$data = json_decode(file_get_contents('php://input'), true);
$name = $data["name"];
The code works perfectly if I send a JSON in the request body using a tool like Postman, but from what I tested using Ajax the json data arrives as POST data, and I can read it using $_POST["name"], but non with the 'php://input' as I did.
How can I fix it so the JSON gets accepted even sent via Javascript?
Hi you can try like this:
First I use an id attribute for each input i dont really like to serialize stuff but thats me you can do it your way here are the files.
your index.php:
<form method="post" id="myformid">
Name :<input type="text" id="name" name="name">
<input type="submit" value="Test">
</form>
<br>
<div id="myDiv">
</div>
your javascript:
//ajax function return a deferred object
function _ajax(action,data){
return $.ajax({
url: 'request.php',
type: 'POST',
dataType: 'JSON',
data: {action: action, data: data}
})
}
//your form submit event
$("#myformid").on('submit', function(event) {
//prevent post
event.preventDefault();
//validate that name is not empty
if ($("name").val() != "") {
//parameters INS is insert data is the array of data yous end to the server
var action = 'INS';
var data = {
name: $("#name").val()
};
console.log(data);
//run the function and done handle the function
_ajax(action,data)
.done(function(response){
console.log(response);
//anppend name to the div
$("#myDiv").append("<p>"+response.name+"</p>");
});
}
});
your request.php file:
<?php
//includes and session start here
//validate that request parameters are set
if (isset($_POST["action"]) && isset($_POST["data"])) {
//getters
$action = $_POST["action"];
$data = $_POST["data"];
//switch to handle the action to perfom maybe you want to update with the form too ?
switch ($action) {
case 'INS':
// database insert here..
//return a json object
echo json_encode(array("name"=>$data["name"]));
break;
}
}
?>
Results:
Hope it helps =)
From the documentation of .serializeArray().
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.
And in the example given in the same page, it is clear that you will get an array in php,
to access an element, you should try-
`$data[0]['name']`
Also, have you tried print_r($data), is it NULL??
Change your ajax codes
$('#btnSubmit').on('click', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/new.php",
data: $("#myformid").serialize(),
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Also you need some changes in form
<form action="new.php" method="post" id="myformid">
Name <input type="text" name="name">
<input id="btnSubmit" type="button" value="Test">
And you can get POST data in php file like $_POST['name']
You can set directly form serialize in ajax request to send params
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/my/path",
data: $("#myformid").serialize(),
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And you can get POST in your PHP using $_POST
print_r($_POST);

Uploading multiple files from different inputs using Ajax

I have two different file inputs and multiple textual/select inputs, that I'd like to upload to a PHP file using Ajax. The file inputs are meant to send images, and because they are two specific images that I'd like to identify by the name of the input, I do not want to use <input type="file" multiple>.
Currently I have the following (names have been changed to keep it simple):
<input type="file" name="file1">
<input type="file" name="file2">
<textarea name="text1"></textarea>
<button>Submit</button>
What I have tried is to push both to a variable once the change event of the file input gets fired, followed by the button press triggering the upload using Ajax.
$('input[type="file"][name="file1"]').on('change', prepareUpload);
$('input[type="file"][name="file2"]').on('change', prepareUpload);
files = new Array;
function prepareUpload(event){
files.push(event.target.files);
}
$('button').on('click', uploadFiles);
function uploadFiles(event){
$('#uploadInfo').html('Uploading...');
event.stopPropagation();
event.preventDefault();
var data = new FormData();
$.each(files, function(key, value){
data.append(key, value);
});
data.append('text1', $('textarea[name="text1"]').val());
$.ajax({
url: '',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(result){
//do stuff
},
error: function(error){
console.log(error);
}
});
}
But this seems to do nothing. Is it even possible to append two image inputs to the same request using Ajax, or am I better off trying to put it in two different requests?
event.target.files is a array, so you need the first file in the array
function prepareUpload(event){
files.push(event.target.files[0]);
}

How can i post data and file by using ajax on event onclick

HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}

how can i upload file to server using FormData?

I try to file upload to spring server using FormData object. And I hide input for type="file". However, when I submit form, it is not working. I don't know where is incorrect.
This is part of html. when some button is clicked, saveFiles() is called.
<script src="http://malsup.github.com/jquery.form.js"></script>
<form name="fileForm" id="fileForm" method="post" enctype="multipart/form-data">
<input style="display:none" type="file" id="fileSelector" name="fileSelector" multiple="" />
<input type="hidden" id="docId" value="${doc.id}" />
<div id="files"></div>
</form>
(function (global, $) {
...
initFilehandler();
...
}
function initFilehandler() {
document.querySelector('#fileSelector').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#files");
}
function saveFiles() {
$("form#fileForm").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
console.log(formdata);
$.ajax({
url: "/rd/file/save",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert("success");
}
});
});
}
You can't just use formdata for uploading files. There's a lot of options for this one. But Im giving you a less complicated one.
Try using this plugin:
jQuery Form
I've been using that for years especially multiple file uploads. Good thing.. these plugin has callback for upload progress.. you can make a progress bar or something out of it..

how to upload file using ajax request with sinatra?

i'm tring to upload file using jquery ajax function with ruby-sinatra function. here is my code.
<form id="ucform" method="post" action="#" enctype="multipart/form-data">
<input type="file" id="cfile" name="cfile" onchange="prepareUpload(this.files)">
<button type="submit">Update</button>
</form>\
javascript code
var ufiles;
function prepareUpload(files)
{
ufiles = files
}
$(function(){
$('#ucform').on('submit', uploadFiles);
});
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
//alert(ufiles);
// Create a formdata object and add the files
var data = new FormData();
$.each(ufiles, function(key, value)
{
data.append(key, value);
});
alert(data);
$.ajax({
url: '/upload_cfiles',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
alert(data);
}
});
}
sinatra function
post '/upload_cfiles' do
begin
File.open('applications/QOS/conf/' + params['cfile'][:filename], "w") do |f|
f.write(params['cfile'][:tempfile].read)
end
return "The file was successfully uploaded!"
rescue Exception => e
return e.message
end
end
above code return bellow error
ERRORS: parsererror
undefined method `[]' for nil:NilClass
please help me to solve this error
It's a safe bet that params['cfile'] is nil. Have you actually logged your request parameters to ensure you are posting what you think you're posting?
Furthermore, I believe that you're trying to upload these files using JSON - you will most likely need to base64 encode the body of the file to do this.

Categories