I am using jquery tabs and trying to use the onclick function but it seems it is not firing. When user clicks the tab and i want to change the detailview mode into readonly mode. Here is my code in aspx:
<div id="tabs-2" class="column" onclick="ChangeMode">
and here code behind:
protected void ChangeMode()
{
if (DV_Test.CurrentMode == DetailsViewMode.Insert)
{
DV_Test.ChangeMode(DetailsViewMode.ReadOnly);
LoadDet();
}
}
I am using this code that forces the pageto stay the selected tab when post pack occurs and it works fine.
<script type="text/javascript">
var selected_tab = 1;
$(function () {
var tabs = $("#tabs").tabs({
select: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
});
I'm assuming you're using ASP.NET C# because of your tags and syntax. I can suggest these options: use Razor view, or use the JavaScript/jQuery you're already using.
If you prefer to use the Razor View, take a look at the references in this question and use the # symbol to call server functions. In this case, #ChangeMode is what you're looking for.
Since you're using jQuery already I suggest you write a JavaScript function using jQuery .click(). Since the JavaScript and jQuery are both able to call the server, you will be able to access your server-side function ChangeMode.
$('#tabs-2').click(function(){
//Make call to server here. You can use [Ajax][4],
//or see the link below concerning ASP.NET C#
});
link, see this fiddle
Ajax calls:
I've found the jQuery .ajax() call very useful, and this is what my .ajax() calls usually look like:
//get information from server and inject in my div with id="mydiv"
$.ajax({
url: '/ControllerName/MethodName',
type: 'POST',
data: ko.toJSON({myvariable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#mydiv').html('visiblity', 'visible');
},
error: function (error) {
alert('Cannot retrieve data');
}
});
Also, I'm not sure what you've decided on using, but I liked these suggestions for tabs: try the html found here, which uses ul/li and a to make the tabs themselves. The thing that triggers the action is typically the a.
Related
I have a VIEW, which contains a dataTable and jquery code which enables the dataTable rows to be clickable so that the user can click on a row and an ajax call is made to the server to fetch the detail of that row.
I've manage to make the dataTable row clickable, and called the Ajax function which under debug mode, I can see the POST method is being called. However, the Partial View which the returned by the POST method does not show up on my browser, even though I can see that my code is being called every step in debug mode..
My ajax/jquery is this (ive got this in a VIEW)
<script type="text/javascript">
$(function () {
$('#dTable tbody tr').on('hover', function () {
$(this).toggleClass('clickable');
}).on('click', function () {
var self = this;
$.ajax(
{
type: "POST",
url: "/TR/AllTHeaderTR",
data: { tID: $.trim($(this).find('td:first').text()) },
success: function (data) {
$('#dtable').html(data);
$(self).off('click');
}
});
});
</script>
I can see that when clicked, the code does move through the POST method, /TR/AllTHeaderTR, which ends up doing a : return PartialView("_AllTDetailTR", travlist);
Ive also tried to replace the above with just a normal HTML page with hard coded text, but the page does not render.
Im not clued up on jquery or ajax, so could someone please assist.
Thanks
Naren
I am using ASP.Net MVC and jQuery 1.8.2
I have a form with a button that calls this javascript when it is clicked:
$(function () {
$('#SearchButton').click(function () {
var data = $('#FilterDefinition :input').serialize() + "&PageNumber=1";
$.post('#Url.Action("Search")', data, LoadContentCallback);
$("#SearchResults").show();
});
});
This calls an MVC Controller Action which returns a PartialViewResult
On the Layout page I have the following JavaScript code:
//Add a custom header to all AJAX Requests
$(document).ready(function () {
$.ajaxSetup({
beforeSend: function(xhr) {
debugger;
if ($('[name=__RequestVerificationToken]').length) {
var token = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', token);
}
}
});
});
When the button is clicked for the first time, the beforeSend function is called correctly. However, if the button is clicked more than once (for example they change the search criteria and search again) then the beforeSend function never gets called again and the validate anti-forgery fails.
I tried using the ajaxSend event instead and I got the same results.
Any help is solving this problem would be greatly appreciated.
Thanks!
It turns out the problem was that the partial view that was being rendered was referencing a different version of jQuery. I removed this reference and everything started working correctly.
Thanks!
I would avoid using $.ajaxSetup if possible. I would just setup your beforeSend in the actual POST request.
I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.
I am simply looking to call a function when a form is loaded via ajax. My current code looks like this:
$('form').live("load",function() {...}
My ajax call looks like this:
jQuery.ajax({
type: "get",
url: "../design_form.php",
data: "coll=App_Forms&form=Step_1_Company_Sign_Up",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
}
})
I know that i could put my call inside the success portion of the ajax call but i am trying to minimize code and resuse other codes so i would really like to use the live feature.
I am loading a form via ajax and when that form is loaded i want to trigger a function using the jquery live. This works fine when i set it to "click"
$('form').live("click",function() {...}
but it is unnecessary to run this function on every click, i just need it to run once on the form load so that is why i want to use the load listener not the click.
Thank you.
Edit: I think you wanted to have custom code inside success callback which will be used in different pages so you don't want to duplicate the same ajax call in different pages. If so, then you should call a function inside that success callback and implement different version of that in different page.
jQuery.ajax({
type: "get",
url: "../design_form.php",
data: "coll=App_Forms&form=Step_1_Company_Sign_Up",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
afterFormLoad(); //Implement this function
}
});
function afterFormLoad() { } //dummy function defined in the common code
And in your specific page,
function afterFormLoad () {
//this is from page 1
}
Below just shows you about .live/.die and .one incase if you want to understand how to unbind it using .die.
You can unbind .live inside the click handler using .die,
DEMO
$('form').live("click",function(e) {
alert('clicked');
$('form').die('click'); // This removes the .live() functionality
});
You can use .one if you are using jQuery 1.7. See below code,
DEMO
$(document).one('click', 'form', function() {
alert('clicked');
});
There isn't a dom insert event.
Although, in javascript you can trigger anything
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000)
.trigger('ajax-load');
}
Then you can listen to event using
jQuery('#Right_Content').on('ajax-load', callback);
Triggering the event manually might be helpful for use in a couple of pages, but if you need it to use across entire application, you'll be better using a plugin such as provided by Oscar Jara
There is no load to trigger with jQuery live, try to read the API documentation: http://api.jquery.com/live/
On the other hand, you can use a plugin called livequery and do something like this:
$(selector).livequery(function() {
});
Use as reference:
https://plugins.jquery.com/livequery
https://github.com/brandonaaron/livequery
You may want to consider load() method which is a convenience method of $.ajax
http://api.jquery.com/load/
var data= "coll=App_Forms&form=Step_1_Company_Sign_Up"
jQuery('#Right_Content').hide().load("../design_form.php", data,function(){
/* this is the success callback of $.ajax*/
jQuery(this).fadeIn(1000);
});
I am developing a web application and am using jQuery to provide a good user interface for users. Therefore, I am using ajax requests and many jQuery functions.
If I disable JavaScript in the browser most of the function will not work because I am sending asynchronous ajax requests for many functions. But how can I handle this? Do I need to rewrite the code without using jQuery and ajax?
Find a below a sample button click event:
$("#renameCategory").live('click', function (event) {
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: '#Url.Action("UpdateCategoryName", "Category")',
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
How can I handle this?
Ajax requests and jQuery will not work when the client has JavaScript disabled. The best way to make this work is to use the URL from the <a> tag href like so:
Click Me!
$("#renameCategory").on('click', function (evt) {
//To prevent the link from sending the default request
//call preventDefault() on the jQuery event object
evt.preventDefault();
//
if ($.trim($("#CategoryNewName").val()) == "") {
alert("Please enter a category name");
return;
}
//GET THE URL FOR THE AJAX REQUEST
var actionUrl = $(this).attr('href');
//
var selectedCategory = $("#SelectedCategoryId").val();
var newCategoryName = $("#CategoryNewName").val();
var postData = { categoryId: selectedCategory, name: newCategoryName };
$.ajax({
type: "POST",
url: actionUrl,
data: postData,
dataType: "json",
success: function (data) {
$('#' + selectedCategory).text(newCategoryName);
$("#selectedCategoryText").html(newCategoryName);
},
error: function () { alert('error') }
});
});
You will also need to check for ajax requests in your Controller like below:
public ActionResult UpdateCategoryName() {
...
if(Request.IsAjaxRequest()) {
return Json(yourData);
}
return View();
}
This way, if your user has JavaScript disabled, the link will function like a normal HTTP request. If the user has JavaScript enabled, then they will get the Ajax experience. This is called graceful degradation.
Ajax call works when javascript is enabled.
You can handle it by server-side scripting, when javascript is disabled, you must do works by post/get requests, so you have to recode your web application.
If a lot of modification is needed for your website to work without javascript, then just force the users to enable javascript. One way to notify users to enable javascript is to use the noscript tag. http://www.w3schools.com/tags/tag_noscript.asp
View stackoverflow's page source to see how they use noscript
If JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code. The most common way to implement interactive web application other than Javascript is Flash, so you can still have a backup plan. You can also go with the old-school server side only generated dynamic pages.
Today, however it is very rare for someone not to have JavaScript enabled, so it should not be an issue at all.
Anyway you can make use of the <noscript> html tag to display a message to these users.
<script type="text/javascript">
... Js code ...
</script>
<noscript>You have JavaScript disabled in your browser. Please enable it.</noscript>
Obviously any functionality depending on script will not work if scripting is disabled, not available or incompatible with the environment it is trying to run in.
It is considered by many to be a good strategy to develop web applications so that they work without script support. You can then add scripting to improve the workflow and efficiency, but you will do so knowing that you have a fall back to a working system available if at any point the script should not run.
The discipline of designing and implementing a good workflow based on just HTML and forms may well lead to an easier interface to script and a more efficient workflow.
All too often developers throw together some minimal HTML and CSS, then try and do everything in script. The extreme is to have a DOCTYPE, title element, one block element and one script element that does everything. Not recommended.