Dropdown selection change is not firing when the function contain ajax call. if the function contains only an alert, the function works.
Here is the code:
<div class="col-md-6">
<div class="form-group">
<label>Select Category</label>
#Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Categories, "CategoryId", "CategoryName", Model.CategoryId),
new { #class = "form-control select2", id = "myCategories" })
</div>
<div class="form-group" id="makes">
</div>
</div>
Here is the js function
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$(document.body).on('change', "#myCategories", function (event) {
var selected = $('#myCategories').val();
alert("catid changed to : " + selected);
$.ajax({
url : #Url.Action("getMakes","Transaction", new {categoryId= Model.CategoryId}),
success: function (data) {
alert(data);
$('#makes').html = data;
},
error: function () {
alert("failed");
}
});
});
});
</script>
}
If I comment the ajax block, it works and shows the alert. Anyone know why it is behaving like this?
Thanks to all those who helped me to fix this problem even though it is Christmas. Finally i got it working by putting single inverted comma before and after the url part in the ajax. Thanks #AnilTalla for the console clue. Here is the updated js
$(document).ready(function () {
$(document.body).on('change', "#myCategories", function (event) {
var selected = $('#myCategories').val();
alert("catid changed to : " + selected);
$.ajax({
url : '#Url.Action("getMakes","Transaction", new {categoryId= Model.CategoryId})',
success: function (data) {
alert(data);
$('#makes').html = data;
},
error: function () {
alert("failed");
}
});
});
});
Merry Christmas everyone.
Related
On my view page I have it where a user can click my 'Add Part' button to add the part they selected from the dropdown. This looks like this
<div id="Part" class="row">
<div class="col-md-2">
#Html.DropDownList("PartID", null, "-- Select --", htmlAttributes: new { #class = "form-control chosen-select Part-select" })
</div>
<div class="col-md-2">
<input type="button" value="Add Part" class="btn" onclick="add()"/>
</div>
</div>
As you can see it includes my button that should call my add() JavaScript function that looks like this
<script type="text/javascript">
function add() {
var token = $("input[name='__RequestVerificationToken']", "#__AjaxAntiForgeryForm").val();
var parts = [];
// Get all part ids and store them in arrays
var partssel = document.getElementsByClassName("Part-select");
for (i = 0; i < partssel.length; i++) {
parts[i] = partssel[i].options[partssel[i].selectedIndex].value;
}
alert("I am an alert box!");
$.ajax({
type: "POST",
url: "#IGT.baseUrl/JODetailsAjax/AddUnits",
traditional: true,
data: {
__RequestVerificationToken: token,
jo_id: #Model.Id,
addPart_id: parts
},
success: function (data) {
if (data.success === "False") {
var errorMessage = data.Message;
alert("Error: " + errorMessage);
return;
}
},
error: function (jqXHR, status, error) {
alert("Error:" + error);
}
});
}
</script>
I verified it's running the method as it hits the Alert, but when it goes through the AJAX section of it, it always returns the 'error' alert in the AJAX method instead of going to my POST Method in my controller. (I verified it's not hitting my POST method by putting a breakpoint at the beginning of it)
Here is what is showing in the network tab of my developer console
Why is this not working?
I'm looking for help about this subject.
I've got in my view 2 textbox.
I would like to get a value (generated in my controller) applied to textbox2 when there is an change on the textbox1.
For example I enter an username in textbox1 and textbox2 is the email address getting from controller (we can imagine that the controller check in a database or an active directory).
My code below seems not working:
In my View file I added an script section :
#section scripts{
<script type="text/javascript" language="javascript">
function ShowPersonalPanel(myChkboxPersonalLine) {
if (myChkboxPersonalLine.checked == false) {
$("#1-w").hide("fast");
}
else {
$("#1-w").show("fast");
}
}
</script>
<script language="javascript">
$("#1-w").hide("fast");
$('#myOtherGID').change(function () {
var myOtherGID = this.value;
$.getJSON("/PhoneController/GetEmailByGID",
{
strGID: myOtherGID
},
function (data) {
$('myOtherEmail').val(data);
});
});
</script>
}
And the code in the view with textbox:
<label for="myOtherGIDlbl">GID:</label>
<label class="text" id="myOtherGIDlbl">
#Html.TextBoxFor(model => model.myOtherGID)
</label>
<label for="myOtherEmaillbl">Email:</label>
<label class="text" id="myOtherEmaillbl">
#Html.TextBoxFor(model => model.myOtherEmail)
</label>
On my controller (named PhoneController) I added an action:
public JsonResult GetEmailByGID(string strGID)
{
string strEmailAddress = "this is my email";
return Json(strEmailAddress, JsonRequestBehavior.AllowGet);
}
As I work with an _layout.cshtml and an viewFile.cshtml, I added in the layout (in the head section) the line below:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
What did I miss?
Regards
I've found my issue.
I've changed my javascript to make an $.ajax command:
script type="text/javascript">
$('#myOtherGID').change(function () {
var selection = $('#myOtherGID').val();
if (selection.length > 0) {
var url = "/Phone/GetEmailByGID";
$.ajax({
type: "POST",
url: '#Url.Action("GetEmailByGID", "Phone")',
dataType: "json",
success: function(data, status) {
alert(data);
},
error: function() {
alert('error');
}
});
}
});
</script>
In the controller :
[HttpPost]
public ActionResult GetEmailByGID(string strGID)
{
string strEmailAddress = strEmailByGID(strGID);
return Json(strEmailAddress);
}
After testing, I can retrive data from my controler to my View without reloading all page.
in my index page i sent a request ajax and response is a number.and i set the response to the value of input with hidden type
<input type="hidden" id="Status">
<script src="js/indexPhone.js"></script>
<script>
$(document).ready(function() {
$("#SendPhone").click(function(e) {
var phoneField = $("#PhoneField").val();
var phoneFieldString = "989" + phoneField.substring(0);
$.ajax({
type:'post',
url:'getSMS.php',
data:{'phoneFieldString':phoneFieldString},
success:(function (response) {
$("#Status").val(response);
})
})
});
});
</script>
and my problem is i want to get this value in another javascript page that i included in my index but it alerts empty. this my indexPhone.js:
$("#SendPhone").click(function() {
alert($("#Status").val());
});
Ajax request is asynchronous, so the second click runs before value is set.
Use events:
// index.html
$("#SendPhone").click(function (e) {
// ...
$.ajax({
// ...
success: (function (response) {
$("#Status").val(response);
$("#Status").trigger("gotSMS");
})
});
});
// indexPhone.js
$("#Status").on("gotSMS", function () {
alert($(this).val());
});
I don't know what I am doing wrong here. but jquery validation is not working in partialview.
let me explain what I did
I am loading parial view from parent (It is not ajax load)
Parent
<div id="EmailInformationBlock" class="profileSection">
<div class="sectionTitle">
<span>Email</span>
</div>
<div id="DivEmailContainer" style="display:block">
#Html.Partial("_DisplayEmail", Model)
</div>
<hr />
</div>
Partial view
#using (Html.BeginForm(null, null, FormMethod.Get, new { name = "frmEmail", id = "frmEmail" }))
{
<td>#Html.Label("Email Location", new { #class = "control-label" })</td>
<td>
#Html.DropDownListFor(model => model.CommunicationLocation,
Enumerable.Empty<SelectListItem>(),"Select ",
new { #class = "input-validation-error form-control",
#name="CommunicationLocationEmail" }
)
}
</td>
}
<script type="text/javascript">
$(function () {
$.validator.addMethod("selectNone",
function (value, element) {
return this.optional(element) || element.selectedIndex != 0;
},
"Please select an option."
);
$("#frmEmail").validate({
rules: {
CommunicationLocation: {
selectNone: true
}
},
messages: {
CommunicationLocation: {
selectNone: "This field is required"
}
},
submitHandler: function (form) {
('#frmEmail').submit(function () {
$.ajax({
url: 'customer/PostEditEmail',
type: 'Post',
data: $(this).serialize(),
success: function (result) {
// $('#DivEmailContainer').html(result);
}
});
});
}
});
$.ajax({
url: "customer/GetCommunicationLocationList",
type: 'GET',
dataType:"json",
success: function(d) {
// states is your JSON array
var data = d.Data;
// alert(JSON.stringify(d.Data));
$.each(data, function (i) {
if (data[i].Description != "Bulk Dues"){
var optionhtml = '<option value="' +
data[i].Code + '">' + data[i].Description + '</option>';
$("#CommunicationLocation").append(optionhtml);
}
});
},
error: function (xhr) { alert("Something seems Wrong"); }
});
});
</script>
After I submit form is redirecting to new url. It shouldn't go to any url.
what I am doing wrong here.
I might be wrong, but it looks like jquery is not aware that the partial view has any validation because it is loaded from a parent view.
Try reparsing the DOM by adding the following to your partial view
$(function(){
jQuery.validator.unobtrusive.parse();
jQuery.validator.unobtrusive.parse("#frmEmail");
});
and this to you parent view
$(function(){
$("#submitButtonId").click(function(){
if (!$("#frmEmail").valid()){
return false;
}
});
});
You effectively have ajax within a submit within a submit...
submitHandler: function (form) {
('#frmEmail').submit(function () {
$.ajax({
....
});
});
}
You forgot the $ in front of the ('#frmEmail') selector, which breaks everything inside the submitHandler, but that's not really the core issue here.
After I submit form is redirecting to new url.
You do not need to put .ajax() within a .submit() handler when you're already inside of the plugin's submitHandler function. That's the whole point of the submitHandler option... to replace the default submit handler of the form.
This is all you'd need....
submitHandler: function (form) {
$.ajax({
url: 'customer/PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
// $('#DivEmailContainer').html(result);
}
});
return false;
}
Also note that $(this).serialize is replaced with $(form).serialize() since this is meaningless inside the context of the submitHandler. The form argument is already passed into this function by the developer to represent the form object.
If you're using the unobtrusive-validation plugin, then you cannot call .validate() yourself since unobtrusive already handles it for you. In other words, the jQuery Validate plugin only pays attention to first time the .validate() method is called, so if your instance is subsequent, then it's ignored along with your options.
I'm making hover card on click for every users so i did for one and its working but i want this to work on every user like i have given them unique title and based on that the server will get the data of that particular users but the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong) so i tried to do this on ajax cache: false but didn't help then i tried return false;, return data; still not use.
So, here is the users links example :
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
Ajax :
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
var data = 'vall=' + get_val + '';
$.ajax({
type: 'POST',
url: 'xx.php',
data: data,
success: function (data) {
box.dialog({
message: data
});
return false;
}
});
});
});
I would do it this way.
HTML
<div class='links'>
<a title="user101" href="#">John</a>
<a title="user102" href="#">Tonya</a>
</div>
JS
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.links').on('click', 'a', function (event) {
event.preventDefault();
var get_val = $(this).prop('title');
$.ajax({
type: 'POST',
url: 'xx.php',
data: {vall: get_val},
success: function (data) {
box.dialog({
message: data
});
}
});
});
});
the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong)
you are wrong.. only 1 links is working beacuse you have same id for multiple elements.. each elements should have unique id.
use class instead
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
and a class selector and return false after ajax success callback function , at the end
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
....
$.ajax({
....
success:function(){
....
}
});
return false;
..
or simply use preventDefault() instead of return false
$('.hover').click(function (e) {
e.preventDefault();
var get_val = $('.hover').attr('title');
.....