I am developing a mobile site using asp.net and jquery. no plugin. just simple jquery.I am using the
<input type="file"/>
of HTML5.
So few questions to get the big picture:
1.Can i load files without jquery plugin, but only simple jquery? Just picking the file, send it using ajax and catch it on server side?
2. I have noticed the Request.Files attribute of the Request object. Will it get filled only with post of the whole page or can i get my files there using Ajax?
3.In case the answer in 2 is "No!", how do i exclude the files data on the server side?
Thanks
This is the solution i have found:
JS:
<script type="text/javascript">
$(document).ready(function () {
$('#inputFile').on('change', function () {
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
var formData = new FormData();
formData.append(file.name, file)
$.ajax({
url: 'AjaxPage.aspx',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
alert(response);
},
error: function (e) {
alert(e);
}
});
});
});
</script>
CS: (On ajax page to catch the files and manipulate them as you will)
var files = Request.Files;
HTML:
<body>
<div>
<input type="file" id="inputFile" />
</div>
</body>
Related
This may be duplicate but I can't solve it.
I can send multiple images by JQuery/Ajax to my server (Asp.Net Core) and save them successfully. But the problem is when I want to add the second batch files, the first batch will not append to form data. I add images with a button and not by input type="file" field.
HTML:
<form asp-area="User" asp-controller="Item" asp-action="Create" id="createForm" method="post" enctype="multipart/form-data" >
<input asp-for="ImageUrl" id="myInput" type="file" name="inputFile[]" accept="image/*" multiple style="display:none" />
<button id="myButton" type="button">+ Add Files</button>
JS:
$(document).ready(function () {
var inputFile = $('#myInput');
$('#myButton').click(function () {
$('#myInput').click();
});
var files = [];
$('#myInput').change(function () {
var newFiles = [];
for (var index = 0; index < inputFile[0].files.length; index++)
{
let file = inputFile[0].files[index];
files.push(file);
}
});
});
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData(document.getElementById('createForm'));
//var formData = new FormData(this);
files.forEach(file => {
formData.append('file[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
});
});
});
Suppose I choose pictures 1,2,3 and submit my form and all 3 pictures save to server side successfully. Now let's try a new record: I add pictures 1,2,3, after that I choose pictures 4,5,6 so I expect to 6 images to be appended to form data. But only the last selection 4,5,6 are saved to server !
This is my console report in below.As you can see I have input-File[]=3 !! Something like I have no jquery and no ajax and just using pure HTML/Input Multiple file and I can upload only my last selections !!
But when I refresh my page and choose just 1,2,3 images (one selection only), I have input-File[]=3 and file[], [object File]=3 and every thing is good.
I tried data: new FormData() and data: formData and many other options on data parameter but no one could solve my problem :(
Update : ******************************:
Case 1:
var formData = new FormData(document.getElementById('createForm'));
. . .
data: formData,
Results: No image save in server and ImageUrl is null in database.
Case 2:
var formData = new FormData()
. . .
data: formData,
Results in error in console : XML Parsing Error: no root element found
Case 3:
var formData = new FormData(this)
. . .
data: formData,
Results : suppose I select images 1,2,3 at first and then select images 4,5,6. I have images 1,2,3,4,5,6 saved on server and 4,5,6 save twice !! I'm getting near but still can't manage it.
.
I think there might be an error in the way that you copied your code. There is an extra }); after $('#myInput').change(function () { ... });
I'm assuming that is not part of the issue and was just a mistake in pasting it over.
The issue I think is that you were trying to send the files over separately from the inputFiles. Updating the for loop in the submit event handler should give you what you are wanting.
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData();
files.forEach((file) => {
formData.append('inputFile[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: formData,
});
});
I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });
I simply want to use ajax to submit a form with an image from a phone.
If I use the below code as a simple function - the form data is not passed.
If I use the code as is - it works but the user has to click the submit button.
How do I either pass the FormData properly to a simple $.ajax({}); submit?
OR
How do I trigger the code below when a picture is taken or selected?
I have this - it works fine when user clicks submit:
// how do I trigger this when image file is selected?
$("#Upload_Form").submit(function(e){
e.preventDefault();
// OR - how do I get FormData with image without using: '$("#Upload_Form").submit(function(e)'
var formData = new FormData(this);
$.ajax({
// POST details are here etc.
});
});
Bind the change event for the file input like below and then trigger the submit event of the form or make an ajax call right away with the FormData see below demo.
If you want to know how to submit image using FormData and ajax see this answer
$("#my-form").on('submit', function(e) {
e.preventDefault();
// OR - how do I get FormData with image without using: '$("#Upload_Form").submit(function(e)'
var formData = new FormData(this);
console.log("sending Ajax call now");
$.ajax({
// POST details are here etc.
});
});
$("#my-file").on('change', function() {
//you can either trigger the form submit here
var form = $("#my-form");
$("#my-form").submit();
//OR
//use this to send the ajax call to upload the image
// var form=$("#my-form")[0];
// var formData = new FormData(form);
// $.ajax({
// type: "POST",
// url: 'your/url',
// data: formData,
// processData: false,
// contentType: false,
// success: function (data) {
// console.log("SUCCESS : ", data);
// },
// error: function (e) {
// console.log("ERROR : ", e);
// }
// });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form" enctype="multipart/form-data">
<input type="file" name="my-file" id="my-file" />
<input type="submit" name="submit" value="submit" />
</form>
Update
Note: if you want to use an ajax call to send the formData you need to set the processData and contentType to false. contentType: false only available from jQuery 1.6 onwards.
I am trying to register a user via AJAX using FOSUserBundle.
The problem is that the name value in the form is fos_user_registration_form_[username] so it isn't accepted by javascript as array.
<input type="text" id="fos_user_registration_form_username" name="fos_user_registration_form[username]" required="required" />
How can I solve that?
Can I change the name parameter in FOSUserBUndle to fos_user_registration_form_username ?
How can I create an array with fos_user_registration_form_[username] value in Javascript?
$("#registerButton").click( function(){
data = {
fos_user_registration_form_[username]:$("#name").val(), // HERE IS WHERE IT CRASHES, IN THE [username] field.
fos_user_registration_form_[email]:$("#email").val(),
fos_user_registration_form_[plainPassword]:$("#password").val(),
};
$.ajax({
type: "POST",
url: serviceURL,
asyn:false,
data: data,
dataType: "json",
success: function(res) {
alert("success"); // JUST FOR TEST
}
});
I am testing a basic example..
This works (triggers the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_username:"blabla"
};
alert(true);
</script>
This doesn't works: (do not trigger the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_[username]:"blabla"
};
alert(true);
</script>
To fetch the data from your input fields, you need to combine the name_of_the_form_ + the name_of_the_field. For example:
fos_user_registration_form_ + username => fos_user_registration_form_username
data = {
fos_user_registration_form[username]:$("#fos_user_registration_form_username").val(),
fos_user_registration_form[email]:$("#fos_user_registration_form_email").val(),
fos_user_registration_form[plainPassword]:$("#fos_user_registration_form_plainPassword").val(),
};
This has been asked many many times. But none of the solutions are working for me in IE and Chrome.
I basically want to show a loading image while ajax call is being made.
Following is what I'm trying.
function ws(){
showL();
var res=$.ajax({url:'webservice.asp?service=LoadingTestSRV',async:false,cache:false}).responseText;
$('#dv').html(res);
hideL();
$('#complete').html('Done');
}
function showL()
{
$('#loading').show();
}
function hideL()
{
$('#loading').hide();
}
Following is the HTML
<table cellspacing="1" cellpadding="1" border="1">
<tr><td>
<input type="button" value="ckick" id="btn" onClick="ws();">
<input type="button" value="clear" onClick="$('#dv,#complete').html('');">
</td><td>
<div id="dv"></div>
</td></tr><tr>
<td>Here<div id="loading" style="display:none" >Loading.................</div></td>
<td>final<div id="complete"></div></td></tr>
</table>
After above js, I tried
ajaxStart and ajaxStop
$.ajaxSetup
$.ajax({...}).done(hideL)
All the js codes I tried are working in Firefox but none of them are working in IE and Chrome.
In Firefox, the code works as expected. Loading div gets shown, ajax is called, loading div gets hidden. This is exactly what I'm expecting.
In IE & Chrome, loading div doesn't show up. Maybe It's getting shown and hidden very fast after or before ajax call.
Please let me know what can be done to make the code work in IE & Chrome.
There has to be some workaround as I've seen other sites show loading div. Or maybe I'm doing something stupid.
Once the code is working in all browsers. I want to make a generic function (like a jQuery plugin) to show a loading div when ajax is being called.
try this:
This will ensure that ur DIV is hidden after the ajax call completes
function ws() {
showL();
var res ="";
$.ajax({
url: 'webservice.asp?service=LoadingTestSRV',
async: true,
cache: false,
success: function(data) {
res=data;
$('#dv').html(res);
hideL();
$('#complete').html('Done');
}
});
}
function showL() {
$('#loading').show();
}
function hideL() {
$('#loading').hide();
}
This form has worked for me previously: (I put in the slow so you could see it if it is fast)
$('#loading').ajaxStart(function() {
$(this).show("slow");
}).ajaxComplete(function() {
$(this).hide("slow");
});
Test example of this here:
http://jsfiddle.net/MarkSchultheiss/xgFkw/
I do it this way try if it helps..
$.ajax({
beforeSend: function () {
$('#loadingDiv').show();
$('#accordion').hide()
},
complete: function () {
$('#loadingDiv').hide();
$('#accordion').show();
},
type: "GET",
url:
data: shallowEncodedData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (
There is a problem in your ajax call. Remove the async:false from ajax call and it will work even in IE8/9 and Chrome. For other Lost-souls, please do the above changes and try again.
simple just Add async=true in ajax function. It will work in chrome
My workaround for this issue in Chrome, use a timeout on the AJAX call of one millisecond.
E.g.
$("#mySpinningLoader").show();
var t = setTimeout(function () {
$.ajax({
url: rootPath + controllerNAction,
async: false,
type: "POST",
data: JSON.stringify(lightweightObject),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
$("#mySpinningLoader").hide();
}
});
}, 1);