MVC5 Ajax update - javascript

I have a dropdown with selection id StaffId. What I am doing is once an item is selected I want to pass on the StaffId to controller to fetch records in a database using the staffId. This is giving an error on page load without passing the StaffId to the controller. below is the snippet
controller
[HttpPost]
public PartialViewResult GetStaffPosts(int? id)
{
var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value);
return PartialView(sPost.ToList());
}
<div id="divPartialView">
#{Html.RenderPartial("GetStaffPosts");}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
$.ajax(options);
}
});
});
</script>

Your current code is not actually making an ajax call on the change event because you are invoking the $.ajax(options); call inside the success callback of the options object. You are not calling the $.ajax method on the change event!
This should work (assuming your controller code is returning a 200 response).
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
options.type= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
You may also simplify your code using the $.post method.
$("#StaffId").change(function() {
$.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) {
$("#divPartialView").html(data);
});
});
Or even using the $.load method and a one liner
$("#StaffId").change(function(event) {
$("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() });
});

Hi just put your ajax call outside of the success function and make an url like the below code and try again
Your changed code:
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "../StaffPost/GetStaffPosts,
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest)
{
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
});
</script>

Related

Why does my jquery plugin cannot access or utilize a data or vaiable from my script?

I have this custom made jQuery plugin, whenever I called it in my script, the option parameter row cannot access the variable or data defined on my script.
JQuery Plugin:
{
$.fn.dbGrid = function (options) {
var settings= $.extend({
read: function () { },
row:""
}, options)
settings.read.call(this)
//console.log(settings.row)
//It ouputs nothing
}
Usage on my Script:
var rows;
function onSuccess(data) {
rows = data;
}
function populateTable() {
$("#container").dbGrid({
read: function () {
$.ajax({
url: "some url",
success: onSuccess,
dataType: "json",
async: false,
type: "GET"
});
},
row:rows
//here the option `row` can not access my `rows` defined in my script, thats why it cannot yield result in my plugin whenever I do console.log
})
//console.log("Row in Base script" + rows);
//Here it outputs the result I want which is data from the function onSuccess
}
populateTable();
}

How to retrieve the elements of a dropdownlist in jquery and send it with ajax to an MVC Controller in ASP.Net?

I have a select item as follows:
<select id="id_category">
<option> </option>
</select>
In run time there is a tree view used to fill up the select menu as follows:
<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});
$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>
and the html for the tree is not important now as it works well.
Now, I want when a user click on a button with HTML as follows:
<input id="btn3" type="button" value="Test 3" />
an ajax will be run to send all the items in the select to a controller in MVC as follows:
$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
and the controller:
[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}
The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?
The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.
$("#btn3").click(function () {
var optionsData= $.map($('#id_category')[0].options, function(elem) {
return (elem.value || elem.text);
}); // create a variable to hold all the options array.
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
Then you can have your controller as below.
[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
//your logic goes here
}
I think it's because you have not added [HttpPost] attribute in your controller function

Call view by dropdownlist value

i'm having a html.dropdownlist where ochange event is speified. i need to call a controller action method using ajax or javascript function and returns view based on the filter value
I try someting like following which is not working,why?
<script type="text/javascript">
$(function() {
$('#Projcbo1').change(function () {
// fetch the newly selected value
var selectedValue = $(Projcbo1).val();
// send it as an AJAX request to some controller action
$.post('#Url.Action("ProjCBOItemSelected")', { value: selectedValue }, function (result) { $("#resultContainer").html(result); });
});
});
</script>
You can use the following to achieve that.
<script>
$(function() {
$('#ddl').change(function () {
$.ajax({
url: '#Url.Action("actionname", "controllername")',
type: 'GET',
dataType: 'html',
data: {Id: $(this).val() },
success: function (result) {
$('#div_to_load_the_content').html(result);
},
error: function (error) {
},
});
});
});
</script>
Let me know if it helps.

Alter the filter on autocomplete to allow sorting on complete string

I have a functioning autocomplete jQuery input control but there are two things it is doing that I would like to alter.
First, it fires again and again. I would like for the data to be returned once, cached and not called again.
Second, I would like for the user to type in the control and based on what they type be able to search the entire string and not just the beginning.
This is my functioning script that returns data to the autocomplete and WORKS.
<script type="text/javascript">
$(function () {
$('#datePicker').datepicker();
});
$(document).ready(function() {
$("#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "FacilitiesAsync",
type: 'GET',
cache: true,
data: 'sourceDb=myDb',
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
response($.map(json, function (name) {
return {
label: name.label,
value: name.value
};
}));
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$("#autocomplete").text(textStatus + ', ' + errorThrown);
}
});
},
select: function (event, ui) {
$('#autocomplete').val(ui.item.label);
return false;
},
messages: {
noResults: '',
results: function () {
}
}
});
});
</script>
I found this bit of code that overrides the filter feature of the autocomplete but I have NO IDEA where to add this. I have tried several places to no avail....
// Overrides the default autocomplete filter function to search only from the beginning of the string
$("#autocomplete").autocomplete.filter = function (array, term) {
var matcher = new RegExp("\\b" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
My input control looks like this.
<input id="autocomplete" />
I appreciate the direction...
To cache the data from your server, setup a separate function which handles (and caches, if necessary) the response from your ajax call:
var cachedResult = null;
function fetchResponse(callback) {
if (cachedResult) callback(cachedResult)
$.ajax({
url: "FacilitiesAsync",
type: 'GET',
cache: true,
data: 'sourceDb=myDb',
dataType: 'json',
success: function (json) {
// call autocomplete callback method with results
var cachedResult = $.map(json, function (name) {
return {
label: name.label,
value: name.value
};
});
callback(cachedResult);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$("#autocomplete").text(textStatus + ', ' + errorThrown);
}
});
}
$(document).ready(function() {
$("#autocomplete").autocomplete({
source: function (request, response) {
fetchResponse(function(result) {
response(result)
})
}
});
});
As for the custom matcher, look no further than the docs, in the Using a custom source callback to match only the beginning of terms example. Your custom matcher only differs in the regex pattern. Note also that this is all done within the "source" callback.

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

Categories

Resources