Trying to get a correct url output - javascript

I am kinda new to asp.net mvc website with jquery, razor, javascript and html. Right now my actionlink has a problem where I cannot insert the filter part, into ..page/?sortMethod=StartDate
filters?=pending generates from a button (pending is just 1 of the many status)
?sortMethod=StartDate generates from actionlink.
I am trying to make them work together to get:
..page/?filters?=pending&sortMethod=StartDate
I tried to do a script that tries to replace the
This is the initial code, sortMethod is a string.
<script>
$(function () {
$("#filterUidClear").click(function () {
$("#filterUid").val('');
});
$('#filterPending').checkboxradio();
$('#filterDirect').checkboxradio();
$('#ApplyFilter').click(function () {
var params = "";
if ($('#filterPending')[0].checked) {
params = "filters=pending";
}
if ($('#filterDirect')[0].checked) {
if (params !== "") {
params = params + "&";
}
params = params + "filters=direct";
}
$("#param").val("?" + params);
window.location.href = "?" + params;
});
});
</script>
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate })
This is the new modified one
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate }, new { id = action })
<script>
$(function() {
$('#action').click(function() {
var filterparam = $("#param").val();
this.href = this.href + '?filters=' + encodeURIComponent(filterparam) + '&sortMethod=' + #ViewBag.StartDate;
});
</script>
I am trying to make them work together to get:
..page/?filters=pending&sortMethod=StartDate but to no avail.
The table will display filtered with pending results and sorted by date
Right now it displays ..page/?action&sortingMethod=StartDate
the table shows sorted by date but no filter and action is not being replaced by filter type e.g. ?filters=pending

Related

Call one function after another to get the proper url

Hi I am working in grails ..
<g:link name="searchLink" controller="MRController"
action="ExcelExport">TEST GRAILS</g:link>
<script>
$(function() {
$('a[name="searchLink"]').bind('click', function() {
$(this).attr('href', $(this).attr('href') + '?startdate=' + start().StartDate +'&enddate=' + start().Enddate);
})
})
function start(){
var StartDate = $("#startDate").val();
var Enddate= $("#endDate").val();
return {StartDate:StartDate,Enddate:Enddate}
}
</script>
I have trying to get the following url
http://localhost:8077/Myproject/MRController/ExcelExport
?startdate=2017-05-21&enddate=2017-05-23
But when i click the link again i get the following url instead i want the link with new startdate and enddate value
http://localhost:8077/Myproject/MRController/ExcelExport?
startdate=2017-05-21&enddate=2017-05-23?startdate=2017-05-21&enddate=2017-05-23
Edited
I have tried with the following script to clear the parameters in the first call but i don't know how to make the script run one after another means first the url call work then the parameters will clear through the function
<script>
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url.substring(url.lastIndexOf('/') + 1);
//get the part after before ?
value = value.split("?")[0];
return value;
}
</script>
Don't change the original href attribute in your JS-code:
$('a[name="searchLink"]').bind('click', function() {
document.location = $(this).attr('href') + '?startdate=' + start().StartDate +'&enddate=' + start().Enddate;
})

Angularjs how to preserve url in function?

Hi I am developing one Angularjs application. I have three cascading drop downs. Based on the selected values in drop down i am binding div with data received from api(div with ng-repeat). I have implemented paging.
On page load i am binding first dropdown.
var arrMakes = new Array();
$http.get(url + 'api' + '/Vehicle/' + 'GetVehicleMake').success(function (data) {
$.map(data.data, function (item) {
arrMakes.push(item);
});
$scope.list = arrMakes;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/';
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
function getcadetails(baseurl)
{
var arrallcarDetails = new Array();
$http.get(baseurl,{ params: $scope.pagingInfo }).success(function (data) {
$.map(data.data, function (item) {
arrallcarDetails.push(item);
});
$scope.carDetails = arrallcarDetails;
$scope.pagingInfo.totalItems = data.totalcount;
}).error(function (status) {
});
}
getcadetails is a function i am calling from different scenarios. For example,
ng-change event of first dropdown
$scope.getModel = function (selectedMake) {
var selectedMakeData = selectedMake.ID;
var arrModel = new Array();
$http.get(url + 'api' + '/Vehicle/' + selectedMakeData + '/GetVehicleModel').success(function (data) {
$.map(data.data, function (item) {
arrModel.push(item);
});
$scope.Modellist = arrModel;
var dynamicUrl = url + 'api' + '/Vehicle/' + 'Getcars/' + '?MakeID=' + selectedMakeData;
//bind data to Div randomly.
getcadetails(dynamicUrl);
}).error(function (status) {
});
}
In paging i have below function. This is executed when i click on page numbers for example 1,2, etc
$scope.pageChanged = function (currentPage) {
$scope.pagingInfo.pageNumber = currentPage;
getcardetails();
};
Here my problem starts. If i click on any page number $scope.pageChanged function executes. I will get page number to send it to server. after that i will call getcadetails(?). Now how can i get baseurl for getcadetails? Is there any way i can implement this in better way? Any help would be appreciated. Thank you.
i think u can define a variate for selectedMakeData, and define a function to create url. every time before invoke getcardetails() u should calculate the dynamicUrl.
code looks this:
var selectedMakeData = 0;
selection.addEventListener('change', () => {
selectedMakeData = newData;
});
$scope.pageChanged = function (currentPage) {
var url = getUrl();
$scope.pagingInfo.pageNumber = currentPage;
getcardetails(url);
};
function getUrl() {
// return url baseed on selectedMakeData
}

Changing url using javascript and jquery

Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.
You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery
Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);
Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];
Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}

