I've seen lots of questions on this subject, but none of them seem to address my issue. It all seems pretty straight forward, but I just get a blank array, am I missing something really simple here?
Thanks.
Here is the html / javascript code:
<script type="text/javascript" src="/javascript/jquery.js"></script>
<form enctype="multipart/form-data" action="" id="frmProduct" method="post">
<input type="file" id="pdffile" name="pdffile" size="50" />
<br />
<input id="pdffileupload" type="submit" value="Upload" />
</form>
<script>
$('#pdffileupload').bind('click', function ()
{
var files=document.getElementById('pdffile').files[0];
var fd = new FormData();
fd.append( "pdffile", files);
$.ajax({
url: '/info.php',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function(data) { alert("YES"); },
error: function(data){ alert("NO"); }
});
return false;
});
</script>
& PHP info.php
<?php
var_dump($_FILES);
?>
Changes needed (just check once by trying all my suggestions):-
1.In the same folder put both files (same working directory).
Code changes:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <!-- add jquery library like this -->
<form enctype="multipart/form-data" action="" id="frmProduct" method="post">
<input type="file" id="pdffile" name="pdffile" size="50" />
<br />
<input id="pdffileupload" type="submit" value="Upload" />
</form>
<script>
$('#pdffileupload').bind('click', function ()
{
var files=document.getElementById('pdffile').files[0];
var fd = new FormData();
fd.append( "pdffile", files);
$.ajax({
url: 'info.php', // remove /
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function(data) { alert("YES"); },
error: function(data){ alert("NO"); }
});
return false;
});
</script>
And in php
<?php
print_r($_FILES);
?>
Note:- Check in your browser console (response tab).
You might try this:
<?php print_r($_FILES); ?>
instead of
<?php var_dump($_FILES); ?>
Because the var_dump doesn't work with $_FILES.
Related
Here is my sample code which I got from a website which converts xls to xlsx. It downloads the file immediately after converting it to xlsx, so I want to use that file further as blob. so is there any way to use that file which I will receive from action method using JavaScript?
Thank you!
HTML Code :
<form action="https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&download=attachment" method="post" enctype="multipart/form-data">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="anyName" />
<input type="submit" value="Convert file"/>
</form>
JavaScript code:
function convert(input){
let obj = {
File : input,
FileName : 'Test'
}
$.ajax({
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&StoreFile=true',
method: 'POST',
headers:{
'content-type' : 'multipart/form-data'
},
body: JSON.stringify(obj),
success : function(res){
console.log(res);
},
error: function(err){
console.log(err.responseText);
}
})
}
you would use javascript's fetch() to upload the file to the conversion endpoint instead of using a form, then you would get the file download as a response, which you can do with what you like.
this question may help you figure out how to upload a file, but you will have to understand a bit of javascript:
How do I upload a file with the JS fetch API?
I tried to upload same way as you mentioned #dqhendricks but didn't worked for me.
when I tried with FormData it worked for me. It would be awesome if we could do it with just JS.
HTML :
<form method="post" enctype="multipart/form-data" id="fileUploadForm">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="newFile" />
<input type="button" id="btnSubmit" value="Convert file"/>
</form>
JS:
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
var form = $('#fileUploadForm')[0];
var d = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=[Secret]&StoreFile=true',
processData: false,
contentType: false,
cache: false,
data: d,
timeout: 600000,
success: function (res) {
console.log(res);
},
error: function (err) {
console.log(err.responseText);
}
})
});
});
For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});
I have a html file where users can input a value.
I wrote a script in PHP that checks if this value is present in the databse. If it's present it returns
{"active":true}
Now my goals is that when the user inputs their value and submit they will be redirected to a certain page if this active is true. If it's false they should see an error message.
So here's what I've tried with my AJAX call:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
data: data,
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
Here is my HTML:
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="#" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue" />
</form>
For some reason I get an error:
Uncaught ReferenceError: data is not defined
I am new to AJAX and I am not sure if what I am trying is correct.
Any help would be greatly appreciated!
Thanks in advance.
Can you try:
$(".aanmeldenmodal").submit(function(e){
e.preventDefault();
I am updating my answer in whole
<html>
<body>
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="txt1" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue checkform" />
</form>
</body>
</html>
jQuery part is like
$("document").ready(function () {
$("body").on("click", ".checkform", function (e) {
e.preventDefault();
var request = $("#txt1").value;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {request: 'request'},
dataType: 'json',
success: function (data) {
if(data.active==true){
alert("success");
}else{
alert("failure");
}
}
});
});
});
ajax.php should be like this
if(isset($_GET['request'])){
//check for the text
echo json_encode($arr);
}
In api/check.php
You can pass data in json format
$json = json_encode($data);
retrun $json;
You can also not share any data so You can remove data from jQuery.
data:data
Your Jquery look like this:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
I want to Upload photos by using Ajax Post method,
Here is my html and javascript code
<script>
$(document).ready(function(){
$('#multiple_upload_form').submit(function(e){
e.preventDefault();
var upload = $('#images').val();
$.ajax({
type:'POST',
url:'album.php',
data:
{
upload : images
},
cache:false,
contentType:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
},
error:function()
{
$('#image_preview').html('error');
}
});
return false;
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="album.php" name="upload_form" id="multiple_upload_form" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="email">Album Name</label>
<input type="text" name="aname" class="form-control" id="aname">
</div>
<div class="form-group">
<label for="file">Upload Photos:</label>
<input type="file" id="images" name="images" />
</div>
<div id="images_preview"></div>
</div>
<center class="feedback" style="display:none">Loading...</center>
<button id="submit" name="submitt" class="btn btn-default">Submit</button>
</form>
and this is my PHP CODING
if(isset($_FILES['images']['name']) )
{
$img = $_FILES['images']['name'];
if(!empty($img))
{
echo 'MaxSteel';
}
}
else
{
echo 'Same Problem';
}
I am having undefine index : images
it works fine with input type="text" but when it comes to "file" type is shows error help me solving this problem
Go through this code, it may help
var data = new FormData();
data.append("Avatar", file.files[0]);
$.ajax({
url: "http://192.168.1.1:2002/,
type: "POST",
data:data,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
Its posible that the file is not upload becouse of some error. You should review the parameters related to file upload as UPLOAD_MAX_SIZE, etc.
You can use var_dump($file) to see the $_FILE content.
You need to be sending your data through FormData().
Try something like this:
var images = $("#images").get(0).files;
var formData = new FormData();
$.each(images, function(i, image) {
data.append("images[]", image);
});
Then send formData as your $.ajax data.
I try to do a simple simple upload but i guess iam too dumb or its too late here.
I searched a bit and founded this here on Stack
HTML
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input id="uploadBTN" type="button" value="Stash the file!"></input>
<div id="output"></div>
JS
$("#uploadBTN").click(function(event) {
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: './ajax/upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
PHP
if(isset($_POST['file'])){
$filename = $_FILES['file']['name'];
if(isset($filename) && !empty($filename)){
echo 'sup my man?!';
}else{
echo 'please choose a file';
}
}else{
echo 'not set';
}
The Problem with these Stuff is its saying not set so? With GET Method its same cause i tested mostly everthing out.
And no i dont want to use any plugin or something else :)
My Question is how can i access correctly the File ?
Or if this Lines of Code are totally Crap what is a other solve?
Thanks!
Try this, It works for me.
$("#uploadBTN").click(function(event) {
event.preventDefault();
var tmp_form = $("#fileinfo")[0];
var fd = new FormData(tmp_form);
$.ajax({
url: './ajax/upload.php',
type: 'POST',
data: fd,
async: true,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
<form action="" method="post" enctype="multipart/form-data" id="fileinfo">
<input type="file" name="file" required >
</form>
<input id="uploadBTN" type="button" value="Stash the file!"></input>
<div id="output"></div>
if(isset($_FILES['file'])){
$filename = $_FILES['file']['name'];
if(isset($_FILES['file']['name']) && !empty($filename)){
echo 'sup my man?!';
}else{
echo 'please choose a file';
}
}else{
echo 'not set';
}