How to send parameters to Action from javascript function? - javascript

I have a simple view that show a table of data, I want to sort one of its columns when the header is clicked by AJAX, I'm new to AJAX and JS, so this was my try in the view:
<table id="tbl" class="table">
<tr>
<th>
<a style="cursor: pointer" onclick="getData('desc')" id="sort">Title</a>
</th>
<th>
Author
</th>
<th></th>
</tr>
</table>
#section scripts{
<script type="text/javascript">
$(document).ready(getData('asc'))
function getData(sort) {
var srt = sort;
$.ajax({
type: 'GET',
url: '/Book/BooksData/' + srt,
dataTtype: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
}
</script>
}
but when I click the header the sort parameter goes null in the action,
public JsonResult BooksData(string sort)
{
var books = new List<Book>();
if (sort == "asc") books = db.Books.Include(b => b.Author).OrderBy(b => b.Title).ToList();
else books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title).ToList();
return Json(books, JsonRequestBehavior.AllowGet);
}
Yes I'm doing it wrong, but I revised it many times, I can't see logical error except that passing parameters in JavaScript is different than C#

Here is the simpliest way.You need to concatenate sort value to url, using query string.
Now, when you click header the sort parameter must goes with your value in the action.
Please try this:
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataType: 'json',
success: function (data) {
$("#tbl > tr").remove();
$.each(data, function (index, val) {
$('#tbl').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
Another way is to use this:
url: '#Url.Action("BooksData","Book")?sort=' + srt
The #Url.Action returns just a string.
In Razor every content using a # block is automatically HTML encoded by Razor.

Related

How to access id of the modal globally using JavaScript Laravel Laravel

I'm have an html table with modal column (see image below for your reference)
Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)
I wanted to access and used it in my Add function using ajax but I'm having an error of "customer_id is not defined" when I tried to use it. Is there a way to fix it or do it properly.
This is my script
<script>
$(document).ready(function () {
// START OPEN CART MODAL FUNCTION
$(document).on('click', '.viewCart', function (e) {
e.preventDefault();
var customer_id = 0;
var customer_id = $(this).val();
console.log(customer_id);
$.ajax({
type: "GET",
url: "/get-cart/"+customer_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr>\
<td>' + item.p_name + '</td>\
<td>' + item.c_qty + '</td>\
<td class="total">' + item.p_amt + '</td>\
<td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>\
\</tr>');
});
}
}
});
});
// END OPEN CART MODAL FUNCTION
// START ADD DATA FUNCTION
$(document).on('click', '.addToCart', function (e) {
e.preventDefault();
var data = {
'store': $('.sel_store').val(),
'product': $('.sel_product').val(),
'quantity': $('.sel_qty').val(),
// HOW TO INPUT Customer ID here, I tried this but im having an error of
// customer_id is not defined
'customer_id': customer_id,
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/cart-list",
data: data,
dataType: "json",
success: function (response) {
}
});
});
// END ADD DATA FUNCTION
});
</script>

How to get my dynamically created div to show up on page after ajax call

