I have the following js code:
function getSelectedPlace(form) {
var places = 1
$(form).find(":input").each(function () {
if ($(this).attr("name") === "Signed_Order_B64") {
$.ajax({
type: 'POST',
url: '/MyController/MyAction',
data: "id=" + places,
success: function (response) {
if (response.Result) {
ret = response.Message;
result = true;
$("input[type=hidden][name=email]").val(response.Email);
$("input[type=hidden][name=appendix]").val(response.Appendix);
} else {
// show fancybox
result = false;
}
},
error: function () {
result = false;
},
async: false
});
$(this).val(ret);
}
});
if (!result) {
$(submitButton).attr("value", btnText);
setStateFotBuyButton(false);
}
return result;
}
I have if statement in success block. I want show partial view in the fancybox in else block. How can I do this? Thanks
Not totally sure what you mean with "partial view" but you could do
} else {
$.fancybox(response,{
// fancybox options here
}); // fancybox
}
You could use the content switch which allows you to set the content of the fancybox to any html:
$.fancybox({
content: response
});
Related
I am tearing my hair out with this...!
I have a telerik kendo mvc ui grid widget using an Inline gridedit mode. When the user adds a new entry to the grid (by way of a custom dropdown edit control), I want it to validate that this entry is not already present in the grid.
I have an MVC controller action that does this and returns True or False accordingly. This works perfectly. Here is the validator javascript code I am using.
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: {
bedQuantity: function (input, params) {
if (input.is("[name='Quantity']") && input.val() <= 0) {
input.attr("data-bedQuantity-msg", "Quantity must be 1 or more");
return false;
}
return true;
},
bedExists: function(input, params) {
if (input.is("[name='BedType']")) {
var model = {
PropertyId: #Model.Id,
BedTypeId: input.val()
};
var url = "/Property/ValidateBedTypeExists";
input.attr("data-val-bedExists-requested", true);
$.ajax({
type: "POST",
url: url,
traditional: true,
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
success: function(data) {
return data === false;
},
fail: function(data) {
return false;
}
});
} else {
return true;
}
}
},
messages: {
bedQuantity: function (input) {
return input.attr("data-val-bedQuantity");
},
bedExists: function(input) {
return "This bed type already exists";
}
}
});
})(jQuery, kendo);
No matter whether the ajax call returns true or false, the validator always flags the entry as invalid.
You can give the html attribute for the kendoDropdownList as required like this
#(Html.Kendo().DropDownList()
.DataValueField("")
.DataTextField("")
.Name("")
.HtmlAttributes(new { required ="required" })
.OptionLabel("- Select a type - ")
.Filter(FilterType.Contains)
)
Try this..
I managed to make this code to submit a form, it works fine, but I can not implement a validator does not need it, but it shows no message just does not send the form is empty.
I searched but could not quite do it. Can anyone help me?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#newsletter').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "newsletter_cadastrar.asp?f=1",
data: dados,
success: function( data )
{
$('#resultado-form-newsletter').html(data);
}
});
return false;
});
});
</script>
<input id="nomenewslbase" name="nomenewslbase" type="text">
<input id="emailnewslbase" name="emailnewslbase" type="email">
Thank you for your attention.
If you are looking for applying jquery validation rules then you can do it like:
<script type="text/javascript">
function ValidationRules() {
}
ValidationRules.prototype.initializeSaveValidators = function() {
jQuery.validator.addMethod("csProjectName",
function(value, element) {
if ($.trim($('#txtProjectName').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
} else
return true;
}, "Project Name is required");
jQuery.validator.addMethod("csDescription",
function (value, element) {
if ($.trim($('#txtDescription').val()) == "") {
if ($.trim($(element).val()) != '')
return true;
else
return false;
}
else
return true;
}, "Description is required");
};
ValidationRules.prototype.enableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: true };
jQuery.validator.classRuleSettings.csDescription = { csDescription: true };
};
ValidationRules.prototype.disableSaveValidators = function () {
jQuery.validator.classRuleSettings.csProjectName = { csProjectName: false };
jQuery.validator.classRuleSettings.csDescription = { csDescription: false };
};
jQuery(document).ready(function () {
var validationRules = new ValidationRules();
validationRules.initializeSaveValidators();
validationRules.enableSaveValidators();
$("#btnsubmit").click(function () {
applyjQueryValidation();
return false;
});
});
function applyjQueryValidation() {
var isValid = $('#newsletter').valid();
//here you can manually check for some extra validations
if (isValid==true) {
alert("valid");
//here is you ajax call
}else{
alert("invalid");
}
}
</script>
Also, you need to include jquery.validate.js
Here is the JSfiddle working example.
I want to validate my course name field if the course name inputted already exist using AJAX, but my ajax function always return the alert('Already exist') even if i inputted data that not yet in the database. Please help. Here is my code. Thanks.
View:
<script type="text/javascript">
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData= {
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/courses/check_course_name_existence",
data: postData,
success: function(msg)
{
if(msg == 0)
{
alert('Already Exist!');
return false;
}
else
{
alert('Available');
return false;
}
return false;
}
});
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
}
</script>
Controller:
function check_course_name_existence()
{
$course_name = $this->input->post('course_name');
$result = $this->course_booking_model->check_course_name_exist($course_name);
if ($result)
{
return true;
}
else
{
return false;
}
}
Model:
function check_course_name_exist($course_name)
{
$this->db->where("course_name",$course_name);
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
You could use console.log() function from firebug. This way you will know exactly what the ajax returns. Example:
success: function(msg) {
console.log(msg);
}
This way you also know the type of the result variable.
jQuery, and Javascript generally, does not have access to the Boolean values that the PHP functions are returning. So either they return TRUE or FALSE does not make any difference for the JS part of your code.
You should try to echo something in your controller and then make your Javascript comparison based on that value.
I cannot figure out how to merge the following separate pieces of code:
$(document).ready(function () {
$("#signupForm").validate();
});
and
$(document).ready(function () {
$("#btnSignup").click(function () {
$.ajax({
type: "POST",
dataType: 'json',
url: "/Newsletter/Signup",
data: $('#signupForm').serialize(),
success: function (response) {
if (response.success) {
$('#signupMessage').show(0);
}
else {
showValidationErrors(response.Data);
}
}
});
return false;
});
I need the first part to execute first, and if it validates the form successfully, then I need to exectute the second part.
I believe that you can use valid().
Pseudo code;
$(document).ready(function () {
$("#signupForm").validate();
$("#btnSignup").click(function () {
if ($("#signupForm").valid()) {
// ajax query
}
return false;
});
});
Does that work? I haven't checked it.
Here is a somewhat general way I use.
$('form').submit(function(e){
if (!$(e.target) && !$(e.target).valid()) {
return;
}
// Ajax call here.
$.ajax({ type: "POST",... });
});
Lastly, you could abstract the logic into an object for a more OOP approach
var formHandler = {
onSubmit: function(e){
if (!$(e.target) && !$(e.target).valid()) {
return;
}
// Ajax call here.
$.ajax({ type: "POST",... });
}
}
$('form').submit(formHandler.onSubmit);
the form is submiting as normal request instead of Ajax.
$(document).ready(function () {
StatusComments();
});
function StatusComments() {
$('.comment').submit(function () {
$(this).ajaxSubmit(options);
return false;
});
var options = {
beforeSubmit: showRequest,
success: showResponse,
resetForm: true
};
function showRequest(formData, jqForm, options) {
var textbox = $('#StatusMessageReplyMessage').val();
alert(textbox);
}
function showResponse(responseText, statusText, xhr, $form) {
}
}
i have a similar one for Status update like this
function StatusUpdates() {
$('#updateStatus').submit(function () {
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
var options = {
target: '.user-status',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse,
// post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
function showRequest(formData, jqForm, options) {
var textbox = $('#StatusMessageMessage').val();
if ((textbox == '') || (textbox == "What have you been eating ?")) {
alert('Please Enter Something and click submit.');
return false;
} else {
$('#StatusMessageMessage').attr('disabled', true);
}
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
$('.share').slideUp("fast");
$('#StatusMessageMessage').animate({
"height": "18px"
}, "fast");
}
}
Instead of
$('.comment').submit(function () {
$(this).ajaxSubmit(options);
return false;
});
Try
$('.comment').click(function(e) {
e.preventDefault();
$(this).ajaxSubmit(options);
return false;
});