ajax helpers in mvc call non-asynchronously - asp.net-mvc-3

I am developing in asp.net mvc and today I saw some strange thing in using ajax helpers.
If I use Ajax.BeginForm(...) or Ajax.ActionLink(...), they do not call (post to) the actions asynchronously, and they work as they are normal form or normal link, but when I check Request.IsAjaxRequest() in action, it returns true.
For ajax forms, I use
$('#createqfrm').submit(function () {...}
and it works fine, and send the form asynchronously.
Note: I know I have to change .live() to .on() in jquery.unobtrusive-ajax.min since new versions of jquery.
also here are my referenced java libs:
<script src="#Url.Content("~/Scripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Edited:
Checking Request.IsAjaxRequest() and saw that it returns false.
Action Code Added:
public ActionResult GetStriing()
{
if (Request.IsAjaxRequest())
{
return Json("ajax called",JsonRequestBehavior.AllowGet);
}
else
{
return Json("ajax not called", JsonRequestBehavior.AllowGet);
}
}
part of html code for form:
<form action="/admin/xxxx/create" data-ajax="true" data-ajax-success="handeCreateQuestionnareSuccess" id="form0" method="post"> <div class="editor-label">
<label for="Title">title</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-required="*" id="Title" name="Title" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="Status">Status</label>
</div>
....
<script type="text/javascript">
function handeCreateQuestionnareSuccess(context) {
debugger;
if (context) {
$("#CreateQuestionnarieform").empty().html(context[1]);
$("#CreateQuestionnarieform").append('<input type=hidden name=questionnarieid value=' + context[2] + '/>');
} else {
$("#CreateQuestionnarieform").empty().html(context[1]);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
}
}
</script>
Code that submits form with ajax call:
$('#createqfrm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (context) {
}
});
}
return false;
});
not a solution but can notify other users:
The problem is with jquery 1.9.0 and updates that I get from nuget for jquery.validate.min.js and jquery.validate.unobtrusive.min.js I changed back to 1.8.3 and it works fine.....

Well that sounds like UnobtrusiveJavaScriptEnabled is set to false. Have a look in your AppSettings-File. In section <appsettings> there should be:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
EDIT:
Just found this link after a minute of googling:
http://forums.asp.net/t/1877166.aspx/1?jquery+unobtrusive+ajax+js+error+with+jQuery+1+9+0+updated
Unobtrusive Ajax stopped working after update jQuery to 1.9.0

Related

Unable to Programmatically invoke the invisible recaptcha challenge by ID

