Controller method call using ajax - ajax

I am using codeigniter framework. I am trying to call controller method using AJAX function call on dropdown change event. My code is:
$(document).ready(function() {
$("body").on('change', '#assettype_id', function(e) {
var categoryval = $('#assettype_id :selected').val();
// assettype_id is dropdown id. On change event of
// dropdown, controller method will be called
myurl = 'http://mylocalsite/index.php/controllername/controllermethod/' + $.now();
alert("category id = " + categoryval); // for testing
$.ajax({
cache: false,
type: 'POST',
data: {
id: categoryval
},
url: myurl,
dataType: 'html',
success: function(data1) {
alert("inside ajax call"); // for testing
$('#result').html("");
// result is a div tag used to display result//
$("#result").html(data1);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error');
},
complete: function(xhr, status) {
alert("The request is complete!");
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This code is working perfectly for initial 2 or 3 change events of dropdown and getting new output but after 2 or 3 selection from dropdown, won't get new result like AJAX method is not working.
I have put 2 alerts for checking. alert with message 'category id =' is calling on every change event of dropdown but alert with message "inside ajax call" is not showing after 2 or 3 selections of dropdown even not going to error section of AJAX call.
I would like to know what is going wrong here? Thank you for you help.

Related

On button click - call Ajax function

I stuck. I try to make Ajax call from button click. Function is loading and responding HTML data. HTML data in format like "< div>...< /div >". When I open "http://domain.com/load_info.php?id=1" in browser, I get all HTML data. But when I try to load it by Ajax function, nothing is loading.
buttons
<input type='button' onclick='getInfo(1);' value='Load Info' >
Ajax Function
function getInfo(id_number){
alert('function started with id =' + in_number); // this alert works fine
$.ajax({
type:"GET",
data: { 'id': id_number },
url : "load_info.php",
dataType: "text",
success: function(response) {
alert('success'); // this alert is not working
$("#info").prepend(response);
}
});
};
You could also use this approach if you are using jQuery:
$("button").click(function(){
$.get("load_info.php",
{
id: id_number
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});

How do I request views from a layout using AJAX?

In my MVC application I don't want the layout page to reload everytime a view is selected. It would be great if the views could be loaded using ajax to keep things nice and fast and allow me to persist certain interface states that are wiped out when you move around.
My initial approach was to add some ajax to the _Layout.cshtml and then whent he view was requested pass that request to the controller method which will grab that page. All I ended up doing however was returning the WHOLE view again.
Here is the code I have so far, am I on the right tracks here or is this totally wrong?
Layout Ajax Script
<script>
$(function () {
var content = document.getElementById('content');
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
console.log("Data Attrib : " + page);
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/")' + page,
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
</script>
As I say, this sort of works, but it's not perfect as it returns the whole page into the content area including layout, ideally I just want the core view data.
you can create a Single Page Application that have 1 layout and in home controller and index action method create menu or user setting or another things
and now you can load other action with Ajax call with data-content html that does not have layout file and append that in container
when user click another menu clean older content and add new or you can create tab strip or window
Layout.cshtml
<script>
$(function () {
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
$.ajax({
type: 'POST',
url: '/Home/Pages',
data: { pageValue: page },
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
Controller
public class HomeController : Controller
{
[HttpPost]
public string Pages(string pageValue)
{
string result = //Whatever
return result;
}
}
Controller
public ActionResult SomeAction(String someparams)
{
//Make the model
SomeModel someModel = new SomeModel();
someModel.someparams = someparams;
return PartialView("SomePartialView", someModel);
}
In View
$.ajax({
url: "/Home/SomeAction",
type: "POST",
dataType : "html",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
$('#SomeDivID').html(data);
}
});

Adding autoresize to server side generated textarea using jQuery

Am using a plugin called "jQuery Autosize!" on my textareas. How can i make it autoresize my server side generated textareas because they generated when the page has already loaded.
This is the code that generates the server side textareas. resultErrorObj.node_html contains the server side generated textarea as shown below.
$(document).ready(function() {
$("#postUpdate").submit(function(event){
// setup some local variables
var $form = $(this),
// let's select and cache all the fields
$inputs = $form.find("input"),
// serialize the data in the form
serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.attr("disabled", "disabled");
// fire off the request to /form.php
$.ajax({
url: base_url + "ajax/post_status_update",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
var resultErrorObj = jQuery.parseJSON(response);
if (resultErrorObj.status == 1)
{ $(resultErrorObj.node_html).hide().insertAfter('#activitiesStream').slideDown('fast');
}
else
{
alert(resultErrorObj.error);
}
},
// callback handler that will be called on error
error: function(jqXHR, textStatus, errorThrown){
// the error
alert("Error here " + errorThrown);
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
});
Thank you!
The website for Autosize (http://jacklmoore.com/autosize) shows that you can manually trigger the autosizing.

Pass Ajax POST variable to JQuery UI dialog

Below is an Ajax POST variable I use to return some information to an ASP MVC3 View. However, I cannot get the .dialg() pop-up function to work. Right now you click on the icon that calls GetProgramDetails(pgmname), and nothing happens. First time using Ajax, so any suggestions would be appreciated. Thx!
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
function GetProgramDetails(pgmname) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
});
request.done(function (data) {
$('#data').dialog();
});
</script>
EDIT
I've updated the request.done function to include a simple alert to see if the code was being called. After stepping through with Chrome's debugger, I saw that the code inside was completely skipped over.
request.done(function (data) {
alert("HERE!");
$('#programExplanation').html(data);
});
SECOND EDIT
Here is the controller code the ajax is returning a value from:
[HttpPost]
public string PopDetails(string programName)
{
BatchPrograms batchprograms = db.BatchPrograms.Find(programName);
if (batchprograms == null) return string.Empty;
StringBuilder s = new StringBuilder();
s.Append(batchprograms.ProgramName + " - " + batchprograms.ShortDescription);
s.Append("<br />Job Names: " + batchprograms.PrdJobName + ", " + batchprograms.QuaJobName );
s.Append("<br /> " + batchprograms.Description);
return s.ToString();
}
You need to use the success method to handle the callback, like so:
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(function(data){ $('#data').dialog()} );
This will launch the dialog for you, but if you want to get the response data to work with it, you can have GetProgramDetails take a second parameter which is a callback for after the data is loaded like so:
function GetProgramDetails(pgmname, callback) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(callback);
}
This way after the response is received you can handle what to do with the data in your implementation of the callback, in this case it seems like you will be setting data in the dialog and launching the dialog.

jquery live() appending click events causing multiple clicks

I have some strange behaviour going on with the jQuery ajax functionality in my asp.net MVC3 application.
I have several boxes of data each containing a link to open a popup and change the data in each box. To do this I've added a jquery live() click event to process the data via a jQuery ajax call. In the "success" method of the ajax call, i take the return data and open a UI Dialog popup (a partial view) which contains a list of radio buttons. I select a different radio button and press 'close' - the close button fires another live() click event, processes that new data via an ajax call which refreshes the data in the box on the main page.
This works perfectly first time. If you then click to change it again, the popup opens, allows you to select a new value, but this time pressing close on the popup triggers two click events which throws an null error in my MVC controller.
If you repeat this process it triggers 3 click events, so it's clear that live() is appending these events somewhere.
I've tried using on() and click(), but the page itself is made up of panels loaded in via ajax so I used live() to automatically bind the events.
Here is the code I'm using:
HTML
<p><!--Data to update goes here--></p>
Update Data
First Click event calling popup with Partial View
$('a.adjust').live('click', function (e) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true
}
});
}
});
e.preventDefault();
});
Second click event the takes the new info to return updated partial view
$('a#close').live('click', function (event) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
$('#box-' + #column).html(response); //this refreshes the box on the main page
},
error: function () {
}
});
$('#ModalDialog').dialog('close');
event.preventDefault();
});
Anybody know what might be happening here, and how I could resolve it?
Use namespaces to unbind previous click binds like this:
$('a.adjust').unbind('click.adjustclick');
Then bind the click action to a.adjust:
$('a.adjust').bind('click.adjustclick', function(){
//your code here
//note the return false, this prevents the browser from visiting the URL in the href attribute
return false;
});
If i understand you correctly, you try to run the second click action when the dialog is closed. Therefor I would use the build in close function for the dialog like this:
$('a.adjust').bind('click.adjustclick', function(){
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true,
close: function(){
var jsonData2 = getJsonString(n[1]);
var url2 = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url2,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData2,
success: function (response2) {
$('#box-' + #column).html(response2); //this refreshes the box on the main page
},
error: function () {
}
});
}
}
});
}
});
});
If you are using your own button a#close, bind a click event to it to close the dialog, it will automatically fire the close function for the dialog.
$('a#close').unbind('click.closedialog');
$('a#close').bind('click.closedialog', function () {
$('#ModalDialog').dialog('close');
return false;
}
Try this:
$('a#close').unbind('click').bind('click', function (event) {
//Your Code
});

Resources