I have no idea how to implement this, let me try to explain
I have a form that open inside a bootstrap modal frame in my layout, in this form i have 2 fields
<input type="file" name="photoimg" id="photoimg" value="" />
<input type="hidden" name="consulta" value="5">
I need to submit this to my url with the value 5 for 'consulta' so the script can read and do the proper things with the file,
BUT
I need to do this without refreshing the opened modal, in other words, using ajax to submit the file (for further cropping)
i have this script that do the submit, what i'm doing wrong here?
<script type="text/javascript">
function enviaimagem(){
$.ajax({
type: "POST",
data: { consulta:5 },
dataType: 'html',
url: "<?=JURI::ROOT()?>ajax.html",
//dataType: "html",
success: function(result){
$("#corpo_modal").html('');
$("#corpo_modal").html(result);
},
beforeSend: function(){
$("#corpo_modal").html('');
$("#corpo_modal").css({display:"none"});
$('#ajaxloadergeneric').css({display:"block"});
},
complete: function(msg){
$('#ajaxloadergeneric').css({display:"none"});
$("#corpo_modal").css({display:"block"});
}
});
}
</script>
File upload through AJAX is supported through FormData object:
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
, however it is not supported by all/old browsers( especially IE < 10)
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,
....
I have a form that has a simple file input.
<form id="uploadFile" name="uploadFile" action="addFile.php" method="POST" enctype="multipart/form-data">
<input type="hidden" value="" name="uploadWUID" id="uploadWUID">
<p>Please upload a signed and completed write-up in PDF format. Please file the hardcopy of the write-up per company policy.</p>
<div class="input-group" style="margin-bottom:7px;">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input type="file" id="reportImport" name="reportImport">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
</form>
There is some local javascript that puts the filename in the text input, but the text input is not used in the PHP file.
The uploadWUID is set dynamically and is passed to add the uploaded file to a specific record in a database.
When I submit the form it works just fine. My browser redirects to addFile.php, success is echoed out, the file is moved to the correct directory and the database is updated.
My issues comes when I add return false to my ajax form submission. I get an error back from the php file stating it couldn't find the index when processing $filename = $_FILES['reportImport']['name']; and my upload/database update fails.
$('#uploadFile').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {}
});
return false;
});
Change script code
$('#uploadFile').submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
data: formData,
type: $(this).attr('method'),
url: $(this).attr('action'),
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(response) {
console.log(response);
alert(response);
return false
}
});
return false;
});
I'm totally noob in jQuery and become desperate to get it to work.
This is the html:
<form method="post" enctype="multipart/form-data">
<input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">
</form>
jQuery:
$("#pic").change(function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data)
alert(form_data);
$.ajax({
url: 'doupload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(dat){
alert('it works maybe');
}
});
});
So I just want to send the file to doupload.php and catch it there with ($_FILES['file']['tmp_name'])
But it's not working (ofc) and I don't find anything which is working either google nor stack...
I use this lilbary: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<input id="pic "type="file" name="file" onchange="javascript:this.form.submit();">
You have "type="file"
Change it to type="file"
Also, if you have the ajax sending on change via "$("#pic").change(function() { then you SHOULD NOT have onchange="javascript:this.form.submit();" as well, as it will submit the form while the ajax is still sending, causing possible timing issues (such as the ajax call not completing)
As far as I can tell, you should not have a submit event at all, as the data is already submitted via an ajax call.
First let me say I'm new to Ajax. I've been reading articles from jquery.com and some tutorials but I didn't figured it out yet how this works on what I'm trying to achieve.
I am trying to get the weather for a searched city using Google's Weather API XML, without page refresh.
I managed to retrieve the Weather XML and parse the data but everytime I search for a different place, the page reloads since my weather widget is under a tab.
This is what I have in my HTML:
<script type="text/javascript">
$(document).ready(function(){
// FOR THE TAB
$('.tab_btn').live('click', function (e) {
$('.tab_content').fadeIn();
});
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
aysnc:false,
success:function(result){
$(".wedata").html(result);
}});
});
});
</script>
<style>.tab_content{display:none;}</style>
</head><body>
<input type="button" value="Show Content" class="tab_btn">
<div class="tab_content">
<h2>Weather</h2>
<form id="searchform" onKeyPress="return submitenter(this,event)" method="get"/>
<input type="search" placeholder="City" name="city">
<input type="hidden" placeholder="Language" name="lang">
<input type="submit" value="search" class="submit" style="width:100px">
</form>
<div id="weather" class="wedata">
</div>
</div>
And here is the actual demo I'm working on: http://downloadlive.org.
Now, if I add action="weather.php" on the search form I get the results, but I get redirected to weather.php which is logical. Without the action="weather.php", everytime I search my index which I'm on, adds up /?city=CITY+NAME which shouldn't. This should be added to weather.php, get the results and then retrieve them back into my index, if that makes sense?
This is my php code for weather.php: http://pastebin.com/aidXCeQg
which can be viewed here: http://downloadlive.org/weather.php
Can someone please help me out with this please?
Thanks alot
You just need to return false; from the click event handler. This will prevent the default action from occuring - in this case, submitting the form. Also, remove the async: false setting. You almost never want synchronous ajax requests.
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});
Alternately you can pass a parameter name to the callback and then use event.preventDefault() to accomplish the same result as above:
$(".submit").click(function(e){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
e.preventDefault();
});
You need to send the form data with the POST. It's super-easy to do this using .serialize().
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
data: $(this.form).serialize(),
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});