Updating DropDownList using minimalect

Ok so the scenario is currently I am populating a drop down list from my model with the following code
ViewBag.LeaseCompanyID = new SelectList(ContractModelEntity.system_supplier.Where(x => x.Type == "Lease"), "CompanyID", "Name", data.LeaseCompanyID);
This works perfectly, however on my form I have a button located next to the drop down list which adds another option in the database, using ajax and a modal popup.
The controller code for this is here
[HttpPost]
public JsonResult AddSupplier([Bind(Include="Name,Type")] system_supplier data)
{
if (ModelState.IsValid)
{
ContractModelEntity.system_supplier.Add(data);
ContractModelEntity.SaveChanges();
return Json(0, JsonRequestBehavior.AllowGet);
}
return Json(1, JsonRequestBehavior.AllowGet);
}
When the new option is added into the database I then need to refresh my dropdownlist to get this new data (currently if I refresh the page I can see the new option). I am using minimalect plugin for the drop downs.
Does anybody know a way of updating this minimalect list, there must be a way of building the list through an ajax call which returns some JSON data.
Thanks in advance for your help
OK so after doing a bit of research here is my solution, hopefully it will help other poeple. Someone might even have a cleaner solution.
I first created a jsonresult controller method which looked like this
[HttpGet]
public JsonResult RetreiveSuppliers(string contractType)
{
var supplierData = ContractModelEntity.system_supplier.Where(x => x.Type == contractType);
var result = new List<object>();
foreach (var x in supplierData)
{
result.Add(new { Id = x.CompanyID, Name = x.Name });
}
return Json(result, JsonRequestBehavior.AllowGet);
}
That got me the data from the database. then I created a javascript on the page which looks like this
$("body").on("click", "#btn_InsertNewSupplier", function () {
var supForm = $("#addSupData");
$.ajax({
url: "#Url.Action("AddLeaseSupplier", "Contract")",
data: supForm.serialize(),
type: "POST",
success: function (result) {
if (result === 0) {
var inst = $.remodal.lookup[$('[data-remodal-id=modal_AddSupplier]').data('remodal')];
inst.close();
NotificationAlert("success", "New Supplier Created");
GetNewSupplierList();
} else {
NotificationAlert("error", "Failed Adding New Supplier");
}
}
});
});
function GetNewSupplierList() {
var actionurl = "#Url.Action("RetreiveSuppliers", "Contract", new { contractType = "Lease"})";
$.getJSON(actionurl, tempdata);
}
function tempdata(response) {
if (response != null) {
var html = "";
for (var i = 0; i < response.length; i++) {
html += '<option value="' + response[i].Id + '">' + response[i].Name + '</option>';
}
$("#LeaseCompanyID").html(html);
}
}
So once the ajax call is successful it will trigger the GetNewSupplierList function which calls my controller method and returns some JSON data. Once that is returned it calls tempdata, which builds the new HTML for my select picker, once that is built it updates the html on the selectpicker id.
Works like a charm!!!
Thanks to everyone who took a look at this post.

calling JQuery HTTP GET request inside javascript function

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Categories