I am trying to show the details of each Student with Json and I think it is not going to the ajax part.
It shows the id and the url when I console.log() them, but I get this error message for the ajax part
I don't know what's missing or where is the issue?
This is my html link
#Html.ActionLink("Details", "StudentDetails", new { id = item.ID }, new { #class = "modalDetails", #id = item.ID })
script
<script type="text/javascript">
$(function () {
$(".modalDetails").click(function (e) {
e.preventDefault(); //stop the default action upon click
var id = $(this).attr('id');
console.log(id);
var url = $(this).attr("href");
console.log(url);
$.ajax({
type: 'GET',
data: { id: id },
dataType: "json",
url: url,
success: function (data) {
$(".modalDetails").append('<span> First Name: ' + data.firstName + '</span></br>');
console.log("success");
}
});
$('#myModal').modal('show'); // show the modal pop up
});
});
</script>
StudentController
public JsonResult StudentDetails(int id)
{
Student student = studentRepository.GetStudentByID(id);
var json = new{
firstName = student.FirstMidName
};
return Json(json, JsonRequestBehavior.AllowGet);
}
Everything was fine, except that I needed to build the solution and append the details to the modal-body. Sometimes it is just a simple fix.
Related
I have a like button on multiple posts, in EJS. Problem is, when I am clicking the first like button, the form sends and updates the View accordingly.
When I click the other buttons they all seem to send and update the first form, and they also update the first button adding the 'active' class to it.
I tried deleting the IDs and adding classes, still same result.
My guess is there is a fault in my AJAX or HTML structure because form is updating the database with no problem.
HTML:
<form id='like' action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST">
<% if (blogposts[i].liked == false) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
<% if (blogposts[i].liked == true) {%>
<div id='likeBtn' onclick="Like()" class="wrapperHearts active">
<svg xmlns="http://www.w3.org/2000/svg" id="Love"><path d="M28.124,15.5615,16.7549,28.6558a1,1,0,0,1-1.51,0L3.876,15.5615A7.6866,7.6866,0,0,1,2.57,7.61a7.1712,7.1712,0,0,1,6.085-4.5752C8.915,3.0122,9.1768,3,9.4424,3A8.6981,8.6981,0,0,1,16,6.0083,8.6981,8.6981,0,0,1,22.5576,3c.2656,0,.5274.0122.7862.0352A7.1713,7.1713,0,0,1,29.43,7.61,7.6866,7.6866,0,0,1,28.124,15.5615Z" style="fill:#212123"/></svg>
</div><%}%>
</form>
AJAX:
let likeButton = document.querySelector('.wrapperHearts');
let frm = $('#like');
function Like(){ frm.submit()}
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log("success");
console.log(data)
if (data.liked == false){
likeButton.classList.add('active')
$("#likesNumber").text(data.likes +1 + ' ' + 'Likes')
}
else{
likeButton.classList.remove('active')
$("#likesNumber").text(data.likes -1 + ' ' + 'Likes')
}
},
error: function(request, status, error) {
console.log("error")
}
});
});
In the form I am using method-override.
I have assigned the EJS dynamic ID to the rendered forms, and then I have created a function which triggered on event, gets the ID of the specific form and assigns it into the AJAX call.
HTML
<form class="likeForm" id="like<%=[i]%>" action="/postLike/<%=blogposts[i]._id%>?_method=PATCH" method="POST" onsubmit="postData(event, this.id)">
More details
var elem = $('#'+id)[0]; // I took the HTML form element in order to assign it to the new form data as seen below
var formData = new FormData(elem)
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
//Used the find() method in order to find the specific element that I want to be updated in real time.
AJAX
function postData(event, id) {
event.preventDefault(event)
var elem = $('#'+id)[0];
var fullDiv = $('#'+id)
var likeButton = fullDiv.find('.wrapperHearts')
var likesNumber = fullDiv.find('.likesNumber')
var currentUserId = <%-JSON.stringify(currentUser._id)%>
console.log(currentUserId)
var formData = new FormData(elem)
console.log(likeButton)
console.log(likesNumber)
$.ajax({
async: true,
type: elem.getAttribute("method"),
url: elem.getAttribute("action"),
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if(!data.userLikes.includes(currentUserId)){
likeButton.addClass('active')
likesNumber[0].innerHTML = data.likes + 1 + ' ' + 'Likes'
}
else{
likeButton.removeClass('active')
likesNumber[0].innerHTML = data.likes - 1 + ' ' + 'Likes'
}
}
})
}
I posted this yesterday but i may not have explained my situation well.
I have 3 grids on a page that are built dynamically through JavaScript.
I then have 3 separate JavaScript methods to set a session when a row is clicked in a certain grid.
Once the session is set i would like it to navigate to the next page.
Here is what i have
OnClick event
$('#clinician-planned').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetPASession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-recent').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetRDSession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-theatre').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetTESession", "Clinician")';
AjaxCall(Location, ID);
});
AJAX Post To Controller
function AjaxCall(Location, ID) {
alert('1');
$.ajax({
type: 'POST',
url: Location,
dataType: 'text',
async: false,
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).done(function (response) {
alert('2');
location.href = "#Url.Action("Summary", "Patient")" + "/" + ID;
});
}
Here are the controller methods
public ActionResult SetPASession()
{
Session.Remove("Clinician");
Session["Clinician"] = "pa";
return Json(null);
}
public ActionResult SetRDSession()
{
Session.Remove("Clinician");
Session["Clinician"] = "rd";
return Json(null);
}
public ActionResult SetTESession()
{
Session.Remove("Clinician");
Session["Clinician"] = "te";
return Json(null);
}
The problem i have is when the row is clicked "alert('1'); shows instantly, however it seems like it takes a while and waits for all grids to be populated before the 2nd alert appears. I have tried putting async: false, but this doesnt seem to work.
Any ideas would be much appreciated.
This is my Post function something like this:
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.NeighbourhoodId = data.id || "";
This is my simple function in knockout. Here at the last line u can see, data: ko.toJson(post)
self.addPost = function () {
var post = new Post();
post.Message(self.newMessage());
return $.ajax({
url: postApiUrl,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: ko.toJSON(post)
})
.done(function (result) {
self.posts.splice(0, 0, new Post(result));
self.newMessage('');
})
.fail(function () {
error('unable to add post');
});
}
Now, along with this, i want to pass dropdown selected id something like this:
data: { id: $("#Locations").val() }
Right now, i have tried using this:
data:{post: ko.toJSON(post), id: $("#Locations").val() }
but in controller, post: ko.toJSon(post) is sending nothing however i am getting id of selected dropdown but not the message property of post parameter.
If i use this line:
data: ko.toJSON(post)
then i can get every property of post parameter but then id is null so, how to deal with this.Plzz Plzz help me out.Debugger is showing nothing useful information.My Post Controller is:
public JsonResult PostPost(Post post, int? id)
{
post.PostedBy = User.Identity.GetUserId<int>();
post.NeighbourhoodId = id;
db.Posts.Add(post);
db.SaveChanges();
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
NeighbourhoodId = post.NeighbourhoodId
};
return Json( ret,JsonRequestBehavior.AllowGet);
}
on my view page,this is the button on which click event i fired addPost function
<input type="button" data-url="/Wall/SavePost" id="btnShare" value="Share" data-bind="click: addPost">
along with this, dropdown for sending id is something like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
<script type="text/javascript">
$(document).ready(function () {
$("#btnShare").click(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("PostPost", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
Plzz someone help me out.I am not getting what to do from here.
My Model has fields which are displayed on the screen, as well as a List which is displayed in a grid on the screen. I have an Add button, which shows a modal popup (without a postback), that allows the user to enter a few fields, and then clicks 'Save'. At the moment, I use a JSON call back to my controller to save the data. I then reload the screen, and the new item appears in the grid, as it was saved to the database, and the Model reloaded.
Problem is, if the user has made any changes to the main details in the model, they're lost, because all the JSON call did was save a new item to the database, and redirect to the main screen which reloads.
What I need to rather do is somehow, add the new item from the popup, to the main Model, and then reload the grid, without saving to the database at all, and without a postback.
My javascript for posting the data from the view looks like this:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmitNewCard').click(function () {
var data = { cardNumber: $('.txtNewCardNumber').val(), cardHolder: $('.txtNewCardHolder').val(), expiryMonth: $('.txtNewExpiryMonth').val(), expiryYear: $('.txtNewExpiryYear').val(), active: $('.txtNewActive').val(), accountId: $('.Id').val() };
$.ajax({
url: '#Url.Action("SaveBankCard", "BankAccount")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result.Success == 'true') {
window.location = '#Url.Action("EditBankAccount", "BankAccount", new { bankAccountId = Model.Id })';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no");
}
});
});
});
</script>
And then the controller method that handles this, looks like this:
public JsonResult SaveBankCard(string cardNumber, string cardHolder, int expiryMonth, int expiryYear, string active, int accountId)
{
var card = new AccountCardDto
{
Id = 0,
AccountId = accountId,
Active = active == "on",
CardHolderName = cardHolder,
CardNumber = cardNumber,
ExpiryDate = new DateTime(2000 + expiryYear, expiryMonth, 1)
};
var id = new BankAccountService().SaveCard(card);
var result = new { Success = "true", Message = "Saved", NewId = id };
var r = new JsonResult
{
Data = result
};
return r;
}
So, the data is saved in the controller, and then the Javascript redirects to roload the whole screen. Can this be changed to rather save the data to the models' List client side, and then the whole model with changes and additions get saved via the one Save button on my screen? Is it possible to add to the Model's List client side?
try json script like this
$('#ddlCompany').change(function () {
//var URL = $('#Enrollform').data('fetchproduct');
$.getJSON('/EnrollmentForm/fetchproduct/' + $('#ddlCompany').val(), function (data) {
var items = '<option>Select a Product</option>';
$.each(data, function (i, product) {
items += "<option value='" + product.Value + "'>" + product.Text + "_" + product.Value + "</option>";
});
$('#ddlProduct').html(items);
});
});
I want to pass the link on textbox blur function.
Jquery code
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a> */* this is the link for get the profile details*/*
<script type ="text/javascript">
$('#getCandidate').text('Get Profile') // Sets text for email.
.attr('href', '#');
$("#Email").blur(function () {
$('#checkEmail').trigger('click');
//$('#checkEmail').trigger('GetCandidateDetail?validateEmail=' + $('#Email').val());
$('#getCandidate').text('Get Profile')
.attr('href', 'GetCandidateDetail?validateEmail=' + $('#Email').val());
});
$(document).ready(function () {
$('#checkEmail').click(function () {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
Html code
<%: Html.TextBox("Email",Model.Email, new {#title="Enter the Candidate Email Id"})%>
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a>
In the above code when I type the email id in textbox it triggers email id is registered or not. Then I give one more link getdetails. If I click that link then the profile will come by using the link GetCandidateDetail?validateEmail=' + $('#Email').val()).
But Now I want when I type the email id in textbox, if exists means it will load the link GetCandidateDetail?validateEmail=' + $('#Email').val())automatically otherwise false. How to do this? Help me to come out this issue?
You can do just like this:
$(document).ready(function() {
$("#Email").on('blur', function() {
// Check mail on blur
var email = $(this).val();
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: {validateEmail:email},
success: function(data) {
// handle your response
}
});
});
});
function verify() {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
return false;
});
}
$("#Email").blur(function(){verify();)
$("#checkEmail").click(function(){verify()})
thats it !!