I try to post an uploaded file via ajax to php.
HTML:
<form id="uploadForm" name="uploadForm" action="#" enctype="multipart/form-data">
<input id="name" name="name" class="form-control" type="text" />
<input id="csv" name="csv" type="file" />
<input id="CSVUpload" type="submit" class="btn btn-default" name="Submit" value="Hochladen" />
JS
$("#uploadForm").submit(function () {
var formData = new FormData();
formData.append( 'csv', $( '#csv' )[0].files[0] );
formData.append( 'name', $( '#name'));
jQuery.ajax({
url: "../lib/import.php",
data: formData,
type: "POST",
success: alert('erfolgreich'),
error: alert('Fehler'),
cache: false,
contentType: false,
mimeType: 'multipart/form-data',
processData: false
});
});
and then i try to get the form data in PHP:
$_FILES['csv']
$_POST['name']
But the Ajax call completes with success and error... I'm confused...
The PHP file will not executed correctly...
Thanks for your help!
You aren't assigning functions to success or error.
You are calling the alert function immediately and then assigning its return value.
You need to create new functions to assign to success and error.
success: function () { alert('erfolgreich') },
error: function () { alert('Fehler') },
You are also calling the function as a submit handler, but aren't preventing the normal form submission. Consequently, the browser will load a new page before processing the response to the Ajax request.
$("#uploadForm").submit(function (event) {
event.preventDefault();
Try restructuring your AJAX call with your success and failure code like this:
$.post('../lib/import.php', formData).done(function() {
console.log('done');
}).fail(function() {
console.log('error');
});
See http://api.jquery.com/jquery.post/ for more examples.
Related
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 am attempting to create an upload document which will upload a profile picture. I am having trouble capturing the data from the changePicture form which only has an input for the images and a submit. I have never used the FormData object to date, so I am still learning around this. Any guidance would be useful.
See my HTML
<form id="changePicture" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Update Your Profile Picture</label>
<input type="file" id="profilePic" class="form-control" name="profilePic">
<input type="hidden" value="<?php echo $id; ?>" name="id">
</div>
<button type="submit" id="updateProfileBtn" class="btn btn-success float-right">Upload Image</button>
</form>
Here is my AJAX code:
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(result){
$("#spinner").hide();
$("#changePicture").append(result);
setTimeout(function(){
$("#changePicture").slideDown();
}, 1500);
}
});
}, 3000);
});
}
The PHP file at this moment only echos out "Working" to see it accesses the page alright, which it does. However, when I attempt to locate the file through a variable nothing has been sent and returns undefined index.
this will be undefined because it's inside ajax's scope
Try:
me = this;
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(me),
...
As, for me, when using ajax I always prefer to base64encode the image and pass it as a JSON to PHP but i guess that's a personal preference...
Why are you wrapping your AJAX call in a
setTimeout(function() {..})
?
By doing this, you cannot simply write new FormData(this), because the this context does not refer to the form that you are looking for.
Try executing the code without the timeout, or try storing the form data in a global variable
Edit: Example added:
var myFormData;
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
myFormData = new FormData(this);
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: myFormData,
....
In jQuery, when a function got success a form getting build. Now when I submit this form it gives all data except inputType='file'. I can't get it why this is happening
here is my jQuery code when form is creating
content += '<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data">'+
'<input type="text" name="album_id" value="'+id+'">'+
'<input type="text" name="user_id" value="'+user_id+'">'+
'<input type="file" name="image" id="image_upload">'+
'<input type="submit" value="Submit">'+
'</form>';
Here form is getting submit
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function(data) {
console.log(data);
});
return false;
});
I am sending this form data in a controller in cakephp.
In controller I get only input field data with text type only. But I need file type too.
please use jquery.form.js for file upload.
http://malsup.com/jquery/form/
<form method="POST" action="'+formURL+'" id="data" enctype="multipart/form-data" onsubmit="return submit_form();" >
function submit_form(){
$('#data').ajaxSubmit({
method:'post',
dataType:'json',
success: function(resp){
}
});
return false;
}
You can change jquery function like this
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
I having multiple forms in a single page submitting via jQuery ajax. All forms use same class names. Also i am using malsup jquery plugin for form submission.
I can successfully pass the data to a php file but the error message is reflecting on all forms div.message. I don't want to have different form ids because i need to have all ids in the jquery then.
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
jQuery part
<script>
$(document).ready(function() {
$('.myform').on('submit', function(event) {
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
$('div.message').append('<div>'+message+'</span>');
}
}
});
});
});
</script>
How can i append the error message to the submitted form's div.message correctly?
Any help will greatly appreciated.
I think you can get the msg div before post .
$(document).ready(function() {
$('.myform').on('submit', function(event) {
msgDiv=($this).children('div.message');//before post get the msg div first
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
msgDiv.append('<div>'+message+'</span>');
}
}
});
});
});
</script>
I have a form that will display a list of transactions based on the name and date.
<form id="form1" name="form1" method="post" action="<?php echo base_url() ?>options/history">
Name
<input name="name" type="text" id="name" />
date
<input name="date" type="text" id="date" />
<input name="find" type="submit" id="find" value="find" />
</form>
Once the form is submitted all the relevant details are being displayed.
Can someone explain to me how I can use jquery to loads the data on the same page?
I'm new to jquery and learning stuff. I did some research and below is what I have found:
<script type="text/javascript">
$(document).ready(function() {
$('#find').click(function() {
$.ajax({
type: "GET",
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
}
});
});
});
</script>
And also how do I pass the form variables to my controller? Is it possible to directly pass the values to the controller or do I have to pass it along with the URL?
<script type="text/javascript">
$(document).ready(function() {
$('#form1').submit(function() {
// get the data of the form
var data_form = $('#form1').serialize();
$.ajax({
type: "GET",
cache: false,
data: data_form,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
// Your data is in the var data returned, you can use it with, for example: $("#content").html(data);
}
});
// Prevent default behaviour
return false;
});
});
</script>
I am a bit confused here. But I suppose you actually want this:
$('form#form1').submit(function(evt){
$.ajax({
type: "GET",
data: $(this).serialize(),
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function (data) {
alert('Data Loaded');
}
});
evt.preventDefault();
return false;
});
You can use .submit() to bind to the JavaScript's submit event instead. By returning false at the end of this handler you can stop the form submission as shown above; or, by using evt.preventDefault().
The data property in $.ajax specifies the data to be sent to the server. As for getting this data you can use .serialize(), it will encode the form elements ready for submit them.