400 bad request while passing object and value to url - javascript

I know how to pass data in url in json or with plain parameters but this is something different
see the below image :-
http://www.tiikoni.com/tis/view/?id=23d9b98
My api Url /geniedoc/api/doctor/Search
as we can see one thing is in object and two paramater is simply passing
can you suggest me a ajax call?
my ajax call
function getNewSlotContent(startIndex, totalRows) {
var skipindex = 0;
if (startIndex > 1) {
skipindex = totalRows;
}
var totalrows = totalRows + 10;
var searchByName = document.getElementById("searchByName").value;
var selectedSpeciality = document.getElementById("searchByName").value;
if (selectedSpeciality != null || selectedSpeciality != "") {
selectedSpeciality = encodeURIComponent(selectedSpeciality);
}
$("#preloader").addClass("pageload");
$("#preloader").show();
var dataString = '{"firstName":"'+ searchByName + '","start_index":"' + skipindex + '","rows":"' + totalrows +'"}';
console.log(dataString);
$.ajax({
type: 'POST',
url : '/geniedoc/api/doctor/search',
data: dataString,
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type':'application/json'},
timeout: 100000,
success: function(data) {
var op = "";
for (doctor in data.response.rows) {
op += '<div class="post-sec">';
op += '<img src="/geniedoc/ajax/data/displayImage?fileName=' + data.response.rows[doctor].profilePicId + '" alt="">';
if (data.response.rows[doctor].prefix == null) {
data.response.rows[doctor].prefix = "";
}
op += '<a target="_blank" href="/doctor/' + data.response.rows[doctor].seo_name + '/' + data.response.rows[doctor].idKey + '" class="title"> ' + data.response.rows[doctor].prefix + ' ' + data.response.rows[doctor].firstame + ' ' + data.response.rows[doctor].last_name + '</a>';
op += '<span class="date">' + data.response.rows[doctor].speciality_id + '</span>';
op += '</div>';
op += '<div class="clear"></div>';
}
$("#preloader").hide();
$("#preloader").removeClass("pageload");
$("#doctor-data").html(op);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}

Modify your dataString like this :
var dataString = {
"firstName":searchByName,
"start_index": skipindex,
"rows": totalrows
};

Related

if else Ajax success restapi Sharepoint Online

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);
}
});

How to retrieve files from Sharepoint Document library Folders

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>

Laravel & Ajax load data without refreshing page

I'm currently working on a code that displays users activity log. Ajax will call the route and gets the response (json) results. I need to be able to display the log records on admin dashboard without refreshing the page.
Ajax
$(document).ready(function() {
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
},error:function(){
console.log(data);
}
});
});
If I understood, you can do this:
$(document).ready(function() {
var requesting = false;
var request = function() {
requesting = true;
$.ajax({
type: 'get',
url:"{{ route('users.activity') }}",
dataType: 'json',
success: function (data) {
$.each(data, function() {
$.each(this, function(index, value) {
console.log(value);
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
requesting = false;
});
});
},error:function(){
console.log(data);
}
});
};
if(!requesting){
setTimeout(request, 1000);
}
});
Every seconds it does a request to your users.activity route, so there is an update every second.
You need to send last record id in server. so you can get only new data.
my updated answer based on #stackedo answer .
$(document).ready(function () {
var lastId = 0; //Set id to 0 so you will get all records on page load.
var request = function () {
$.ajax({
type: 'get',
url: "{{ route('users.activity') }}",
data: { id: lastId }, //Add request data
dataType: 'json',
success: function (data) {
$.each(data, function () {
$.each(this, function (index, value) {
console.log(value);
lastId = value.id; //Change lastId when we get responce from ajax
$('#activity').append('' +
'<div class="sl-item">' +
'<div class="sl-left bg-success"> <i class="ti-user"></i></div>' +
'<div class="sl-right">' +
'<div class="font-medium">' + value.causer.username + '<span class="sl-date pull-right"> ' + value.created_at + ' </span></div>' +
'<div class="desc">' + value.description + '</div>' +
'</div>' +
'</div>');
});
});
}, error: function () {
console.log(data);
}
});
};
setInterval(request, 1000);
});
In controller add were condition to query :
UserActivity::where('id','>',$request->id)->get();

execute javascript after for loop

I have a for loop that gets data from lists in subsites to build a html list on the page using an async ajax request, this works, but i wish to order the list after it has been generated to show the list in alphabetical order. I am on a learning curve with javascript so any help is appreciated. I need to run the sortProjects function after the onWebsLoaded function is complete.
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++)
{
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
getProjectProperties(url, title, desc, client, id);
}
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}
You can amend your logic so that you store an array of the promises returned from the $.ajax() calls. You can then apply() that array to $.when and call sortProjects(). Try this:
function onWebsLoaded(sender, args) {
var requests = [];
for (var i = 0; i < this.webs.get_count(); i++) {
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
requests.push(getProjectProperties(url, title, desc, client, id));
}
$.when.apply($, requests).done(sortProjects);
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
// note 'return' below
return $.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}

Call function after some period time

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();
}
},

Categories

Resources