I have a project that I am trying to implement with jquery. I have an add button, so everytime it is clicked, it will create a new record on in my database. I am trying to figure out how to get my ajax call to recognize the new data and display it on the screen, without me having to manually refresh the screen, I was hoping to just use fadeIn or something similar to only show my new div.
This is for a checklist system,so someone can edit a checklist by adding steps on the fly and reorder existing steps
I wrote a loadData function to loop through my records and append the appropriate data, but not sure how to auto refresh my div when someone adds a new step. I don't want to reload the entire page, only the newly created div.
$(function() {
loadData();
});
// drag and drop steps and update the database
$('#steps').sortable({
update: function(event, ui) {
var data = $(this).sortable('serialize');
data = data + '&id=' + json.IDchecklist + '&ver=' + json.Version;
$.ajax({
data: data,
type: 'POST',
url: '../Processes/Reorder.php',
success: (function() {})
});
}
});
//load data
function loadData() {
$.ajax({
url: '../json/test.php',
type: 'GET',
dataType: 'json',
success: function(data) {
json = data
$('#details').find('h2').html(data.IDchecklist);
$('#details').find('h4').html(data.Status);
$.each(data, function(k, v) {
if (k == "Steps") {
count = 1;
$.each(v, function(key, value) {
$('#steps').append('<span>' + count + '</span><div id=step' + value.IDstep + '>' + value.StepText + '</div>');
count++;
text[count] = value.StepText;
})
}
})
}
})
}
//add new step
$('#add').click(function() {
console.log(count);
div = $('#step-' + count);
$.ajax({
type: 'POST',
data: {
id: json.IDchecklist,
ver: json.Version,
step: count
},
url: '../processes/addStep.php',
success: (function() {
div.fadeIn('fast')
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div class="jumbotron"></div>
<div id="details">
<h2></h2>
<h4></h4>
</div>
<div id="steps">
</div>
<button id=add value="Add">Add</button>

AJAX couldn't remove the DOM data

I have a dropdown selection where the user can select a name and related data will be loaded with the selection. Everything works fine except it always keeps the first data after the second or third selection. How do I remove the first selected data's when I am selecting a value the second time?
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Course Code</td>
<td>Name</td>
<td>Grade</td>
</tr>
</thead>
</table>
<script type="text/javascript">
$('#student').on('change', function(e) {
$('#example tr:last').remove().end();
var std_id = $('#student option:selected').attr('value');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{url('ajax-student-result')}}",
data: {
std_id: std_id
},
success: function(data) {
$.each(data, function(index, subcatObj) {
$('#example tr:last').after('<tr><td id="code">' + subcatObj.c_code + '</td><td id="course_name">' + subcatObj.c_name + '</td><td id="grade">' + subcatObj.grade + '</td></tr>');
});
}
});
});
</script>
I guess you are using Symfony and Twig.
I think a CSRF token is to be used only once so if you don't renew your csrf token for each ajax post request it may be the reason why it works only once.
Edit : Found this question which might help you :
Generate new CSRF token without reloading the entire form
Change the code to include removal:
success: function(data) {
$('#example tr:last')remove();
$.each(data, function(index, subcatObj) {
$('#example tr:last').after('<tr><td id="code">' + subcatObj.c_code + '</td><td id="course_name">' + subcatObj.c_name + '</td><td id="grade">' + subcatObj.grade + '</td></tr>');
});
}

How to update an HTML table through AJAX call?

Guys I have a html table in my ASP.net MVC home view. Now the table is being filled initially through the data present in model. Now upon clicking certain buttons on the homepage, I want to update the data present in the table i.e. clear the data present in the table and update it with the one from ajax call.
This is my table from view :
<article class="scrlable">
<table>
<tr>
<td>#</td>
<td>Name</td>
<td>Status</td>
<td>Since</td>
</tr>
#{
int srno = 1;
foreach (var pendingResponseModel in Model.hrPendingResponseList)
{
<tr>
<td>#srno</td>
<td>#pendingResponseModel.CandidateName</td>
<td>#pendingResponseModel.CandidateLifeCycleStatusName</td>
#if (pendingResponseModel.DayDifference == "1")
{
<td>#(pendingResponseModel.DayDifference) day</td>
}
else
{
<td>#(pendingResponseModel.DayDifference) days</td>
}
</tr>
srno++;
}
}
</table>
</article>
And this is my ajax call :
function GetStatusWise(control, departCode) {
$.ajax(
{
type: "GET",
url: "...URL..." + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data.data, function (index, value) {
// UPDATE TABLE HERE...
});
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
}
The data returned from ajax call is in JSON. It has Name, Status and Since elements. They can be viewed by using value.CandidateName, value.Status etc
Now I want to update the values of above table with the values I am getting through AJAX call. How would I go about doing that? Is it possible to replace the whole article ?
Note : I am getting multiple values through ajax call so that is why I put a loop on the function.
I have solved my problem by the following code
function GetStatusWise(control, departCode) {
$.ajax(
{
type: "GET",
url: WebApiURL + ".....URL...." + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
var srno = 1;
$('#tblPendingHrResponse').find($('.trTblPendingHrResponse')).remove();
$.each(data.data, function (index, value) {
random(value, srno);
srno++;
});
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
}
.
function random(values, srno) {
var daydifference = values.DayDifference == 1 ? '<td>' + values.DayDifference + ' day </td>' : '<td>' + values.DayDifference + ' days </td>';
var tr = '<tr class="trTblPendingHrResponse">' +
'<td>' + srno + '</td>' +
'<td>' + values.CandidateName + '</td>' +
'<td>' + values.CandidateLifeCycleStatusName + '</td>' +
daydifference + '</tr>' + srno++;
$('#tblPendingHrResponse').append(tr);
}
You can use jQuery append.
success: function (data) {
$.each(data.data, function (index, value) {
$("table").html("Your HTML to updated");
});
},
Have your controller method return a partial which contains your table or article.
[HttpPost]
public virtual ActionResult GetTable(ArticleViewModel viewModel)
{
// do stuff
return PartialView("_ArticleTable", viewModel);
}
Then update the table or article in jQuery:
ou can use jQuery append.
success: function (data) {
$("table").html(data);
},

Using Jquery inside of Razor

I'm trying to pass a string from javascript to a razor ActionLink
string filtering =$("#Hello").val();
#Html.ActionLink(Name, ControllerName, new { sort = columm, order = orderby, filters = filtering })
but I'm not able to access to this variable, I already try #:filtering or "#filtering" but doesn't work anyway,
How can I pass the variable to the controller?
If you want to send or post the data to Controller's Action then you may try this...
<input type="submit" id="btnFilter" value="Filter" name="btnFilter" />
$('#btnFilter').click(function () {
var sort = sortValue;
var order = orderValue;
var filter= filterValue;
$.ajax({
type: 'POST',
url: '#Url.Action(ActionName, ControllerName)',
data:'{"sort":"' + sort+ '","order":"' + order+ '","filter":"' + filter+ '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
},
error: function () {
}
});
});
then.... in controller action
public ActionResult ActionName(string sort ,string order , string filter)
{
// do Something here....
}
You'd have to add the parameter to the URL yourself manually using jQuery to assign the href attribute of the anchor tag.
First, let's take off the filter parameter off your ActionLink and give it an ID (so we can reference it in jQUery):
#Html.ActionLink(Name, Controller, new { sort = columm, order = orderby }, new { id = "myLink" })
Then do the following jQuery:
$(function () {
var newLink = $("#myLink").attr("href") + "?filter= " + $("#Hello").val();
$("#myLink").attr("href", newLink);
});
the way that I could do it was passing the Url to the controller
window.location = window.location.protocol + "//" + location.host + "/Name/Controller/" + "?sort=sort" + "&order=order" + "&page=page" + "&filters=" + filter;

Categories

Resources