I'm trying to submit a form using AJAX to stop the browser from refreshing the page.
The form is located inside a secondary page, that is called into the main page div ( similar to using a master page and the content placeholder ).
I have been trying several methods but I always reach the same problem. Whenever I try to submit the form, the response is the secondary page with the form, and I can't place the awnser inside the content div of the mainpage like intended.
Any tips on how to make this work?
Main Page
<div id="content"> Secondary page content goes in here loaded using AJAX</div>
Secondary Page
<form runat="server" id="formuser">
<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
<asp:TextBox ID="txtemail" runat="server"></asp:TextBox>
Submit Form
</form>
What I intend to do is Submit the above form, while staying in the Main Page and showing the response in the content div.
I need the form to be runat="server" so I can manipulate the data using the code-behind.
Use some jquery:
$('#SaveFormButton').click(function (e) {
$.ajax({
type: "POST",
url: $('#FormToSubmit').attr("action"),
data: $('#FormToSubmit').serialize(),
success: function (data) {
//Whatever you want to do after the form has posted
},
error: function(data){
alert("Error");
}
});
});
Something like this should do it. This way using e.preventDefault() you can use standard form markup and submit buttons.
http://jsfiddle.net/CcDPx/1/
It seems that the method I was using for the content load was building a xmlHttpRquest and it was conflicting with the response that I got from the jquery.
Related
I have the below code which I am using to open a aspx page inside a modal popup but the issue is as soon as I load the host page of the modal popup it is redirecting to the one which is inside the iFrame.
<cc1:ModalPopupExtender ID="mp1" runat="server" PopupControlID="Panl1" TargetControlID="Button1"
CancelControlID="Button2" BackgroundCssClass="Background">
</cc1:ModalPopupExtender>
<asp:Panel ID="Panl1" runat="server" CssClass="Popup" align="center" Style="display: none">
<iframe style="width: 350px; height: 300px;" id="irm1" src="PayrollScope.aspx?id=49437" runat="server"></iframe>
<br />
<asp:Button ID="Button2" runat="server" Text="Close" />
</asp:Panel>
So the sequence is
MainPage.aspx -> Click PopUp -> Load PayrollScope.aspx inside the modal
But as soon as I hit the MainPage.aspx it is redirecting to PayrollScope.aspx. I tried to use jQuery modal popup also but the same issue is happening. Can someone please tell me why it's redirecting.
Thanks
If you use jQuery dialog to load that other page?
Well, it will display, but THEN if any code in the page has a post back, then yes, it will re-direct to that page.(jQuery dialog simply pulls the whole other page right into that div and "merges" it into your current page's dom. So, you can display the page, and no re-direct will occur. However, any server side button event code (button press, or even say a after update event of editing a text box (on changed) will cause a post back. And any post-back WILL thus cause the page to re-direct (after all any code behind event does send the WHOLE page back and the URL to IIS. So, it much depends on if you JUST displaying that page, or if you want/need/have user interaction on the 2nd page loaded as a dialog.
So, dump the ajax popup and controls reverence to the id of the popup. (don't try jQuery an the ajaxtool kit to "both" try and pop up a control/div - they tend to not play nice with each other.
I do suggest using jQuery.
This would work (but with above post back issues in mind).
<body>
<form id="form1" runat="server">
<br />
<asp:Button ID="Button1" runat="server" Text="Show page as dialog" OnClientClick="showpage1();return false"/>
<div id="poppage" runat="server" style="display:none">
</div>
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
function showpage1() {
var mydiv = $('#poppage');
mydiv.dialog({
autoOpen: false, modal: true, title: 'My cool other page', width: '50%',
position: { my: 'top', at: 'top+150' }
});
mydiv.load('MyOtherPage.aspx');
// Open the dialog
mydiv.dialog('open');
}
So, above will LOAD the other page (into that div), thus pop up the 2nd page when you click on the above button. (and note the return=false). If you have any postback on the page, then everything will quite much blow out the dialog. (and this also means the 2nd page we display (load) as per above.
However, if you need interaction on that 2nd page? (have to click on buttons etc.).
Then the idea of a iframe is a VERY good idea.
So, you have same as before, but we now don't "load" the page using jQuery.ui, but JUST display (and thus pop up) the div with a iframe you placed inside.
So,the div becomes this:
<div id="poppage" runat="server" style="display:none">
<iframe src="MyOtherPage.aspx" class="auto-style1"></iframe>
</div>
and the js code becomes this:
function showpage1() {
var mydiv = $('#poppage');
mydiv.dialog({
autoOpen: false, modal: true, title: 'My cool other page', width: '50%',
position: { my: 'top', at: 'top+150' }
});
// Open the dialog
mydiv.dialog('open');
}
So, now the above will just display that other page in the div, and since it is a iFrame, then you can interact - and post backs in that iframe should work just fine.
So, remove the ajax panel stuff - give jQuery.ui a try. I used the ajaxtool kit stuff, but for displaying another whole page in a dialog, then i found jQuery.ui seems to work a lot better
I have jquery code on cc.js that I need to execute when an asp.net button is clicked.
The code on cc.js has a variable called settings and then submits these settings to an API (POST action) with the following code:
'Transaction Submit'
$.ajax(settings).done(function (response) {
console.log(response);
});
Basically I need this button <asp:Button ID="BtnSubmit" runat="server" Text="Submit" /> to execute that jquery code. How can I do so?
You are looking for the OnClientClick property
<asp:Button ID="BtnSubmit" runat="server" OnClientClick="JSFunctionName(); return false;" Text="Submit" />
You will need to add the additional return false statement to prevent a post back from occurring if you button element is located inside a form.
This is assuming you want to decouple your front end html from your js code by using an inline call. If that is not the case then you mod your cc.js to autobind on the element as others have mentioned. One thing they left out is that in that process is that IF you button is inside a form then you need to prevent the auto-post back like so:
$(document).ready(function() {
$("#BtnSubmit").click(function(){
JSFunctionName();
e.preventDefault();
});
});
If the ID of the button is BtnSubmit, then you should be able to add a event handler like this.
$(document).ready(function() {
$("#BtnSubmit").click(function(){
alert("button clicked - do stuff here.");
});
});
change the alert("button clicked - do stuff here."); to your ajax request code.
You can write the following code to create an event on Button click to call the jquery method..
Basically, you take the ID by $("#btnSubmit") and on its click event write your Ajax function.
$("#BtnSubmit).on('click',function() {
// your ajax code here
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />
Hope this helps.
Just Add a click event with your button id using jquery..
$("#BtnSubmit").on('click',function(){
console.log('success...');
//ajax call here...
});
You can use Ajax within JS functions. I'm not sure what version of .NET you're using, but I'll answer with what I know for MVC 5.
Here's how I would do it:
HTML
<button id="SubmitBtn">Submit</button>
JS(JQuery)
$('#SubmitBtn').on('click', function () {
//Transaction Submit
$.ajax({
type: "POST",
url: '/ProjectName/Controller/Method',
data: { methodParameter1: data1, methodParameter2: data2 },
success: function (data) {
//do whatever
}
error: function (response) {
//do whatever
}
});
});
I have a Website project with a master page with the standard default Microsoft theme that is created when starting a new project.
I created a Search page that I want to call from this menu and put the new anchor tag within this standard menu. The click of the search link will pull up a modal and bring in my search.aspx page within it.
<li>Search</li>
function Search() {
document.getElementById('<%= hdnButtonSearch.ClientID%>').click();
}
This is the modal the source is a webform Search.aspx
<asp:ModalPopupExtender ID="ModalSearch" runat="server" PopupControlID="Panl1" TargetControlID="hdnButtonSearch"
CancelControlID="Button2" BackgroundCssClass="modalBackground" ></asp:ModalPopupExtender>
<asp:Panel ID="Panl1" runat="server" CssClass="Popup" align="center" style = "display:none">
<iframe style=" width: 800px; height: 600px;" id="irm1" src="Search.aspx" runat="server"></iframe>
<br/>
<asp:Button ID="Button2" runat="server" Text="Close" />
</asp:Panel>
I could call this modal window from being on any of the webforms just by clicking the Seach link within the menu.
Now the Problem.
I Call and open up the modal extender and it opens the search.aspx webform.
On this webform I want to put a button to close the modal.
I don't want to use the standard button in this case Button2 within the ModalPopupExtender I want to use a button that is actually on the Search.aspx page.**
What will really happen is the user searches for a client the client goes inside a grid and then the client wants to view that client so they click a link button within the gird which loads the client and then I want the modal to close.
How could I close this modal within the search.aspx page?
The search page does not have a MasterPageFile its just a webform that pops up within the modal.
In the search page I have a button. That calls the Javascript function to close the modal but it does not work I get an error.
Microsoft JScript runtime error: Object expected
function HideModalPopup() {
$find("ModalSearch").hide();
return false;
} </script>
Your search.aspx page is being rendered into the modal but is effectively part of the same page. This isn't an iframe, so you can assume it has full access to the DOM and all the available scripts.
Whatever JavaScript function you already have in place to close the modal, call that from the relevant client-side control from your search.aspx page.
So that's a long title, here's what I'm doing: To avoid having report parameters show up in the URL I'm doing this in a button click handler in the code-behind to show the report:
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head></head>");
System.Web.HttpContext.Current.Response.Write("<body onload=\"document.mainform.submit(); \">");
System.Web.HttpContext.Current.Response.Write(string.Format(CultureInfo.InvariantCulture, "<form name=\"mainform\" method=\"post\" action=\"{0}\">", ReportURL));
foreach (string key in Params.Keys)
{
System.Web.HttpContext.Current.Response.Write(string.Format(CultureInfo.InvariantCulture, "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", key, Params[key]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
This works great, but when I go back from the report I'm taken to the page I just generated which immediately submits the form due to the onload event. I can hit back twice really quickly to go back past it but this isn't ideal.
I've tried opening a new window with JavaScript using ClientScript.RegisterStartupScript before writing the html but I don't know how (or if it's even possible) to get the HttpContext for the new window.
I wasn't able to recreate the problem using your code, so more context may help. Depending on how the rest of the page is structured, you may be able to use PostbackURL instead of a click handler:
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="Key1" Value="Value1"/>
<asp:HiddenField runat="server" ID="Key2" Value="Value2"/>
<asp:Button runat="server" ID="button"
Text="ok" PostBackUrl="ReportURL.aspx"/>
</form>
This way you don't have to worry about an extra/replaced page in the browser history.
I ended up opening a new window. I added two small javascript functions
function openNewWin() {
$('form').attr('target', '_blank');
setTimeout('resetFormTarget()', 500);
}
function resetFormTarget() {
$('form').attr('target', '');
}
Then in the linkbutton I set
OnClientClick="openNewWin();"
The OnClick still executes the code above server-side but the response is written to the new window. The setTimeout in the openNewWin function resets the form's target property so the app will still function normally after coming back to it.
I have a ModalPopup that will contain a gridview and 4 fields to enter items into the gridview itself.
Is it possible to postback to the server and update the gridview while keeping the modal open?
When you submit the fields and the postback occurs the modal closes has anyone done this before? Someone mentioned a solution using jQuery, but this was long ago.
Wrapping the popup's content (i.e. not the popup itself!) in an UpdatePanel worked for me.
My popup content is a search panel with sortable/pageable grid of results. The UpdatePanel gave me the exact behaviour I require with no additional code.
Thanks to Patel Shailesh for the idea.
<asp:Panel runat="server" ID="PopupPanel" Height="650" Width="900" Style="display: none">
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<!-- popup content -->
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<ajax:ModalPopupExtender runat="server" ID="PopupExtender" PopupControlID="PopupPanel"
TargetControlID="PopupButton" />
<asp:Button runat="server" ID="PopupButton" Text="Popup" />
The key to doing this is going to be using AJAX of some flavor -- Microsoft.Ajax or jQuery Ajax. If the UpdatePanel is not working, then I'd suggest using jQuery to submit back to the server using AJAX. This would involve creating a WebMethod to accept the AJAX post on the server side and instrumenting the client-side with jQuery to send the request/receive the response. Without seeing your HTML it's a little hard to be very specific.
Basic idea:
$(function() {
$('#modalSubmitButton').click( function() {
$.ajax({
url: 'path-to-your-web-method',
dataType: 'json', // or html, xml, ...
data: function() {
var values = {};
values['field1'] = $('#field1ID').val();
...
values['field4'] = $('#field4ID').val();
return values;
},
success: function(data,status) {
... update page based on returned information...
}
... error handling, etc. ...
});
return false; // stop any default action from the button clicked
});
});
I am not sure if this would work, but try to put whatever inside the modalpopup in a UpdatePanel
Please if this works don't hate me after you release, I hate updatepanels too
A kind of ugly option is to force a postback when showing the modal popup in the first place and setting a ViewState["ModelPopupOn"] = true; and then check that on page load and finally postback again and set it to false/remove it from viewstate when closing the popup.
(these kind of issues are why I hate the ajax toolkit)
I was experimenting with the modalpopupextender, and find a ugly solution.
If the modal panel has a button that makes the postback to happen
<asp:Panel runat="server" ID="PopupPanel" Height="650" Width="900" Style="display: none">
<asp:Button ID="OkButton" runat="server" Text="OK" OnClick="OkBtn_Click" />
</asp:Panel>
If the OkBtn_Click in the code-behind has a call to:
System.Web.HttpContext.Current.Response.Write("<script></script>");
Then the modalpopupextender is not closed.
This happened too to this guy:
http://forums.asp.net/t/1591860.aspx