Reusable jquery ajax requests - asp.net-mvc

I am developing a web application using asp.net mvc... I am listing out the details of Clients,Staff,Reports via ajax requests using jquery... What i am doing is writing seperate functions(jquery ajax requests) for each actions (ie) view,add,edit,Delete ...
//Clients
function getClients(currentPage) {
$.ajax({
url: "Clients/GetClients",
data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.isRedirect && data.isRedirect === true) {
alert('must redirect to ' + data.redirectUrl);
location = 'http://www.google.com';
}
else {
var divs = '';
$("#hfId").val('');
$("#ResultsDiv").empty();
$.each(data.Results, function() {
divs += '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + this.ClientName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + this.ClientMobNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + this.ClientId + ' onclick="storeIds();"/></span><br/><br/><span class="resultfields">Address :</span> <span class="resultfieldvalues">' + this.ClientAddress + '</span></div>';
});
$("#ResultsDiv").append(divs);
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
$("#HfId").val("");
$("#HfId").val(data.Count);
}
}
});
return false;
}
//Drivers
function getDrivers(currentPage) {
$.ajax({
url: "Staff/GetDrivers",
data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.isRedirect && data.isRedirect === true) {
alert('must redirect to ' + data.redirectUrl);
location = 'http://www.google.com';
}
else {
var divs = '';
$("#hfId").val('');
$("#ResultsDiv").empty();
$.each(data.Results, function() {
divs += '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + this.DriverName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + this.DriverMobileNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + this.DriverId + ' onclick="storeIds();"/></span></div>';
});
$("#ResultsDiv").append(divs);
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
$("#HfId").val("");
$("#HfId").val(data.Count);
}
}
});
return false;
}
//get client by id
function getClientbyId(clientId) {
$.ajax({
url: "Clients/getClientById",
data: { 'clientId': clientId },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
$("#Name").val(data.ClientName);
$("#MobileNo").val(data.ClientMobNo);
$("#Address").val(data.ClientAddress);
$("#hfEditId").val(data.ClientId);
$("#adddiv").show();
$("#ResultsDiv").hide();
$("#PagerDown").hide();
$("#ImageButtonDiv").hide();
}
});
return false;
}
//get driver by id
function getDriverById(driverId) {
$.ajax({
url: "Staff/getDriverById",
data: { 'driverId': driverId },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
$("#Name").val(data.DriverName);
$("#MobileNo").val(data.DriverMobileNo);
$("#hfEditId").val(data.DriverId);
$("#adddiv").show();
$("#ResultsDiv").hide();
$("#PagerDown").hide();
$("#ImageButtonDiv").hide();
}
});
return false;
}
//clients delete
function deleteClients(clientIds) {
$.ajax({
url: "Clients/deleteClients",
data: { 'ids': clientIds },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.Result == "Success") {
getClients(0);
var maxvalues = $("#HfId").val();
$(".pager").pagination(maxvalues, {
callback: getClients,
current_page: 0,
items_per_page: 5,
num_display_entries: 5,
next_text: 'Next',
prev_text: 'Prev',
num_edge_entries: 1
});
return false;
}
}
});
$("#alert").remove();
topBar('successfully deleted');
return false;
}
//delete drivers
function deleteDrivers(driverIds) {
$.ajax({
url: "Staff/deleteDrivers",
data: { 'ids': driverIds },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.Result == "Success") {
getDrivers(0);
var maxvalues = $("#HfId").val();
$(".pager").pagination(maxvalues, {
callback: getDrivers,
current_page: 0,
items_per_page: 5,
num_display_entries: 5,
next_text: 'Next',
prev_text: 'Prev',
num_edge_entries: 1
});
return false;
}
}
});
$("#alert").remove();
topBar('successfully deleted');
return false;
}
How to make these functions into a single function and just pass the values to the function... Is there way to do this...

