Form is not posted in IE in mvc? - javascript

My form is submitted correctly in all browser all functions working right. But In IE the form is not posted.
I have searched and found the issue of cache. But nothing works. This is my code.
$('#newUserForm').submit(function () {
debugger;
var form = $(this);
var url = form.attr('action');
var formData = form.serialize();
$.ajaxSetup({ cache: false });
$.post(url, formData, function (result) {
if (result.redirect) {
window.location.href = result.redirect;
return;
} else {
UserRoles.cleanData();
}
});
return false;
});

Remove the debugger; line from your js. I believe your form works in ie, but only while the developer console is open. The ie stops all script execution after a console.log() for example, while the dev console is closed.
As a workaround, you could ask the window object if a console is opened:
if (window.console) {
debugger;
}

Related

e.preventDefault() on a link still loads the page

the title may be a bit misleading but I'm not sure how to phrase it better, so I apologize for that.
I'm creating a custom handler so the site doesn't refresh when new content is pressed (similar to how youtube works, for example).
For that I'm using this script:
$('.sidebar2 li a').click(function (e) {
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
e.preventDefault();
test = false;
return false;
}
}
});
});
even though I've stated e.preventDefault() to trigger, javascript loads the new content into the current frame without refreshing, but the browser refreshes again anyway.
I've tried to use href="#" however in this case when I go back and handle that, I always end up with two same pages, one without and one with # at the end, and in addition to that it wouldn't be very user friendly to have all links href="#"
What am I doing wrong to make the browser redirect "normally" even though I've told him no no no?
I've also tried adding onclick="javascript:void(0)" on a elements and that didn't help
ajax is async. By the time success callback is called event will already be bubbled up the DOM tree and processed. You need to call preventDefault before sending a request.
$('.sidebar2 li a').click(function (e) {
e.preventDefault(); // here for example
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
test = false;
// returning here makes no sense also
// return false;
}
}
});
});

on browser reload/refresh/close alert and then ajax

Is it possible to fire an alert on browser close? If user confirm "reload/close" then want to execute some ajax stuff. This is I have tried so far
window.onbeforeunload = function () {
return 'This will close your chat session. Are you Sure!';
var meta_id = $('#meta_id').val();
$.ajax({
url: site_url + '/chat/send_offline',
type: 'post',
cache: false,
async: false,
data: {
meta_id: meta_id
}
});
}
As far I know code not execute after the return statement. So is it possible to alert and execute ajax code simultaneously if user confirm??
I found this in MDN documentation
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Do you want to leave this page ?";
// Call AJAX RIGHT HERE
e.returnValue = confirmationMessage; // Gecko and Trident
return confirmationMessage; // Gecko and WebKit
});
You have to call the Ajax before return in the function. Because return break the execution of the function.
Maybe chrome.runtime.onSuspend or chrome.windows.onRemoved will help you?

Ajax form submitting twice with Yii 2

I've looked around and none of the other similar posts have helped me. I have built an AJAx based form in Yii 2 and jQuery and it seems it submits the form twice.
My form:
$form = ActiveForm::begin([
'id' => 'company_form',
'ajaxDataType' => 'json',
'ajaxParam' => 'ajax',
'enableClientValidation' => false
]);
My JS code:
$(document).ready(function() {
/* Processes the company signup request */
$('#company_form').submit(function() {
signup('company');
return false;
});
})
function signup(type) {
var url;
// Set file to get results from..
switch (type) {
case 'company':
url = '/site/company-signup';
break;
case 'client':
url = '/site/client-signup';
break;
}
// Set parameters
var dataObject = $('#company_form').serialize();
// Run request
getAjaxData(url, dataObject, 'POST', 'json')
.done(function(response) {
//.........
})
.fail(function() {
//.....
});
// End
}
Shouldn't the standard submit be stopped by me putting the return: false; in the javascript code?
Why is it submitting twice?
More Info: However the strange thing is, that only appears to happen the first time; if I hit submit again it only submits once; but if I reload the page and hit submit it will do it twice again.
You may need to change your code like below:
$('#company_form').submit(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
signup('company');
return false;
});
http://api.jquery.com/event.stoppropagation/
http://api.jquery.com/event.stopimmediatepropagation/
Solution common
Next JS will works with any state of 'enableClientValidation':
$('#company_form').on('beforeSubmit', function (e) {
signup('company');
return false;
});
https://yii2-cookbook.readthedocs.io/forms-activeform-js/#using-events

