Jquery Ajax Upload with progress is reloading page - javascript

I have strange stuf with a Jquery form submit.
After the upload completed, the page is reloading even in the server has not finished to process.
The server just return a json succes status, so It's not on server side.
Here"s the code:
$form.on('submit', function (e) {
console.log('Submit form ' + fileNumber);
if ($form.hasClass('is-uploading')) return false;
$form.addClass('is-uploading').removeClass('is-error');
if (isAdvancedUpload) {
e.preventDefault();
e.stopPropagation();
var ajaxData = new FormData($form.get(0));
var $input = $form.find('input[type="file"]');
if (fileToUpload) { ajaxData.append($input.attr('name'), fileToUpload); }
console.log('FileTo Upload: ' + fileToUpload);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: 'json',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
},
cache: false,
contentType: false,
processData: false,
beforeSend: function (xhr,settings) {
},
complete: function (xhr, status) {
xhr.
//$form.removeClass('is-uploading');
//fileNumber++;
//fileToUpload = droppedFiles[fileNumber];
//if (fileToUpload) { $form.submit(); }
},
success: function (data,status,xhr) {
//$form.addClass(data.success === true ? 'is-success' : 'is-error');
//if (!data.success) $errorMsg.text(data.error);
},
error: function (xhr,status,error) {
}
});
} else {
// ajax for legacy browsers
}
});
The issue is here:
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
If I remove return myXhr The page is not reloading after upload, but I have no progress report.
I don't know what to do to prevent reloading.
Thanks.

I found out the issue.
There was no worry with the xhr object.
The issue was coming from Visual Studio Browser Link.
After shuting it down, everything worked perfectly.
Browser link, for an obvious reason was fire a reload of the page.
Will see with the ASP.NET Core team

try change buttin type submit to button and implement click function
eg:
$( "#buttonID" ).click(function() {
//your code
});

Related

How to run JavaScript code on Success of Form submit?

