I have a popup calendar that is being called from the parent form. What I am wanting to happen is when the user clicks on the date after it updates parent form field it automatically submits the parent form (where certain date checks will happen upon refresh). Ive tried using Ajax and for some reason the calendar popup window closes after the selection is made but the parent form wont submit. Is there anything Im missing here?
Here is the ajax code in the actual calendar popup window.
<script type=”text/javascript”>
// function create GetXmlHttpObject
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject(“Microsoft.XMLHTTP”);
}
return null;
}
function submitFormWithAjax(){
var myAjaxPostrequest=new GetXmlHttpObject();
var t2lrequestend=document.docreq.request_end.value;
var t2lrsubmit="Submit Request";
var parameters=”request_end=”+t2lrequestend+"rsubmit="+t2lrsubmit;
myAjaxPostrequest.open(“POST”, “rm_new_arp_request_NEW_TIME_RESTRICTION.php”, true);
myAjaxPostrequest.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
myAjaxPostrequest.send(parameters);
myAjaxPostrequest.onreadystatechange=function(){
if(myAjaxPostrequest.readyState==4){
if(myAjaxPostrequest.status==200){
document.getElementById(“result”).innerHTML=myAjaxPostrequest.responseText;
document.getElementById(“docreq”).style.display = “none”;
}
else {
document.getElementById(“docreq”).innerHTML=”An error has occured making the request”;
}
}
}
}
</script>
And here is where it is supposed to submit the form and close the child window.
function set_datetime(n_datetime, b_close) {
if (!obj_caller) return;
var dt_datetime = obj_caller.prs_time(
(document.cal ? document.cal.time.value : ''),
new Date(n_datetime)
);
if (!dt_datetime) return;
if (b_close) {
obj_caller.target.value = (document.cal
? obj_caller.gen_tsmp(dt_datetime)
: obj_caller.gen_date(dt_datetime)
);
submitFormWithAjax();
window.close();
}
else obj_caller.popup(dt_datetime.valueOf());
}
if (obj_caller && obj_caller.time_comp)
document.write('<form onsubmit="javascript:set_datetime('+dt_current.valueOf()+', true)"><tr><td colspan="7" bgcolor="#87CEFA"><font color="White" face="tahoma, verdana" size="2">Time: <input type="text" name="request_end" value="'+obj_caller.gen_time(this.dt_current)+'" size="8" maxlength="8"><INPUT TYPE="hidden" NAME="rsubmit" VALUE="Submit Request" ></font></td></tr></form>');
</script>
</table></tr></td>
</table>
</body>
</html>
Any ideas on how I can get this to submit the parent form with the date still being used?
Related
I have a form in which I need to call two action methods, one after the other. This is how the flow goes.
First I check if the prerequisite data is entered by the user. If not then I show a message that user needs to enter the data first.
If all the prerequisite data is entered, I call an action method which return data. If there is no data returned then I show a message "No data found" on the same page.
If data is returned then I call another action method present in a different controller, which returns a view with all the data, in a new tab.
The View:
#using (Ajax.BeginForm("Index", "OrderListItems", null, new AjaxOptions { OnBegin = "verifyRequiredData"}, new { #id = "formCreateOrderListReport", #target = "_blank" }))
{
//Contains controls and a button
}
The Script in this View:
function verifyRequiredData() {
if ($("#dtScheduledDate").val() == "") {
$('#dvValidationSummary').html("");
var errorMessage = "";
errorMessage = "<span>Please correct the following errors:</span><ul>";
errorMessage += "<li>Please enter Scheduled date</li>";
$('#dvValidationSummary').append(errorMessage);
$('#dvValidationSummary').removeClass('validation-summary-valid').addClass('validation-summary-errors');
return false;
}
else {
$('#dvValidationSummary').addClass('validation-summary-valid').removeClass('validation-summary-errors');
$('#dvValidationSummary').html("");
$.ajax({
type: "GET",
url: '#Url.Action("GetOrderListReport", "OrderList")',
data: {
ScheduledDate: $("#dtScheduledDate").val(),
Crews: $('#selAddCrewMembers').val(),
Priorities: $('#selPriority').val(),
ServiceTypes: $('#selServiceTypes').val(),
IsMeterInfoRequired: $('#chkPrintMeterInfo').val()
},
cache: false,
success: function (data) {
debugger;
if (data !== "No data found") {
//var newUrl = '#Url.Action("Index", "OrderListItems")';
//window.open(newUrl, '_blank');
return true;
} else {
//Show message "No data found"
return false;
}
}
});
return false;
}
}
The "GetOrderListReport" Action method in "OrderList" Controller:
public ActionResult GetOrderListReport(OrderListModel model)
{
var contract = new OrderReportDrilldownParamDataContract
{
ScheduledDate = model.ScheduledDate
//Setting other properties as well
};
var result = OrderDataModel.GetOrderList(contract);
if (string.IsNullOrWhiteSpace(result) || string.IsNullOrEmpty(result))
{
return Json("No data found", JsonRequestBehavior.AllowGet);
}
var deserializedData = SO.Core.ExtensionMethods.DeserializeObjectFromJson<OrderReportDrilldownDataContract>(result);
// send it to index method for list
TempData["DataContract"] = deserializedData;
return Json(deserializedData, JsonRequestBehavior.AllowGet);
}
The last action method present in OrderListItems Controller, the result of which needs to be shown in a new tab:
public ActionResult Index()
{
var deserializedData = TempData["DataContract"] as OrderReportDrilldownDataContract;
var model = new OrderListItemViewModel(deserializedData);
return View(model);
}
The problem is that I am not seeing this data in a new tab, although I have used #target = "_blank" in the Ajax.BeginForm. I have also tried to use window.open(newUrl, '_blank') as can be seen above. But still the result is not shown in a new tab.
Please assist as to where I am going wrong?
If you are using the Ajax.BeginForm you shouldn't also be doing an ajax post, as the unobtrusive ajax library will automatically perform an ajax post when submitting the form.
Also, if you use a view model with data annotation validations and client unobtrusive validations, then there would be no need for you to manually validate the data in the begin ajax callback as the form won't be submitted if any validation errors are found.
The only javascript code you need to add in this scenario is a piece of code for the ajax success callback. That will look as the one you currently have, but you need to take into account that opening in new tabs depends on the browser and user settings. It may even be considered as a pop-up by the browser and blocked, requiring the user intervention to allow them as in IE8. You can give it a try on this fiddle.
So this would be your model:
public class OrderListModel
{
[Required]
public DateTime ScheduledDate { get; set; }
//the other properties of the OrderListModel
}
The form will be posted using unobtrusive Ajax to the GetOrderListReport of the OrderList controller. On the sucess callback you will check for the response and when it is different from "No data found", you will then manually open the OrderListItems page on a new tab.
This would be your view:
#model someNamespace.OrderListModel
<script type="text/javascript">
function ViewOrderListItems(data){
debugger;
if (data !== "No data found") {
var newUrl = '#Url.Action("Index", "OrderListItems")';
//this will work or not depending on browser and user settings.
//passing _newtab may work in Firefox too.
window.open(newUrl, '_blank');
} else {
//Show message "No data found" somewhere in the current page
}
}
</script>
#using (Ajax.BeginForm("GetOrderListReport", "OrderList", null,
new AjaxOptions { OnSucces= "ViewOrderListItems"},
new { #id = "formCreateOrderListReport" }))
{
#Html.ValidationSummary(false)
//input and submit buttons
//for inputs, make sure to use the helpers like #Html.TextBoxFor(), #Html.CheckBoxFor(), etc
//so the unobtrusive validation attributes are added to your input elements.
//You may consider using #Html.ValidationMessageFor() so error messages are displayed next to the inputs instead in the validation summary
//Example:
<div>
#Html.LabelFor(m => m.ScheduledDate)
</div>
<div>
#Html.TextBoxFor(m => m.ScheduledDate, new {id = "dtScheduledDate"})
#Html.ValidationMessageFor(m => m.ScheduledDate)
</div>
<input type="submit" value="Get Report" />
}
With this in place, you should be able to post the data in the initial page using ajax. Then based on the response received you will open another window\tab (as mentioned, depending on browser and user settings this may be opened in a new window or even be blocked) with the second page content (OrderListItems).
Here's a skeleton of what I think you are trying to do. Note that window.open is a popup though and most user will have popups blocked.
<form id="formCreateOrderListReport">
<input type="text" vaule="testing" name="id" id="id"/>
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$('#formCreateOrderListReport').on('submit', function (event) {
$.ajax({
type: "POST",
url: '/home/test',
data: { id: $('#id').val()},
cache: false
}).done(function () {
debugger;
alert("success");
var newUrl = '/home/contact';
window.open(newUrl, '_blank');
}).fail(function () {
debugger;
alert("error");
});
return false;
});
</script>
Scale down the app to get the UI flow that you want then work with data.
I have 2 Form.Request in 2 functions that are executed on 2 different buttons clicks
here is fiddle
http://jsfiddle.net/RtxXe/38/
seems like I did not set the events in right order in my functions since they are mixing up the responses. if you hit Clear cache and than Send you still get response from clear cache and vice versa. Unless you reload the page and click again you cant get the right response for each button as it should be .
Since this is not my original form and *I can only change it with js * , i added the clear cache button with new Element. I cant figure out as to why is this happening and any help is appreciated.
this is original html:
<div id="toolbar">
<ul>
<li id="adminsubmit">Send</li>
</ul>
</div>
<div id="response"></div>
<form action="http://www.scoobydoo.com/cgi-bin/scoobysnack" method="post" name="editform" id="myform">
<fieldset>
<!-- form elements go here -->
</fieldset>
<input type="hidden" name="task" value="">
</form>
and here is js:
var AdminForm = {
start: function() {
var toolbar = $$('#toolbar ul');
var addbtn2 = new Element('li', {
'id': 'cache',
'class': 'button',
html: 'Clear Cache'
});
addbtn2.inject(toolbar[0], 'top');
var btn1 = $('adminsubmit').getElement('a');
var btn2 = $('cache').getElement('a');
btn1.addEvent('click', function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
AdminForm.formChange();
});
btn2.addEvent('click', function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
AdminForm.clearCache();
});
},
formChange: function() {
var adminform = $('myform');
var target = $('response');
var adminsend = new Form.Request(adminform, target, {
onSend: function() {
target.set('html', 'formChange sending');
},
onComplete: function() {
target.set('html', 'formChange sent');
}
});
adminsend.send();
},
clearCache: function() {
var adminform = $('myform');
var target = $('response');
var clearingcahe = new Form.Request(adminform, target, {
onSend: function() {
target.set('html', 'clearCache sending');
},
onComplete: function() {
target.set('html', 'clearCache sent');
}
});
clearingcahe.send();
}
}
window.addEvent('domready', AdminForm.start);
The Form.Request in Mootools inherits Class.Occlude, see http://mootools.net/docs/more/Class/Class.Occlude
But the Class.Occlude will prevent that several Objects are created and applied to the same DOM Element. That is, it works like a singleton, so the first time you do new Form.Request(adminform, ...) it will return a new instance of Form.Request.
However, the second time you call new Form.Request(adminform, ...) the previous object will be returned instead.
Your fiddle actually demonstrates this very good, because the first one that is clicked of "Clear Cache" or "Send" will be the one that initiates the object. The second time it will discard your options and just return the old object.
So there are two ways to solve this:
Create the Form.Request but don't set the event handlers through the options but through
adminsend.removeEvents('complete'); adminsend.addEvent('complete', ....)
Don't forget to remove the old event handlers before applying the new! otherwise you will just apply more and more eventhandlers.
There are two "buttons" so make two forms, which would be much more semantically correct as well.
ajax code:
try {
xmlhttp = new XMLHttpRequest();
}
catch(ee) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E) {
xmlhttp = false;
}
}
}
div_base = "";
valor = 0;
function abre(arquivo,metodo,div) {
div_base = div;
valor++;
xmlhttp.open(metodo,arquivo+"?valor="+valor);
xmlhttp.onreadystatechange=response
xmlhttp.send(null)
}
function response() {
nova_div = div_base;
document.getElementById(nova_div).innerHTML="<div>Loading...</div>"
if (xmlhttp.readyState==4) {
document.getElementById(nova_div).innerHTML=xmlhttp.responseText
}
}
html code:
<form>
<select name="menu" style="width:400px; height:25px;">
<option>Change Theme:</option>
<option></option>
<option onclick="javascript: abre('Chat_Themes/Default.html','GET','response2');">Default - Shadow Hunters</option>
<option onclick="javascript: abre('Chat_themes/Custom.html','GET','response2');">Custom - Shadow Hunters</option>
</select>
</form>
<br />
<div id="response2"></div>
i changed the "div = responce" to "div = responce2" without changing the ajax code at the top, im not sure if i have to change the ajax code or not or i can leave it and it works fine the way it is, but it does not work on google chrome idk if its just google chrome being retarded, but it works in ff and ie just fine, any thoughts?
Try indenting your code: you'll find that your try-catch statements don't have matching braces. You can also try a Javascript-validating service like jshint, but indenting should come first.
You might want to consider using a third-party library which already has cross-browser AJAX capability, like jQuery.
I have a save button (input button) that I have written javascript code to save the form data to the database. My jQuery .validate function doesn't run before I save the form. How can I manually execute my jQuery .validate function before I save. Here is what I am doing.
<input type="button" class="saveSubmit" name="action" value="Save" />
// Give user feedback when clicking save
$(".saveSubmit").click(function() {
if (save() == true) {
alert("Email has been saved.");
} else {
alert("Error saving email.");
};
return false;
});
// Validation
$("#emailForm").validate({
// rules here
});
Found it. I need to use $("#emailForm").valid().
As the title states my Ajax call is actually causing the form to be submitted to its default action, why? I've never come across this before, all my other ajax calls have never done this.
function newAjax(t,u){ //t = type(post/get), u = url
var resource = null;
if (window.ActiveXObject) {
resource = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
resource = new XMLHttpRequest();
resource.overrideMimeType('text/html');
}
resource.open(t,u,false);
resource.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
return resource;
}
function send_newsletter(){
formObj = document.getElementById("news_form");
var inputs = formObj.getElementsByTagName("INPUT");
var parameters = "";
for(i = 0; i < inputs.length; i++){
parameters += inputs[i].name+"="+encodeURI(inputs[i].value);
if(i != inputs.length-1){
parameters += "&";
}
}
var url = "whereitshouldbegoing.com";
var ajax = newAjax("POST",url);
ajax.onreadystatechange = ajaxResult;
ajax.setRequestHeader("Content-length", parameters.length);
ajax.setRequestHeader("Connection", "close");
ajax.send(parameters);
}
It all works fine upto the .send line, which is the bugger which is causing the form to submit aswell(I also have no idea if the ajax request actually gets off).
The send_newsletter function is called from an input type="image" element with onclick="send_newsletter()"
Please don't tell me to use jQuery or another library, as much as I would love to, we can't use any external librarys, corporate guidelines and whatnot.
An input of type "image" will behave the same as a submit button. Use an anchor or button type input to trigger your method.
<input type="button" onclick="send_newsletter()" value="Send" />
<button onlclick="send_newsletter()">... </button>
<img src="... />
Are you using a submit button to call send_newsletter?
onreadystatechange callback function 'ajaxResult' is not called because you're doing a synchronous call to the server:
resource.open(t,u,false);
if you want ajaxResult to be called change it to :
resource.open(t,u,true);
for now that's what I see. You have to provide more info like how do you call send_newsletter?
EDIT:(following author comment)
an INPUT of type image is a graphical submit button.