As all your functions have similar AJAX setup options I would recommend you to setup common options globally using the $.ajaxSetup function:
$(function() {
$.ajaxSetup({
contentType: 'application/json; charset=utf-8',
global: false,
async: false,
dataType: 'json',
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
});
});
Next let's first consider the getClients and getDrivers functions. Those look pretty much the same. The only difference I can see between them is the url you are sending the AJAX request and the html that's being appended to the #ResultsDiv. So you could have two separate functions that handle the result:
function formatDriversResult(result) {
return '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + result.DriverName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + result.DriverMobileNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + result.DriverId + ' onclick="storeIds();"/></span></div>';
}
and
function formatClientsResult(result) {
return '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + result.ClientName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + result.ClientMobNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + result.ClientId + ' onclick="storeIds();"/></span><br/><br/><span class="resultfields">Address :</span> <span class="resultfieldvalues">' + result.ClientAddress + '</span></div>';
}
And finally the two functions could be merged into a single one:
function getEntities(url, currentPage, formatResultFunction) {
$.ajax({
url: url,
data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
success: function(data) {
if (data.isRedirect && data.isRedirect === true) {
alert('must redirect to ' + data.redirectUrl);
location = 'http://www.google.com';
}
else {
var divs = '';
$("#hfId").val('');
$("#ResultsDiv").empty();
$.each(data.Results, function() {
divs += formatResultFunction(this);
});
$("#ResultsDiv").append(divs);
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
$("#HfId").val("");
$("#HfId").val(data.Count);
}
}
});
return false;
}
Now when you want to get the current clients:
var clients = getEntities("Clients/GetClients", currentPage, formatClientsResult);
and when you want to get the current drivers:
var drivers = getEntities("Staff/GetDrivers", currentPage, formatDriversResult);
Next let's consider the getClientbyId and getDriverById functions. They could be simplified to:
function getEntityById(data, url, formatResultFunction) {
$.ajax({
url: url,
data: data,
success: function(data) {
formatResultFunction(data);
$("#adddiv").show();
$("#ResultsDiv").hide();
$("#PagerDown").hide();
$("#ImageButtonDiv").hide();
}
});
return false;
}
The same pattern could be used for the rest.

Related

set value to select2 dropdown which retrieved from database in ASP.NET MVC

<script type="text/javascript">
$(document).ready(function () {
//following values i retrived from database and i want to display into select2 dropdown
var selectedValue1 = '43,48,47,57';
$('#ddlCity1').select2({
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
dataType: 'json',
delay: 250,
url: '#Url.Action("GetCityList", "DemoMVC")',
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.City
});
});
return { results: newData };
},
cache: true
},
});
$(".city1").on("select2:select", function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
$('.city1').on('select2:unselect', function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
});
//Dropdown with select2 control
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>City</label>
<select id="ddlCity1" class="city1" style="width:500px"></select>
</div>
</div>
</div>
i assume that this action "GetCityList" returned json
$('#ddlCity1').select2({ minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%"
});
function ("/DemoMVC/GetCityList", {}, "json", success, falier) {
$.ajax({
url: url,
data: paramters,
contentType: "application/json; charset=utf-8",
dataType: returnFormat,
success: function (data) {
success(data);
let htmlData = "<option value='' selected disabled hidden>Select City...</option>";
for (let i = 0; i < Object.values(data)[1].length; i++) {
htmlData = htmlData + Template(Object.values(data)[1][i]);
}
$("#ddlCity1").html(htmlData);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText + ': ' + xhr.responseText + ': ';
console.log('Error - ' + errorMessage);
},
type: 'GET',
});
}
function Template(item) {
let itemHtml = "<option value='" + item.id + "'>" + item.city + "</option>";
return itemHtml;
}

jeasyui: how to get queryparams in another page by clientside