I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.
I have the below Code.
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", id = "formID" }))
{
}
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
FunctionToBeCalled(); //JS function
}
}
But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().
So I made the below changes by referring this link. But now the APIMethod is getting called twice.
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
function FunctionToBeCalled(){alert('hello');}
So I am not able to solve the issue.
If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.
View:
$('form').submit(function (event) {
event.preventDefault();
var formdata = $('#demoForm').serialize();
//If you are uploading files, then you need to use "FormData" instead of "serialize()" method.
//var formdata = new FormData($('#demoForm').get(0));
$.ajax({
type: "POST",
url: "/DemoController/Save",
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set to
false in order for FormData to work (otherwise comment out both of them) */
processData: false, //For posting uploaded files
contentType: false, //For posting uploaded files
//
//Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
beforeSend: function () {
//e.g. show "Loading" indicator
},
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data); //e.g. display message in a div
},
complete: function () {
//e.g. hide "Loading" indicator
},
});
});
Controller:
public JsonResult Save(DemoViewModel model)
{
//...code omitted for brevity
return Json(new { success = true, data = model, message = "Data saved successfully."
}
Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.
function save(event) {
//Validate the form before sending the request to the Controller
if (!$("#formID").valid()) {
return false;
}
...
}
Update your function as follows.
$('#formID').submit(function (e) {
e.preventDefault();
try{
$.validator.unobtrusive.parse("form");
if ($(this).valid()) {
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
catch(e){
console.log(e);
}
});
Check the browser console for fetching error. The above code will prevent of submitting the form.
I think line $.validator.unobtrusive.parse("form") were throwing error.
For that use you need to add the following jQuery libraries.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:
Here is the revised version of your code :
<form method="post" id="formID">
<!-- Your form fields here -->
<button id="submit">Submit</button>
</form>
Submit your form on button click like:
$('#submit').on('click', function (evt) {
evt.preventDefault();
$.ajax({
url: "/Configuration/APIMethod",
type: 'POST',
dataType : 'json',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
});
function FunctionToBeCalled(){alert('hello');}
You need to use Ajax.BeginForm, this article should help [https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/ ]
The major thing here is that I didn't use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked
You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.
(function() {
$(function() {
var _$pageSection = $('#ProccessProductId');
var _$formname = _$pageSection.find('form[name=productForm]');
_$formname.find('.buy-product').on('click', function(e) {
e.preventDefault();
if (!_$formname.valid()) {
return;
}
var formData = _$formname.serializeFormToObject();
//set busy animation
$.ajax({
url: 'https://..../', //_$formname.attr('action')
type: 'POST',
data: formData,
success: function(content) {
AnotherProcess(content.Id)
},
error: function(e) {
//notify user of error
}
}).always(function() {
// clear busy animation
});
});
function AnotherProcess(id) {
//Perform your operation
}
}
}
<div class="row" id="ProccessProductId">
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", name="productForm" id = "formID" })) {
<li class="buy-product">Save & Proceed</li>
}
</div>

How to write code inside ajax without xhr

I have a code like this before:
<script>
function()
{
//*code*
fxajax.sendData
({
url:"",
data:{},
success:function(){},
error:function(){}
});
}
</script>
But my manager wants me to put my code inside the ajax so i put it inside beforeSend
<script>
function()
{
fxajax.sendData
({
beforeSend: function()
{/*code*/}
url:"",
data:{},
success:function(){},
error:function(){}
});
}
</script>
My problem is beforeSend is not executed but url, data, success and error works fine. Then I think maybe its because I don't have an XHR request.
Any idea how I should implement this code?
Here is a simple way
$(document).ready(function(){
// set a 1 second to fire ajax request
setTimeout(function () {
// url of the image
var url = 'https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg';
$.ajax({
url : '', // url request
type : "GET", // type of request,
beforeSend : function () {
var i = new Image();
i.src = url;
i.onload = function () {
// change it to div
$('div').append(i);
}
console.log("ajax is firing");
},
success: function () {
},
error : function (xhr, txtstatus, text) {
console.log(txtstatus);
console.log('error');
// any error from request
}
});
}, 1000);
});
Here is a simple DEMO

Abort a multiple file upload AJAX request

I am trying to abort a multiple file upload with a progress bar, showing the state of the process.
What I want to achieve is to completely abort the multiple file upload on the abort button click; to stop the progress bar as well as to clear every file(s) that might have been uploaded during the course of the initially triggered multiple file upload process.
Below is my code:
var AJAX = $.ajax({
xhr: function() {
var XHR = new window.XMLHttpRequest();
XHR.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var PROGRESS = Math.round((e.loaded/e.total)*100);
$('#PROGRESS_BAR').text(PROGRESS);
} }, false); return XHR; },
url : '/php.php',
type : 'POST',
data : DATA,
cache : false,
processData: false,
contentType: false,
beforeSend : function() { },
success : function() { }
});
$(document).on('click', '.ABORT', function(e) {
AJAX.abort();
});
I use the code above to dynamically upload images with a progress bar.
I found lots of articles using .abort() to stop the process, but that seemed to only work browser side and not server side.
In what way can I cease the upload completely as in: on both client and server side as .abort() does not enable me get the desirable result?
Try this:
var XHR = new window.XMLHttpRequest();
var AJAX = $.ajax({
xhr: function() {
XHR.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var PROGRESS = Math.round((e.loaded/e.total)*100);
$('#PROGRESS_BAR').text(PROGRESS);
} }, false); return XHR; },
url : '/php.php',
type : 'POST',
data : DATA,
cache : false,
processData: false,
contentType: false,
beforeSend : function() { },
success : function() { }
});
$(document).on('click', '.ABORT', function(e){
XHR.abort();
});

event.preventDefault(); only works some of the time with submit form

I am using the Mailchimp API to submit a form. The goal is to prevent the default callback provided by Mailchimp. The majority of the time event.preventDefault() is behaving as it should. Then randomly it will not work:
$(function () {
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
if(event) event.preventDefault();
register($form);
});
});
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
var message = data.msg
var messageSh = data.msg.substring(4);
if (data.msg == '0 - Please enter a value' || data.msg == '0 - An email address must contain a single #') {
$('#notification_container').html('<span class="alert">'+messageSh+'</span>');
} else {
$('#notification_container').html('<span class="alert">'+message+'</span>');
}
} else {
// It worked, carry on...
var message = data.msg;
$('.popup-promo-container').addClass('thanks');
$('.checkboxes, #mc_embed_signup_scroll').addClass('hidden');
$('.complete-promo').html(message).removeClass('hidden');
setTimeout(function() {
document.querySelector('.popup-promo').style.display = "none";
},20000);
}
}
});
}
Try
take off ready function.
remove if on event
Code:
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
event.preventDefault();
register($form);
});

Tooltip script. Need to correct code

$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
var ajaxQueue = $({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
$.ajaxQueue = function(ajaxOpts) {
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
});
});
it's my first experience with js and i need some help. for tooltips i use bootstrap tooltips.
when cursor hover on link, script send post data to controller and receive callback data. in the first hover script receives the data, but tooltip doesn't pop up, only the second hover. how i can fix it?
and one more question. can script will send the request only the first mouse hover, and the following hover will use the information from the cache?
and sorry my english ;D
It is hard to test cross domain
Here is what I THINK you need
$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
$.ajax({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
});
});
Create flag for ajax query.
var isTooltipTextEmpty = true;
$('.challenge').mouseover(function(){
if(isTooltipTextEmpty) {
...add ajax query here)
}
}
And you need to trigger tooltip show event, when ajax query is ready like this
.success(data) {
$('.challenge').show();
isTooltipTextEmpty = false; //prevents multiple ajax queries
}
See more here: Bootstrap Tooltip

Categories

Resources