I have used submit and added an onclick event to it and I want to call the controller method save for it, and after that I want to redirect my page to another method of the controller for that I have used onclick where I have used opener.href = "". My problem is that sometimes it goes to the save page but oftenly it goes to the onclick event first. I have searched it on google and all the methods tell me to the way I did but something is not right. Please help me.
Here is the code:
<input id="m_bs_btnNext" type="submit" value="Save" onclick="closeWindow();" />
and the onclick function is:
function closeWindow() {
window.opener.location.reload();
window.opener.location.href = "ViewDesign";
setTimeout("window.close()", 800);
}
I would have your close window happen after the save by using onsubmit on your form:
<form id="form" action="/save" onsubmit="saveAndCloseWindow()">
<-- Other form elements -->
<input id="m_bs_btnNext" type="submit" value="Save" onclick="closeWindow();" />
</form>
Then your save function would look like this:
function saveAndCloseWindow() {
$.ajax({
url: $('#form').attr('action'),
method: 'POST',
success: function() {
window.opener.location.reload();
window.opener.location.href = "ViewDesign";
setTimeout("window.close()", 800);
}
})
}
Related
I am new in asp.net core and facing one issue. I have a partial view which is updated by Ajax call inside the main view. The calling button is also inside the partial view. Now I want to show a loader image for some fix time when I click the button and then results from ajax call will be loaded. For this I wrote a function to display the image for 5 seconds. But when I am clicking the button image appears and suddenly disappears. Even if I removed setTimeout then also same behavior. Below is the code from partial view. Please advice.
<form asp-controller="Home" asp-action="Parser" data-ajax="true" data-ajax-update="#CustomerList" onsubmit="return show();">
<input type="text" id="txtWeb" name="Web" placeholder="Please enter" class="form-control" style="margin-top: 20px;" />
<button type="submit" id="button1">
Click
</button>
<p>
#ViewBag.Id
</p>
<img src="~/img/ajax-loader.gif" id="img" style="display:none" />
<script type="text/javascript">
function show() {
document.getElementById('img').style.display = 'block';
setTimeout(hide, 5000);
}
function hide() {
document.getElementById('img').style.display = 'none';
}
</script>
</form>
Why the display style of image automatically set to 'none' again here?
But when I am clicking the button image appears and suddenly
disappears
This is because the onsubmit method directly executes its own process, which skips other codes in the show method.
Here its own process of the onsubmit method is to directly submit the form to /Home/Parser action.
To make the code in the show method execute normally, you need to use the event.preventDefault(); statement to prevent the original process, and then at the end of the hide method, manually create the form submission code by ajax.
<script>
function show() {
event.preventDefault();
document.getElementById('img').style.display = 'block';
setTimeout(hide, 5000);
}
function hide() {
document.getElementById('img').style.display = 'none';
$.ajax({
type: "post",
url: "/Home/Parser",
success: function (data) {
$("#txtWeb").val(data);// here is my test code
}
})
}
</script>
In Home controller:
[HttpPost]
public IActionResult Parser()
{
return Json("new value");
}
Here is the test result:
I have a form on a page.
<div id="form_catch">
<form id="form2">
<div><input type="button" value="Dear Diary" id="add" /><input type="button"
value="Dear Friend" id="add_1" /></div>
<div><input type="text" id="salutations" name="salutations" value=""/></div>
<input type="submit" value="Submit" class="submit" />
</form>
</div>
I use a javascript to manipulate this form
$(document).ready(function(){
var form_box_copy = $('#form_catch').html()
$("#add").click(function(){
$('input#salutations').val('Dear Diary,');});
$("#add_1").click(function(){
$('input#salutations').val('Dear Friend,');});
//console.log('test button');
$("form#form2").submit(function(evt){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://wei.rocks/test2.html',
type: 'GET',
data: {
format: 'html'
},
enctype: 'multipart/form-data',
processData: false,
error: function(){alert('You Failed');},
success: function (response) {
alert('You passed');
$('#form_catch').html(form_box_copy + "html replaced");
$('#form_catch').append("Test222222222");}
});
return false;
})
})
When I run the page the scrip works as designed I ajax the form, the task are successful. After success It replaces the form with a fresh copy of it self. All this work except when it is complete the Replacement of the form is no long working with the Java script.
The reason this is happening is because when you replace the form with the new html, it discards the submit event registration attached to the form.
To bypass it you can either re-register the event or, as a better approach, register the event at the document level.
Simply change:
$("form#form2").submit(function(evt){
// your code
});
to:
$(document).on('submit', '#form2', function(evt) {
// your code
});
});
This should now work since the event is registered at the document level and not at the form level (and the document is never being replaced).
In general if you are replacing DOM elements, then the events registered to them will no longer work. This is why registering to the element's parent is a better approach (when needed).
See this codepen for working example.
Hope this helps.
I want to insert an email address into my db with an ajax call.
Here comes the problem. Instead of working into the background, it refreshes the page.
alert("yea"); in the success function is not being reached.
What could be the problem?
$(document).ready(function() {
$("#header-subscribe").click(function(){
var str = $("#email").val();
if( validateEmail(str)) {
$.ajax({
url: 'php/signupForm.php',
type: 'GET',
data: 'email='+str,
success: function(data) {
//called when successful
alert("yea");
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
The form:
<form id="hero-subscribe" class="the-subscribe-form" >
<div class="input-group">
<input type="email" class="form-control" placeholder="Enter Your Email" id="email">
<span class="input-group-btn">
<button class="btn btn-subscribe" id="header-subscribe" type="submit">subscribe</button>
</span>
</div>
</form>
The Ajax call has nothing to do with the refresh. You have a submit button and the purpose of the submit button is to submit the form.
The simplest solution would be to not use a submit button:
type="button"
However, binding the event handler to the click event of the button is not good practice. So instead of that and changing the type, bind the handler to the submit event and prevent the default action (which is submitting the form):
$("#hero-subscribe").submit(function(event) {
event.preventDefault();
// ...
});
You need to prevent the default action of the click...
$("#header-subscribe").click(function(event){
event.preventDefault();
You should bind the submit event of form and use event.preventDefault() to prevent the default action of event.
$("#hero-subscribe").submit(function(event) {
event.preventDefault();
//Your code
});
event.preventDefault() the form action, otherwise it submits like a normal form.
$("#header-subscribe").click(function(event){
event.preventDefault(); //stop the default submit action
I’m trying to submit a form to with javascript (jquery) to another page that export the result to excel. Below is the code I use to send form data a page and return the results to a div on the same page.
<script type="text/javascript">
function get3() {
$.post('chartprojecttype.php',
$('form[name="reportform"]').serialize(),
function (output) {
$('#info').html(output).show();
});
}
</script>
I tried to modify it like this,
<script type="text/javascript">
function get4() {
$.post('openticketsexcel.php',
{
document.getElementById(‘reportform’).submit();
});
</script>
But it does not work. I have another way to do this and have to different pages that export it in different format.
<input type="image" name="excel" onclick="submitForm('openticketsexcel.php')" value="Export To Excel" src="../pix/excel.png" class="submit_button"><input type="image" name="word" onclick="submitForm('openticketsword.php')" value="Export To Word" src="../pix/word.png"class="submit_button">
and
<script type="text/javascript">
function submitForm(action)
{
document.getElementById('reportform').action = action;
document.getElementById('reportform').submit();
}
</script>
This works but only in IE. Chrome and FireFox can used the first code that returns the submitted data but not the code that submits it to the export pages. Any ideas?
You have MANY issues
1) input type=image is a submit button. Do NOT submit in the onclick of the submit button since you will actually interfere with the event
2) why would you need to submit a form after you post the form to the server? If you need the server to return a word or excel, you need to GET (I GET below by chaning location) or POST a form - but not using $.post since the browser needs to open the file, you cannot ajax word or excel
You likely just want this:
<button class="button" id="excel"><img
alt="Export To Excel" src="../pix/excel.png"/></button>
<button class="button" id="word"><img
alt="Export To Word" src="../pix/word.png"/></button>
using
$(function() {
$(".button").on("click",function(e) {
e.preventDefault();
location="opentickets"+this.id+".php?"+$('form[name="reportform"]').serialize();
});
});
The simpler solution is just
<form action="export.php" target="_blank">
<input type="submit" name="exportformat" value="Excel" />
<input type="submit" name="exportformat" value="Word" />
</form>
and have the php sort things out
You forgot the function and an ending curly brace, and your single quotes were curly instead of straight. Try this:
<script type="text/javascript">
function get4() {
$.post('openticketsexcel.php', function() {
document.getElementById('reportform').submit();
});
}
</script>
jQuery post should be like this
$.post( "some/url", function( data ) {
// code goes here
});
REFERENCE
http://api.jquery.com/jQuery.post/
So I have this:
$('#id').submit(function(e){
e.preventDefault();
etc etc
I want to be able to have this:
$('#id' + variable).submit(function(e){
e.preventDefault();
etc etc
I'm not sure what I should do to go about that. The reason for it is that there are many similar forms on the page that get generated dynamically.
I tried doing this and I'm guessing that is just a terrible thing to do but it was all I could think to try as I am not very good with JQuery:
function foo(variable){
$('#id' + variable).submit(function(e){
e.preventDefault();
etc etc
}
But that causes the form to be submitted multiple times.
-edit- to respond to a request:
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function(data) {
var responseData = jQuery.parseJSON(data),
etc etc do some stuff like show a message (all that works)
If you are producing multiple forms with different ID's dynamically, it would probably advantageous if they all used the same class="preventSubmit" and your code looked like:
$('.preventSubmit').submit(function(e){
var currentThis = this;
alert(this.id);
e.preventDefault(); // breaks this
alert(currentThis.id);
etc etc
If you want to avoid the submission itself, there are two approaches:
1) Use a input type="button" and attach a event handler for click:
<input type="button" id="submit_btn" value="Submit" />
// (In Javascript):
$("#submit_btn").click(function() {
});
2) To stop the submission, use return false :
$("#id" + variable).submit(function() {
return false;
});
Try this.
$('form').on('submit', function(e){
var variable = $(this).attr('id');
e.preventDefault();
});
If you have this html
<div id="wrap">
<form id="id35">
<input type="submit" value="submit" />
</form>
</div>
and this js
var threeFive = 35;
$("#id"+threeFive).submit(function(e){
e.preventDefault;
alert("hi");
});
it works!! ... BUT, ...if you have this html
<div id="wrap">
</div>
and later you append dynamically the form element to the container, let's say like
sample js function
function addMe(){
$('#wrap').append('<form id="id35"><input type="submit" value="submit" /></form>')
}
sample add button
<a class="addMe" href="javascript:addMe();">add form</a>
then, the example alert doesn't work anymore when you submit the form.
You would need to modify your script to support that dynamically added form using the .on() method (and jQuery v1.7.x) targeting the parent container like
var threeFive = 35;
$("#wrap").on("submit","#id"+threeFive, function(e){
e.preventDefault;
alert("hi");
});
then it will work
if you have to deal with a lot of forms in single page, you might want to exploit bubbling.
<div class="container-for-all-forms">
<form id="..." class="..."> ..... <input type="submit" /> </form>
<form id="..." class="..."> ..... <input type="submit" /> </form>
<form id="..." class="..."> ..... <input type="submit" /> </form>
.
.
</div>
js bit might be
$('#container-for-all-forms').bind('click.formProcessor', function(event){
var $clicked = $(event.target);
if($clicked.is(':submit')){
event.preventDefault();
console.log($clicked.parents('form').attr('id'));
/* at this point you can get all id names from php (or template language), bind js variables and match. like:
var idNames = ['<?...?>','<?...?>']
*/
}
});
this will bind only one event to container element, and you can run all sorts of checking when a click occurs in that container.