jeasyui: how to get queryparams in another page by clientside
page 1(root.html):
$.ajax({
type: "get",
async: true,
url: "/ashx/product/root.ashx",
dataType: 'json',
success: function (res) {
var o = $('#tb');
for (i = 0; i < res.length; i++) {
o.tabs('add', {
title: res[i].Name + '-' + res[i].PkId,
href: '/html/usr/node.html', queryParams: { 'id': res[i].id }
});
o.tabs('select', 0);
}
}
});
page 2(node.html):
<script>
// how to get queryParams from page root.html here in javascript.
alert();
</script>
Use JSONP
JQUERY
$.ajax({
url:"node.html.html",
dataType: 'jsonp',
success:function(json){
alert("Success");
},
error:function(){
alert("Error Message");
}
});
node.html ( note im using php )
<?php
$arr = array("param1",
"param2",
array("param3","param4"));
$arr['name'] = "response";
echo json_encode($arr);
?>

JQuery Autocomplete acts wierd once i publish my website

I am using this functionality to fill the JQuery UI with minimum length set to 2. This code works good when I try to select the list through mouse or through keyboard.
But once I publish my code through my virtual machine it does not work. Neither the minimum length works nor the mouse or keyboard selection works.
Please help me here.
function SPAutoComplete(request, response) {
//debugger;
$.ajax({
url: 'Contracts/SearchSpByNumber',
type: 'GET',
cache: false,
contentType: "application/json; charset=utf-8",
data: request,
dataType: 'json',
success: function (json) {
var i = 0;
i++;
// call autocomplete callback method with results
response($.map(json, function (item) {
return {
label: item.SP_NBR,
SPDesc: item.SP_DESC,
ID: item.ElementID
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('error - ' + textStatus);
console.log('error', textStatus, errorThrown);
}
});
}
$("#SP1").autocomplete({
source: SPAutoComplete,
minLength: 2,
select: function (event, ui) {
// alert('you have selected ' + ui.item.name + ' ID: ' + ui.item.name);
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
_newDirty = true;
event.preventDefault();
return false;
},
change: function (event, ui) {
debugger;
if (ui.item != undefined || ui.item != null) {
$("#SP1").val(ui.item.label);
$("#SPDesc1").val(ui.item.SPDesc);
$("#SPDesc1").attr("readonly", true);
$("#SP1ID").val(ui.item.ID);
event.preventDefault();
return false;
}
},
focus: function (event, ui) {
debugger;
$("#SP1").val(ui.item.value);
return false;
}
});

JQuery dropdown key

I found this example online and it was perfectly fine but I'd like to know how to store (hidden) the employeeID, so it can be used later on the server side.
Thank you
<script type="text/javascript">
$(function() {
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "EmployeeList.asmx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
</script>
The autocomplete has a change event which is fired when the field is blurred if the value has changed. You need to bind an event handler to this event and then set a hidden field within that event handler.
So
$(".tb").autocomplete({
source: function(request, response) {
$.ajax({
url: "EmployeeList.asmx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.Email
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1,
change : function (event,ui) {
$("#hdnEmpId").val(ui.item.value);
}
});
You will have to figure out how you want to implement the change event handler. You can read more about that at http://jqueryui.com/demos/autocomplete/#event-change
Hope this helps!

Jquery UI autocomplete event change

Hi I got a problem with change event.
By documntation there should be object ui.item
After an item was selected; ui.item refers to the selected item. Always triggered after the close event.
But when I try it ui.item is undefined :( I want unset s_town_id when input in autocomplete doesn't match with data from script.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
// ui.item is undefined :( where is the problem?
$("#s_town_id").val(ui.item.id);
}
});
});
I find out solution where I testing event.originalEvent.type if it is meneuselected or not and after fail I unset s_town_id. But any better solution is still wellcome.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
try
{
if(event.originalEvent.type != "menuselected")
{
// Unset ID
$("#s_town_id").val("");
}
}
catch(err){
// unset ID
$("#s_town_id").val("");
}
}
});
});
if ui.item is not defined that means your json source is not well formed.
You have to send a json source like this:
[{"label":"Jean","value":1},{"label":"carl","value":2}]
You can add more key to the array but at least you have to set "label" and "value".
Check the json string.
Also I reckon you to use the last version of autocomplete 1.8.1 at the moment

Resources