I'm trying to query data using AJAX from a controller, my controller is:
[HttpGet]
public ActionResult GetTestStatus(string userName)
{
var db = new SREvalEntities();
var allTests = db.Tests
.Where(x => string.Equals(x.Owner, userName))
.Select(x => new { CreateDate = x.CreateDate, EndDate = x.EndDate, Status = x.Status })
.OrderByDescending(x => x.CreateDate)
.ToList();
return Json(allTests, JsonRequestBehavior.AllowGet);
}
And my javascript code in an extern file is:
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
}
});
$("#ShowDetail").html(txt);
}
When I tried to debug this function, the code will never excute to
$("#ShowDetail").html(txt);
And my page will never be changed. How can I get it work? Thanks.
As you are using $.ajax(), which is asynchronous. Thus the $("#ShowDetail").html(txt) is called before the value is returned from API.
You should set the html() after the each block
function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias.value }, //Use the value property here
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt); //Move code to set text here
}
});
}
Try the following function
function Filter() {
var userAlias = $("#UserAliasInput").val();//change this
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td>Goto</td></tr>";
});
$("#ShowDetail").html(txt);//place this in the success function
}
});
}
Related
I want to do a search with AJAX. I simply did with the get method through passing search string in controller but that not I want
Below my controller code, where I get the search value from URL and return DATA (which is a list)
if (search != null)
{
if (search.ToLower().ToString() == "paid")
{
DATA = DATA.Where(a => a.Purchased_Price > 0).ToList();
}
else if (search.ToLower().ToString() == "free")
{
DATA = DATA.Where(a => a.Purchased_Price == 0).ToList();
}
else
{
DATA = DATA.Where(a => a.Purchased_File_Name.ToLower().StartsWith(search.ToLower()) || a.Purchased_Category.ToLower().StartsWith(search.ToLower()) || a.User1.Email.ToLower().StartsWith(search.ToLower()) || a.Purchased_Price.ToString().StartsWith(search)).ToList();
}
ViewBag.SoldList = DATA.ToPagedList(page ?? 1, pageSize); *this is what I actually did*
return Json(DATA , JsonRequestBehavior.AllowGet); *this is trial I do not know this work or not*
}
Below is the script which I wrote in view. Where I am going wrong? I'm not aware of that. I want whatever list comes with the help of whatever search I entered. To be printed in the table. Table is just above this script; I don't think it's needed so I did not include that.
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var search_value = $("#searchText").val();
alert(search_value);
var SetData = $("#tabledata"); *tabledata is id of tbody tag *
SetData.html("");
console.log("setddata");
console.log(SetData);
$.ajax({
type: "get",
url: "/Home/MySoldNotes?search=" + search_value, *home is controller, mysoldnotes is action*
contentType: "application/ json; charset = utf - 8",
dataType: "html",
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
You must pass object to controller from ajax call. Example
<script>
$(document).ready(function () {
$("#search_button").on("click", function () {
var objParam = new Object();
objParam.search_value = $("#searchText").val();
$.ajax({
type: "POST",
url: "/Home/MySoldNotes"
contentType: "application/json; charset = utf-8",
data: JSON.stringify(objParam)
success: function (result) {
console.log("result");
console.log(result);
$.each(result, function (index, value) {
var data = "<tr>" +
"<td>" + value.NoteDetail.File_Name + "</td>" +
"<td>" + value.Purchased_Category + "</td>" +
"<td>" + value.User1.Email + "</td>" +
"<td>" + value.NoteDetail.Sell_Price + "</td>" +
"<td>" + value.Req_Solved_Date + "</td>" +
"</tr>"
SetData.append(data);
});
},
error: function (err) {
alert("Error aa gai");
console.log(err.responseText);
}
});
});
});
</script>
Then in your controller
public JsonResult MySoldNotes(string search_value)
{
// Do whatever and return json as result
}
List<BuyerReq> DATA = dc.BuyerReqs.Where(a => a.seller_id == ab && a.Status == true).AsQueryable().ToList();
return Json(DATA, JsonRequestBehavior.AllowGet);
while returning from the controller I am getting an error(not success my AJAX call).
but when I am doing this for testing purpose :
var aa = "checking"; return Json(aa, JsonRequestBehavior.AllowGet);
this works. I am not getting the exact error.
Im trying to show a custom 'No new uploads' message when the rest api returns no entries on Success event. The code below works perfect when rows are returned on Success event and shows blank on 0 entries.
I tried implementing if else statement with no luck. Kindly assist.
$(function(){
var today = new Date();
today = moment(today).format("YYYY-MM-DD");
var currentDate = today+'T00:00:00.000Z';
var requestUri = "#SPO_SITE#/_api/web/lists/getbytitle('LIST_NAME')/items?$top=20000&$select=DistrDate,EncodedAbsUrl&$filter= DistrDate ge datetime'" +currentDate+ "'";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="mbrTable" style="width:100%"><caption class="text-info">Report</caption>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + moment(objItems[i].DistrDate).format("DD-MM-YYYY") + " - " + "<a target='_blank' href=" + objItems[i].EncodedAbsUrl + ">" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
document.getElementById("mbrTable").innerHTML = (tableContent);
}
});
Following fixed the issue.
$(function(){
var today = new Date();
today = moment(today).format("YYYY-MM-DD");
var currentDate = today+'T00:00:00.000Z';
var requestUri = "#SPO_SITE#/_api/web/lists/getbytitle('LIST_NAME')/items?$top=20000&$select=DistrDate,EncodedAbsUrl&$filter= DistrDate ge datetime'" +currentDate+ "'";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
if (objItems.length == 0) {
var tableContent = '<table id="mbrTable" style="width:100%"><caption class="text-info">Report</caption><tr><td>No new uploads</td></tr>';
}
else {
var tableContent = '<table id="mbrTable" style="width:100%"><caption class="text-info">Report</caption>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + moment(objItems[i].DistrDate).format("DD-MM-YYYY") + " - " + "<a target='_blank' href=" + objItems[i].EncodedAbsUrl + ">" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
}
document.getElementById("mbrTable").innerHTML = (tableContent);
}
});
I have two folders in my document library, that two folders are created automatically based on the year when the file was uploaded. Now what I need to do is Retrieve the file from multiple files.How can I achieve this using javascript...
My Function for Uploading file and create a folder based on year
onclick="fileUpload('Improvement-Projects','improvementprojects')
function fileUpload(divId , fileId) {
var clientContext;
var oWebsite;
var oList;
var itemCreateInfo;
var resultpanel = "MySite";
clientContext = new SP.ClientContext.get_current();
oWebsite = clientContext.get_web();
oList = oWebsite.get_lists().getByTitle("QualityCI");
itemCreateInfo = new SP.ListItemCreationInformation();
itemCreateInfo.set_underlyingObjectType(SP.FileSystemObjectType.folder);
var d = new Date();
var n = d.getFullYear();
var dynfloder = itemCreateInfo.set_leafName(divId + '-' + n.toString());
alert(dynfloder);
this.oListItem = oList.addItem(itemCreateInfo);
this.oListItem.update();
clientContext.load(this.oListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
And function to retrieve the files
var d = new Date();
var n = d.getFullYear();
fileGetAction("/sites/Sitename/QualityCI" + '/' + divId + '-' + n.toString());
function fileGetAction(folderUrl) {
if ($.fn.DataTable.isDataTable('#table_id')) {
$('#table_id').DataTable().destroy();
}
$('#table_id tbody').empty();
var requestURL = _spPageContextInfo.webAbsoluteUrl
+ "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files";
$.ajax({
url: requestURL,
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
complete: function (data) {
console.log("folder: " + folderUrl + " - files: ", data);
var dynamicTable = "";
for (j = 0; j < data.responseJSON.d.results.length; j++) {
var tableData = data.responseJSON.d.results[j];
dynamicTable += "<tr>";
dynamicTable += "<td>" + tableData.Name.split('.').slice(0, -1).join('.') + "</td>";
dynamicTable += "<td>" + ' "' + tableData.Name + '"' + "</td>";
dynamicTable += "<td class='text-center'>" + '<a class="btn btn-primary delete" onclick="javascript: fileDeleteAction(\'' + tableData.ServerRelativeUrl + '\',\'' + folderUrl + '\');">Delete</a>' + "</td>";
dynamicTable += "</tr>";
}
document.getElementById("datatable").innerHTML = dynamicTable;
table = $('#table_id').DataTable();
},
error: function (err) {
console.error("Error: ", err);
}
});
}
This is working fine.But my requirement is if the folder name is Improvement-Projects-2020 then that folder data only I can retrieve I want to retrieve Improvement-Projects-2019 files also Please help me
Use promise, you could request multiple requests and get return data from these requests and then bind the data.
Sample script:
<script>
var d = new Date();
var n = d.getFullYear();
fileGetAction("/sites/dev/QualityCI" + '/Improvement-Projects-' + n.toString(),"/sites/dev/QualityCI" + '/Improvement-Projects-' + (n-1).toString());
function fileGetAction(...args) {
if(arguments.length==0){
console.log("There is no corresponding folder in the library")
return;
}
var reqs=new Array()
$('#table_id tbody').empty();
var dynamicTable = "";
for(var i=0;i<args.length;i++){
var folderUrl=args[i]
var requestURL = _spPageContextInfo.webAbsoluteUrl+ "/_api/web/GetFolderByServerRelativeUrl('" + folderUrl + "')/Files";
reqs[i] = _ajax(requestURL)
}
Promise.all(reqs).then((result) => {
var dynamicTable = "";
for (j = 0; j < result.length; j++) {
for(var x=0;x<result[j].d.results.length;x++){
var tableData = result[j].d.results[x]
dynamicTable += "<tr>";
dynamicTable += "<td>" + tableData.Name.split('.').slice(0, -1).join('.') + "</td>";
dynamicTable += "<td>" + ' "' + tableData.Name + '"' + "</td>";
dynamicTable += "<td class='text-center'>" + '<a class="btn btn-primary delete" onclick="javascript: fileDeleteAction(\'' + tableData.ServerRelativeUrl + '\',\'' +args[j] + '\');">Delete</a>' + "</td>";
dynamicTable += "</tr>";
}
}
document.getElementById("datatable").innerHTML = dynamicTable;
table = $('#table_id').DataTable();
}).catch((error) => {
console.log(error)
})
}
function _ajax(requestURL){
return new Promise((resolve, reject) => {
$.ajax({
url: requestURL,
type: "GET",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function(data) {
resolve(data)
},
error: function(error) {
reject(error)
}
})
})
}
</script>
I can't seem to figure out why I am getting this error I've seen solutions for the error but none of those were using AJAX to get the data if anyone could help that would be great here's the JS:
$(document).ready(function() {
function updatetabel() {
console.log("update");
$.ajax({
url: "/main",
type: 'GET',
dataType: "",
cache: false,
success: function(result) {
console.log("succes!");
console.log()
$(".table-hover-cells").remove();
$.each(result, function(index, value) {
console.log("update_tabel");
var content = "<table class=\"table-hover-cells" +
this[0] + "\" id=\"hover-table\">" + "<thead>" + "<tr>" + "<td>" +
this.Name + "</td>" + "<td>" +
this.Description + "</td>" + "<td>" +
this.Status + "</td>" + "<td>" +
this.Date + "</td>" + "</tr>" + "</thead>" + "</table>"
$("inv").append(content);
})
console.log("tabel_update");
},
error: function(result, thrownError) {
console.log("Failure!")
console.log(result)
}
});
}
updatetabel();
setInterval(function() {
updatetabel()
}, 100000);
});
$(document).ready(function() {
$('table tbody tr td').on('hover', function() {
$(this).toggleClass('bg');
});
});
The following line in your success callback throws the error:
$.each(result, function(index, value) {
...
}
Most likely, your 'result' is not a valid response to your request, and $.each requires a valid array to iterate through. Check the XHR response of your ajax call first to see if an array is returned. It's also better to define your dataType too.
I'm having a problem and don't know how to solve it. I have two functions in Javascript, both are called via AJAX, first function get values and insert records in DB and second function reads from DB and show the results. Since first function get values remotely sometimes response times are larger than second function and for that reason second function executes before first. What I need is to call buildTablesFromDB() only if AJAX call for buildClassification() is done. This is how my code looks like:
$(document).ready(function() {
function buildTablesFromDB() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/reader.php",
success: function(data) {
$("#clasification-data").html();
if (data.response === false) {
$(".alert").show();
$(".close").after(data.error);
} else {
if (data.html_content.position.length != 0) {
$("#clasification-holder").show();
var iterator = data.html_content.position;
var tr = "";
$.each(iterator, function(key, value) {
tr += "<tr>";
tr += '<td><img src="' + value.team_image + '" alt="' + value.team_name + '" title="' + value.team_name + '"> ' + value.team_name + '</td>';
tr += '<td>' + value.team_jj + '</td>';
tr += '<td>' + value.team_jg + '</td>';
tr += '<td>' + value.team_jp + '</td>';
tr += '<td>' + value.team_difference + '</td>';
tr += '<td><span class="glyphicon glyphicon-play"></span><span class="glyphicon glyphicon-stop"></span></td>';
tr += '</tr>';
});
$("#clasification-data").html(tr);
}
}
},
error: function() {
request.abort();
}
});
}
function buildClassification() {
var request = $.ajax({
type: 'GET',
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
// some error
}
},
error: function() {
request.abort();
}
});
}
window.setInterval(function() {
buildClassification();
}, 1800000); // Updates table results each 30 minutes
window.setInterval(function() {
buildTablesFromDB();
}, 1800000); // Updates table results each 30 minutes
buildClassification();
buildTablesFromDB();
});
How I can get this done?
you can call buildTablesFromDB() in the callback method of buildClassification()
e.g.
....
dataType: 'json',
url: "http://local/parser/parser.php",
success: function(data) {
if (data.response === false) {
//
}else{
buildTablesFromDB();
}
},