We have a set up with multiple forms on a single page. We are rendering each recaptcha successfully, however I'm struggling to invoke the recaptcha challenge programatically targeted to an ID.
Looking at the docs (https://developers.google.com/recaptcha/docs/invisible#programmatic_execute) my understanding is that I can pass an ID with the execute command so the response is filled into g-response within the correct form, otherwise the response defaults to the first g-response it finds on the page (which is no good for anything other than the first form on the page).
I've tried it with a slightly modified version of Googles own example, however we get the error message 'Invalid site key or not loaded in api.js: recaptcha123' even though the key is correct.
Does anyone have any idea how we might get this working?
<html>
<head>
<script>
function onSubmit(token) {
alert('thanks ' + document.getElementById('field').value);
}
function validate(event) {
event.preventDefault();
if (!document.getElementById('field').value) {
alert("You must add text to the required field");
} else {
grecaptcha.execute('recaptcha123');
}
}
function onload() {
var element = document.getElementById('submit');
element.onclick = validate;
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form>
Name: (required) <input id="field" name="field">
<div id="recaptcha123" class="g-recaptcha"
data-sitekey="XXXXXXXXXXXXXXXX"
data-callback="onSubmit"
data-size="invisible"></div>
<button id="submit">submit</button>
</form>
<script>onload();</script>
</body>
</html>
The following code works:
<html>
<head>
<title>reCAPTCHA demo: Explicit render after an onload callback</title>
<script>
var onSubmit = function(token) {
console.log('success!');
};
var onloadCallback = function() {
widgetId1 = grecaptcha.render('recaptcha', {
'sitekey' : 'XXXXXXXXXXXXXXXXXX',
'callback' : onSubmit
});
};
</script>
</head>
<body>
<script src="/wp-content/themes/kc_water_care_services/js/pristine.min.js"></script>
<form action="?" method="POST" id="contactForm">
<div class="form-group">
<label for="name">Name (required)</label>
<input type="text" required data-pristine-required-message="Please enter your name"
id="name" name="name" />
</div><!--/.form-group-->
<div id="recaptcha" data-size="invisible"></div>
<input id="submit" type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer>
</script>
</body>
</html>
<script>
var form = document.getElementById("contactForm");
// create the pristine instance
var pristine = new Pristine(form);
form.addEventListener('submit', function (event) {
event.preventDefault();
// check if the form is valid
var valid = pristine.validate(); // returns true or false
if(valid == true){
grecaptcha.execute(widgetId1);
}
});
</script>
Turns out the id doesn't refer to the css ID, it refers to an ID created when you use the render function.

ajax form does not submit

I can't get this form to submit via Ajax to a PHP script and cannot figure out why. Please help. I am planning to use this in phone gap after development and was under the impression this ajax format would work better than xmlhttprequest method - is this really the case?
<html>
<head>
<title></title>
</head>
<body>
<h1>Welcome</h1>
<hr>
<form id="idForm" name="idForm">
<input type="text" size="8" id="date" name="date"><br>
<input type="hidden" size="8" id="reversedate" name="reversedate"><br>
<input type="hidden" size="1" id="dow" name="dow"><br>
<input type="submit" id="submitbutton" name="submitbutton">
</form>
<br><br><br>
<br>
<br>
<p id="p1">x</p>
<br>
log out
<script>
$('#submitbutton').click(function(){
$("#idForm").submit(function() {
var url = "fetchsimple.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/ui.js"></script>
</body>
</html>

POST an Ajax form from a Kendo UI window

To edit a record, I'm opening a modal Kendo UI window populated with a partial view containing an AJAX enabled form:
#model MVC_ACME_Hardware.Models.BaseModel
<script type="text/javascript">
$(function () {
$("form").kendoValidator();
});
</script>
#using (Ajax.BeginForm("EditProduct", new AjaxOptions { UpdateTargetId = "ProductDiv", OnSuccess = "SomeMethod" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeFTE</legend>
#Html.HiddenFor(model => model.Products.Product_ID)
<div class="editor-label">
#Html.LabelFor(model => model.Products.Product_Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Products.Product_Name)
#Html.ValidationMessageFor(model => model.Products.Product_Name)
</div>
<input type="submit" value="Save" class="myButton" />
</fieldset>
}
When I run the form and click 'Save' on the popup, the form posts successfully but the post is not done via AJAX and my 'SomeMethod' onsuccess method is not being called. I've tried adding...
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
...on the partial view but it did not help. How can I get my form to submit using AJAX? I'm missing something obvious. Thanks!
try something like this (attention to the input type):
<input type="button" value="Save" class="myButton" id="btnSave" />
and the in the $(document).ready() :
var validator = $(document.forms[0]).kendoValidator().data("kendoValidator");
$("#btnSave").click(function(e) {
if (validator.validate()) {
var formContent = $(document.forms[0]).serialize();
var url = $(document.forms[0]).action;
$.post(url, formContent).done(function(data) {
$(document.body).append("<div class='savedRecordMessage'>success</div>");
});
}
});
I think you need to add these files if you want to use unobtrusive validation of MVC and Ajax options of AJAX form.
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

ajax form input file upload loading a separate page in codeigniter

I am using
<script src="http://malsup.github.com/jquery.form.js"></script>
for my ajax form upload.
When I upload file without the Codeigniter framework this works fine. But when I used it within the frame work it shows me the following error :-
HTTP wrapper does not support writeable connections
plus it is actually loading a separate page
Here's my code :-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
clearForm: true,
resetForm: true
};
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
//alert("Thank you for your comment!");
});
$('#myForm').ajaxForm(options);
});
</script>
</head>
<body>
<form id="myForm" name="myForm" action="comment.php" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<br />
<textarea name="comment"></textarea>
<br />
<input type="file" value="Share a Pic" name="file" id="file" />
<br />
<input type="submit" value="Submit Comment" />
</form>
</body>
For Codeigniter I changed the action to
site/submit_myform
So it loads site/submit_myform. Site being my controller. other values are being stored in the database
Thanks
The ajax part isn't working if the page is redirecting. You need to return false; during the on submit to prevent the page from redirecting.
I would suggest following the ajaxSubmit()example provided in the form plugin.

Ajax form with jquery validation

I can't make heads or tails of this and am wondering if you could help! When I click on the button, nothing happens. Ideally, I would like the form to validate before submission and to prevent submission if it doesn't validate.
<script type="text/javascript" src="../assets/js/validate/jquery.validate.min.js">
</script>
<script type="text/javascript" src="../assets/js/validate/jquery.validate.more.js">
</script>
<script type="text/javascript" language="javascript">
var J = jQuery.noConflict();
J(document).ready(function(){
J("form#nameform").validate({
rules: {
"name": {
required: true,
format: true},
},
submitHandler: function() {
J.ajax({
type: "POST",
url: "process.php",
data: J("form#nameform").serialize(),
success: function(html) {
J('form#nameform').html('hello');
}
});
};
});
});
</script>
<div id="name">
<form id="nameform" method="post">
<input id="name" class="text" name="name" size="20" type="text">
<input type="submit" value="go" />
</form>
</div>
A lot of tutorial to make Jquery Form valitation, they show how to make ajax validation too :)

Resources