Delayed submit results in multiple continuous submits

I have the following jQuery code, the point of this code is to create a short time delay, so the AJAX request gets time to execute properly:
$('#form_id').submit(function(e) {
e.preventDefault();
$submit_url = $(this).data('submitUrl');
$submit_url = $submit_url.replace('http://','').replace(window.location.host,'');
if ($(this).data('toBeAjaxSubmitted') == true) {
$.ajax($submit_url, {
type : $(this).attr('method'),
data : $(this).serialize(),
complete : function(data) {
$(this).data('toBeAjaxSubmitted', false);
$('#form_id').submit();
}
});
}
});
What happens is, the form starts off with a submit url that I need to submit to in order for the component to save an entry to the database. But I also need user input to submit directly to a payment gateway URL where the user then makes a payment.
The code above creates the AJAX request, but does not return to normal postback behaviour (via $('#form_id').submit()).
It keeps submitting the form over and over, but never posts to the gateway URL or redirects out.
What am I doing wrong?
The following worked for me after some more debugging:
$('#chronoform_Online_Submission_Step8_Payment').submit(function(e) {
var form = this;
e.preventDefault();
$submit_url = $(this).data('submitUrl');
$submit_url = $submit_url.replace('http://','').replace(window.location.host,'');
if ($(this).data('toBeAjaxSubmitted') == true) {
$.ajax($submit_url, {
type : $(this).attr('method'),
data : $(this).serialize(),
complete : function(data, status) {
}
}).done(function() {
form.submit();
});
}
});
What really put me on the wrong path was that in Chrome's Developer Tools I had the following option enabled 'Disable cache (while DevTools is open)' and this was causing some headaches with inconsistent behaviour between Safari, Firefox (which worked) and Chrome which did not.
What about some fiddling with this approach?
$('#form_id').submit(function(e) {
// closures
var $form = $(this);
var fAjaxComplete = function(data) {
// don't send the ajax again
$form.data('toBeAjaxSubmitted', 'false');
// maybe do some form manipulation with data...
// re-trigger submit
$form.trigger('submit');
};
var oAjaxObject = {
type : $form.attr('method'),
data : $form.serialize(),
complete : fAjaxComplete
};
var sSubmitUrl = $form.data('submitUrl');
// scrub url
sSubmitUrl = sSubmitUrl.replace('http://','').replace(window.location.host,'');
// if ajax needed
if ($form.data('toBeAjaxSubmitted') != 'false') {
// go get ajax
$.ajax(sSubmitUrl, oAjaxObject);
// don't submit, prevent native submit behavior, we are using ajax first!
e.preventDefault();
return false;
}
// if you got here, go ahead and submit
return true;
});

JS: Cross Browser Compatibility - my JS works in chrome, not in FF

I've got some JS which works in Chrome, but not in FireFox, and I'm too inexperienced in JS to be able to troubleshoot this without some assistance.
I tested it from localhost on my dev machine and from its deployed location (on our internal intranet) ... same results in both cases.
In chrome, it does exactly what I expect. It asynchronously catches a JSON object from the API and splashes it for the user.
In FF, it takes the user to the target API URL. No "asynchronisity".
What tweaks can I do to support FF too??
(fortunately, FF & Chm are the only two I need to code against).
Any and all help will be greatly appreciated.
var submit_map_url = 'blahblah'; // dynamically generated by PHP
$('#mapper_form').submit(function() {
event.preventDefault();
$.ajax({
type:'POST',
url: submit_map_url,
data:$('#mapper_form').serialize(),
success: function(response) {
var response = $.parseJSON(response);
if(response.status == 'failure'){
alert(response.message);
}else{
var doRedirect = true;
$('#splash').fadeIn(800, function() { // fade in
window.setTimeout ( function() { // start a timer for auto redirect
$('#splash').fadeOut(1000, function() { // fade out
if(doRedirect) window.location = redirect_target; // then redirect
}) }
, 4000); //
});
$('#splash').click(function(){ // on click
doRedirect = false; // cancel the redirect request
$(this).fadeOut(700,function() {}); // and fade out
});
$('#countdown').countdown({until: +5, format: 'S'});
} // end IF/ELSE
} // end success:
}); // ajax
return false;
});
Add the event parameter to you submit function. $('#mapper_form').submit(function(event) {
Chrome has a global event object window.event when you are in a event handler.

Categories

Resources