What I usually do is grab the data from the repository and pass that data along to the view via addAttribute, like this:
#GetMapping("html_page")
public String dynamicPage(Model model){
List<MySqlDataDTO> mySqlDataDTO = mySqlRepository.findAllByName(name);
model.addAttribute("mySqlDataDTO", mySqlDataDTO);
return "html_page";
}
Then use thymeleaf to loop through the data and display it in a table, like this:
<table id="table" >
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Fav</th>
</tr>
</thead>
<tbody >
<tr th:each="mySqlDataDTO : ${mySqlDataDTO}" >
<th th:text="${mySqlDataDTO.id}"></th>
<td th:text="${mySqlDataDTO.name}"></td>
<td th:text="${mySqlDataDTO.fav}"></td>
</tr>
</tbody>
</table>
This is all fine but, the issues comes up when the user intially sends the data to the DB, the page would refresh and force the user to the top of the page thus creating a negative user experience.
I figured out how to use ajax to fix the issue of the refreshing page by having the post request go through ajax first like so:
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
Which works just fine by sending the data to the DB and not having the page refresh, but the issue is the retrieval of the data after its been sent to the database. I dont quite understand how to then retrieve the data and have it be displayed in a table to the user, here's what I have so far, but doesnt seem to work:
$(document).ready(function () {
$('#form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
$('#table').empty();
$.each(data.items, function(item) {
alert(data.name);
});
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I added an alert just to see the data as a test. Basically I want to grab the data from the DB like I normally do via my repository, then pass that data to the view to be displayed like this:
But again it should use ajax get, so as soon the user hits submit that table refreshes (not the whole page) and the table reflects the DB data.
Related
I am trying to send the data of my table with dynamic values to the controller.
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td class="AutoId">#item.AutoID <input type="hidden" name="AutoID" value="#item.AutoID" /></td>
<td class="hove" name="text"> <b>#item.Text</b><br /><label></label></td>
<td class="Active">#item.Active</td>
<td id="oBy" name="OrderBy">#item.OrderBy</td>
</tr>
}
}
above is the table structure
I am using below ajax call to send one field for example...
<script>
$(document).ready(function () {
alert("Test 1");
$("#btnSave").click(function (e) {
alert("Test 2");
$.ajax({
type: "POST",
url: '#Url.Action("LookupManagementUpdate", "Admin", new { Area = "Admin" })',
data: $(".hove").val(),
dataType: 'json',
async: false,
success: function (response) {
Success = true;
},
error: function (response) {
},
});
});
});
</script>
Below is my controller code
public string LookupManagementUpdate(string text)
{
return "answer"+Request["text"]+text;
}
I tried using both Request and parameter method to fetch the data but it does not display the table data.
This is a c# mvc ado.net based project
try using Ajax.BeginForm and ajaxOptions Onsuccess
I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls.
My view:
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def getfromServer(request):
if is_ajax(request=request) and request.method == "GET":
books= Book.objects.all()
bookserial = serializers.serialize('json', books)
return JsonResponse(bookserial, safe=False)
return JsonResponse({'message':'Wrong validation'})
index.html
<div class="container">
<table id="books" class="display" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Author</th>
<th>Genre</th>
<th>Date Publishedd</th>
<th>Copies</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function() {
$('#books').DataTable({
ajax: {
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
},
columns: [
{ data: 'name' },
{ data: 'author' },
{ data: 'genre' },
{ data: 'pub_date' },
{ data: 'copies' },
]
});
</script>
Im pretty sure it kinda works this way but i just cant figure it out .
jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library
So it doesn't make sense to put an ajax request inside the .DataTable() method
You have to make the ajax request first:
$.ajax({
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
success: function (result) { // result is the response you get from the server if successful
// Use the data in result to write the values to your html table respectively here
}
error: function (err) {
// handle error
}
})
thats what I came up with but still doesnt seem to do the trick all i get is an empty table .
$.ajax({
type: "GET",
datatype : 'json',
url: "views/getfromServer", // "{% url 'index' %}"
success: function (response) {
var instant = JSON.parse(response[books]);
for book in books {
var fields= instant[book]["fields"];
$("#books tbody").prepend(
`<tr>
<td>${fields["name"]||""}</td>
<td>${fields["author"]||""}</td>
<td>${fields["genre"]||""}</td>
<td>${fields["pub_date"]||""}</td>
<td>${fields["copies"]||""}</td>
</tr>`
)
}
},
error: function (response) {
alert(response["responseJSON"]["error"]);
}
})
$(document).ready(function() {
$('#books').DataTable();
I'm using jquery DataTables to show some tabular data, and I also placed an edit link for each row in said jquery DataTables so that the user can edit data associated with a particular row if needed. ( Also, I have No clue how to use ASP.NET MVC Html helpers within jQuery DataTables so that is why I am using the html link in the following code )
jquery DataTable javascript:
$("#resultCodeTable").dataTable({
"processing": true,
"serverSide": false,
"destroy": shouldDestroy,
"ajax": {
"url": "../Admin/LoadResultCodes",
"type": "GET",
"datatype": "json",
"data": function (data) {
data.actionCodeIDArg = actionCodeIDInQuestion;
}
},
....................................
............................
..............
columnDefs: [
{
{
targets: 1,
searchable: false,
orderable: false,
name: "EditResultCodeInQuestionReasonForArrears",
"data": "ID",
render: function (data, type, full, meta) {
if (type === 'display') {
data = '<a class="editResultCodeInQuestionReasonForArrears" href="javascript:void(0)" data-id="' + full.ID + '">Edit RFAs</a>'
}
return data;
}
},
....................................
............................
..............
Clicking on the aforementioned link will ensure that the point of execution reaches the following jQuery Event Handler method:
jQuery Event handler method/ function Javascript
$('#resultCodeTable').on('click', '.editResultCodeInQuestionReasonForArrears', function () {
console.log(this.value);
navigateToAParticularResultCodeAssociatedReasonForArrearsList($(this).data('id'));
});
The jQuery Ajax call successfully invokes the C# Controller's action because I see the Visual Studio's Debugger's point of execution reach said Controller's action, however, it fail to navigate to the view that I want to show.
jquery / javascript:
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/NavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
C#: ( in my AdminController.cs )
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
Razor / Html: (In my \Areas\Admin\Views\Admin\AdminModules\Auxiliaries\AParticularResultCodeAssociatedReasonForArrearsList.cshtml view )
#model Trilogy.Areas.Admin.ViewModels.Auxiliaries.AParticularResultCodeAssociatedReasonForArrearsListViewModel
#{
ViewBag.Title = "AParticularResultCodeAssociatedReasonForArrearsList";
}
<h2>AParticularResultCodeAssociatedReasonForArrearsList</h2>
Could someone please tell me how I can change the code so that the view shows up after the jquery Ajax invocation?
May be on .done function you will get the view in the response, you need to take that response and bind it to your control
You call the controller via AJAX, and sure it hits the controller action method, and the controller returns a view but this is your code that deals with whatever is returned from the AJAX call (from the controller):
.done(function (response, status, jqxhr) {})
You are doing absolutely nothing, so why would it navigate anywhere.
A better question you need to ask yourself, instead of fixing this, is why would you use AJAX and then navigate to another page. If you are navigating to a whole new page, new URL, then simply submit a form regularly (without AJAX) or do it via a link (which the user will click). Use AJAX post if you want to stay on the same page and refresh the page's contents.
#yas-ikeda , #codingyoshi , #code-first Thank you for your suggestions.
Here are the modifications that I had to make to resolve the problem(please feel free to suggest improvements):
Basically, I had to end up creating 2 separate Action methods to resolve the problem.
In the jquery/Javascript code below, it is important to note the first action method '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList'
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
window.location.href = response.Url;
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
The purpose of the 1st action method called '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' is to retrieve a url within a Json object.
[HttpPost]
public ActionResult RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
var redirectUrl = new UrlHelper(Request.RequestContext).Action("NavigateToAParticularResultCodeAssociatedReasonForArrearsList", "Admin", new { resultCodeTable_IDArg = resultCodeTable_IDArg });
return Json(new { Url = redirectUrl });
}
The purpose of the 2nd action method is to ultimately navigate to the ASP.NET MVC View that I want to show.
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
aParticularResultCodeAssociatedReasonForArrearsListViewModel.RFACodeList = actionCodeResultCodeBusinessService.GetSpecificResultCodeRFACodeList(resultCodeTable_IDArg);
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
However, I Dislike the fact that I have to use 2 action methods to navigate to the desired asp.net mvc view, therefore, please feel free to suggest improvements or even a totally different better solution.
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
Good day, i need past variable in post to other file
}
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}
code variable
<tr>
<td class="col1"><label for="pat">Sucursal:</label></td>
<td class="col2">
<input type="text" name="suc" id="suc" class="medium" readonly="true" style="width: 200px;"size="40" maxlength="200" onChange="javascript:this.value=this.value.toUpperCase();" />
<input type="button" class="btn btn-success btn-sm" id="sbm" name="sbm" value="Buscar" onclick="llenaSucursales()" />
</td>
</tr>
Error image is :
whats its a problem?
I await your help and I started reading and search and can not find the error
You should have a look at the jQuery documentation for $.ajax() to understand what you may use to react on errors in your AJAX call:
$.ajax({
url: 'emps.php',
type: 'POST', // GET or POST
data: {"sucursal":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function(jqXHR, status, errorThrown) {
// This callback is called if your AJAX query has failed
alert('Got the error ' + errorThrown + ' with status ' +status);
}
});
I would also recommend to open up the Developer Tools (F12 in most browsers) and check the "Network tab" to see the responses of AJAX calls.
Not related to your question:
In the future please take more care when writing your post. Remove unnecessary blank lines, don't post code with errors (just concentrate on the important parts of what you post) - thanks.
The error was that I was missing "/" the address of the file, Thanks, then I leave the code
function empleados(){
if($("#suc").val()=='')
{
alert('Elige una sucursal');
return false;
}
$.ajax({
url: '/emps.php',
type: 'POST', // GET or POST
data: {"suc":$("#suc").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Errors!");
}
});
}