How to keep a tab active after asp.net button event? - javascript

I would like to know how to keep a tab open after a button postback event, I could not get it to work using HiddenFields. I would like the second tab to stay open after a button click on the second tab however my code would always refresh to the first tab.
I have also tried to use an update panel instead of refreshing the entire page however the tabs would not toggle properly using this method.
I would prefer to not postback on every tab click as it affects the user experience. Is there any other codes to do this without affecting the fade aesthetics?
$(function () {
$('.tab-content:first-child').show();
$('.tab-nav').bind('click', function (e) {
$this = $(this);
$tabs = $this.parent().parent().next();
$target = $($this.data("target"));
$this.siblings().removeClass('active');
$target.siblings().css("display", "none");
$this.addClass('active');
$target.fadeIn("slow");
});
$('.tab-nav:first-child').trigger('click');
});
<ul class="tabs-nav d-flex" style="padding-left: 35px;">
<li class="tab-nav d-flex justify-content-center align-items-center" data-target="#tab_1">Overview</li>
<li class="tab-nav d-flex justify-content-center align-items-center" data-target="#tab_2">Expenses</li>
</ul>
<div id="tab_1" class="tab-content">
<p>abc</p>
</div>
<div id="tab_2" class="tab-content">
<p>abc</p>
<asp:Button ID="saveexpense" runat="server" Text="Save"/>
</div>

You may be better off creating a web method and calling that from your jQuery instead of trying something with update panels. Especially considering the performance problems update panels can cause.
You would move your save functionality into a web method like this
[WebMethod]
public static void SaveExpense(string data, string moredata)
{
//your save code here
}
and something like this in your front end
<button id="saveexpense">Save</button>
Then you can call your webmethod like this
$('#saveexpense').click(function () {
$.ajax({
type: "POST",
url: "CurrentPage.aspx/SaveExpense",
data: JSON.stringify({ data: $("#textbox").val(), moredata: $("#textbox2").val() }) ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("data saved");
},
error: function (jXHR, textStatus, err) {
console.log(err);
}
});
});

Related

Displaying API data on button click

I would like to make different news feed and trigger them on click. Currently i have different subpage on my website and when I click there it redirects me on another page, API shows the information. It looks like this.
Any ideas how i can setup same way but to trigger api on button without redirecting on another page. Ideal - I want to have a container which gonna keep different news feed and trigger different ones on click.
Sorry for lame question, novice in API's.
$(document).ready(function(){
let url = "https://newsapi.org/v2/everything?q=bitcoin&from=2020-04-01&to=2020-04-20&apiKey=APIKEY";
$.ajax({
url:url,
method: "GET",
dataType: "Json",
beforeSend: function(){
$(".progress").show();
},
complete: function(){
$(".progress").hide();
},
success: function(news){
let output = "";
let latestNews = news.articles;
for(var i in latestNews) {
output +=`
<div class="col">
<div class="card-content">
<h5>${latestNews[i].title}</h5>
</div>
</div>
<div class="published">
<h6>${latestNews[i].publishedAt}</h6>
</div>
<div class"card-reveal">
<p>${latestNews[i].description}</p>
</div>
`;
}
if(output !== ""){
$("#newsResults").html(output);
}
},
error: function(){
$("#newsResults").html("Some error occured");
}
})
});
You can add a listener to a button click using jQuery like so:
// Suppose your button has id='target'
$( "#target" ).click(function() {
your api call here
});
https://api.jquery.com/click/

Reload Tab content using ajax without loading page on Refresh

Reload Tab instead of Whole Page
<div class="content">
<div id="tabstrip">
<ul>
<li id="tabEdit">#ResourceStrings.Text_ProblemDetails</li>
<li id="tabItemsAffected">#ResourceStrings.Text_ItemsAffected</li>
<li id="tabAttachments">#ResourceStrings.Text_Attachments</li>
#if (ApplicationGlobals.SELECTED_COMPANY_CODE != CompanyCode.MONTREAL)
{
<li id="tabPlmReferences">#ResourceStrings.Text_PlmReferences</li>
}
<li id="tabDispositions">#dispositionsText</li>
#if (ApplicationGlobals.SELECTED_COMPANY_CODE == CompanyCode.MONTREAL && (ApplicationGlobals.SELECTED_NCRBASE.NcrType != (int)NcrTypeEnum.NCRATTEST))
{
<li id="tabReworkDetails">#ResourceStrings.Text_ReworkDetails</li>
}
<li id="tabLineClosure">#ResourceStrings.Text_Line_Approval</li>
<li id="tabTraceability" style="float:right">#ResourceStrings.Text_Traceability</li>
</ul>
</div>
</div>
Is it Possible to update parts (Like Tabs) of a web page, without reloading the whole page on switching to another Tab
$.ajax({
url: "NcrLine/Reload",
type: "GET",
async: false,
dataType: "json",
success: function () {
alert("Hello");
var tab = $('#tabstrip').tabs('getSelected');
tab.panel('refresh');
}
});
First thing I need to understand is what type of updates are those, if those have simple rendering of code, you can simply bind the HTML code to the tabs handle once you receive the response. This is shown as below -
$.ajax({
url: "NcrLine/Reload",
type: "GET",
async: false,
dataType: "json",
success: function () {
alert("Hello");
var tab = $('#tabstrip').tabs('getSelected');
tab.panel('refresh');
// Add css to the selected tab
$('#tabstrip[selected=selected]').css('css-property', 'css-value');
//Render complete new HTML code of updated tabstrip
$('#tabstrip').html('<Your tabstrip HTML template>');
}
});
If you have complex HTML rendering, then I would suggest you to create partials by using handlebars.js, that will help you to create reusable partials with dynamic values and that can be bind to your content page.

How to refresh an element using AJAX?

I have an element for ex. <div>. and in that I have fetched dynamic contents from database, I am already performing some database operation using AJAX and I am able to load some part of my page from other php file, but on the same page I want my other div to be repopulate its data from database.
This is my manage_your_listing.php
<div class="col-sm-12 pd">
<ul class="nav nav-tabs notificationtabs">
<li class="active">Live On Site</li>
<li>Pending Review</li>
<li>Pause</li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane fade active in" id="live_on_site" >
<?php
include'manage_order/live_on_site.php';
?>
</div><!-- End tab1-->
<div class="tab-pane fade" id="pause" >
<?php
include'manage_order/pause_order.php';
?>
</div><!-- End tab2 -->
</div><!-- End tab-content -->
this is my live_on_site.php's AJAX function
function ConfirmPause(prod_id){
$.ajax({
type: "get",
url: "seller/manage_order/live_on_site_pause.php?prod_id="+prod_id.id,
cache: false,
dataType: "html",
asyc: false,
success: function (data) {
$("div#live_prod").html(data);
}
});
}
so finally my live_on_site.php's live_prod div is being repopulated with the contents of live_on_site_pause.php
but what I want is, there is div in pause_order.php which is accessible in every php file specified here, and that div is being populated with some database content by using select statement, and I want it just to refresh, Is it possible? or do I need to create a new php file and call it using ajax?
I solved it by using nested ajax function.
I wanted to refresh one div after processing of some database update using ajax, But later I found that there is no way ajax can refresh div, it just copies some data from source position and paste it into specified position. So while success of previous ajax function I typed one more ajax function which worked for me.
function ConfirmPause(prod_id)
{
if (confirm("Pause Product?"))
{
$.ajax({
type: "get",
url: "seller/manage_order/live_on_site_pause.php?prod_id=" + prod_id.id,
cache: false,
dataType: "html",
asyc: false,
success: function (data) {
$("div#live_prod").html(data);
//nested ajax to change pause products tab real time the moment user pauses a product it will get removed from live tab and will be added to pause products tab
$.ajax({
type: "get",
url: "seller/manage_order/pause_order_resume.php",
cache: false,
dataType: "html",
asyc: false,
success: function (data) {
$("div#pause_prod").html(data);
}
});
}
});
}
}
you cant just refresh an element with ajax, you can either process something in ajax or in other file and replace it with old contents using ajax.

when loading a page content through ajax post and codeigniter load functions, some jquery functions are in the head section cannot be called

I know My question Title is not perfectly describe my question extremely sorry about that. I don't know how to tell this as a summery. anyway this is my question.
I am making a admin panel to change some of the content in my web page. this scenario is for change slideshow images.
ok then after someone logged into my page I am loading three pages. like this.
$this->load->view('admin/header');
$this->load->view('admin/menu');
$this->load->view('admin/table_and_editor_holder');
all the page contents I have mentioned below. so basic path is like this. once someone logged he can click the button [slide manage] to load the images and details of already inserted slides. these are getting from a database. so once he clicked the menu button. this jquery function is executing.
$('.menu-item > a').on('click', function() {...})
this function simply getting a html page. filled with previous slide details. this is the controller function handle the menu request.
function slider_edit_delete() {
$sdata['slide_imgs'] = $this->admin_basic_curd->get_all_items('sider_images');
$slide_manager = $this->load->view('admin/slider_manager', $sdata, TRUE);
echo $slide_manager;
}
so previous jquery function is then appending this page content to a div like this.
$('#table_container').html(data);
so inside this page content I have a buttons call edit for each slide already inserted. so by clicking on of this button I can edit that slide image or some test content of it. that button is like this.
<a class="onclick_post_by_a" href="<?php echo base_url() . 'adm_edit_this_slide/' . $sl->id; ?>">
<button class="btn btn-info"> Edit </button>
</a>
so by clicking this button must execute this function in the header section and this function must add a html form (in a separate page) to the #editor-form-container div as previously
$('.onclick_post_by_a').on('click', function() {...})
but the problem is once I click the edit button it couldn't find this function. so it is opening the content as a separate page
How can I make this to work? Thank you
the header page contains all the css and js file links. and some jquery functions. like this.
<script>
$(document).ready(function() {
$('.menu-item > a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#table_container').html(data);
});
return false;
});
$('#editor-form-container').css({
display: "none"
});
function posting_url(url, pdata) {
return $.ajax({
url: url,
data: pdata
});
}
$('.onclick_post_by_a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#editor-form-container').css({
display: "block"
});
$('#editor-form-container').html(data);
});
return false;
});
$('.post_with_image').on('submit', (function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
}));
});
</script>
</head>
then I have load menu page. it is like this.
<div class="admin-navi">
<div class="menu-item">
Home
</div>
<div class="menu-item">
Side Manage
</div>
</div>
<div class="clearfix"></div>
table_and_editor_holder.php page. it is like this.
<div class="col-lg-12">
<div class="col-lg-2"></div>
<div id="table_container" class="col-lg-8">
</div>
</div>
<div id="editor-form-container" class="col-lg-6">
</div>
Dynamically created element does not respond to direct call to events like below -
$('.onclick_post_by_a').on('click', function() {...})
So you have to write like this
$(document).on('click', '.onclick_post_by_a', function() {...})
Just try it out.

HTML5 jQuery .animate()({scrollTop: }); not working as intended

I am writing my first HTML5 based app using XDK. I have successfully connected it to a simple local .vb based web service for mock user login validation. Upon a successful log in I wish to load a new div into the view so that my navigation within the app is consistent in look and feel.
Navigation being performed from the main page works as follows:
<ul class="list widget uib_w_3 d-margins" data-uib="app_framework/listview">
<li class="widget uib_w_4" data-uib="app_framework/listitem">
<a class="icon user" href="#login_page">Login
</a>
</li>
<li class="widget uib_w_5" data-uib="app_framework/listitem">
<a class="icon pencil" href="#register_page">Register
</a>
</li>
<li class="widget uib_w_6" data-uib="app_framework/listitem">
<a class="icon settings" href="#settings_page">Settings
</a>
</li>
<li class="widget uib_w_7" data-uib="app_framework/listitem">
<a class="icon paper" href="#acc_management_page">Acc Managment
</a>
</li>
</ul><span class="uib_shim"></span>
Everything above works great, and as intended. Upon clicking/touching the Login button you are taken to the login_page, and you have an input field for username and password. The login is handled by a jQuery script which verifies the information via a vb.net web service. The login verification is working as intended. Upon a user entering their username and password they click the Login button and an onClick event calls the jQuery script which is as follows:
function verifyInfo(){
var uName=document.getElementById("l_username").value;
var pWord=document.getElementById("l_password").value;
$.ajax(
{
type: 'POST',
url: 'http://localhost/TestWebService/Verify.asmx/UserVerify',
data: "{ \"username\":\""+uName+"\",\"password\":\""+pWord+"\"}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
if(data.d == "true"){
alert("Correct Login Credintials");
}
else{
alert("Incorrect Login Credintials");
}
alert(data.d);},
error: function(data){alert('Failed on :'+data.d);}
});
}
To achieve the functionality that I want I have added the following piece to this script:
function verifyInfo(){
var uName=document.getElementById("l_username").value;
var pWord=document.getElementById("l_password").value;
$.ajax(
{
type: 'POST',
url: 'http://localhost/TestWebService/Verify.asmx/UserVerify',
data: "{ \"username\":\""+uName+"\",\"password\":\""+pWord+"\"}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
if(data.d = "true"){
alert("Correct Login Credintials");
//Added functionality
$('html,body').animate({
scrollTop: $("#acc_management_page").offset().top
});
//End of added functionality
}
else{
alert("Incorrect Login Credintials");
}
alert(data.d);},
error: function(data){alert('Failed on :'+data.d);}
});
}
This should, if I understand it correctly, fire the animation call to navigate to the appropriate div, in our case acc_management_page. This method of navigation works fine from my navigation menu but is not working from the script. The login is validated all alerts fire as intended but the acc_management_page is never scrolled to. Any suggestions and or solutions would be greatly appreciated.
Thanks!
Did you try add an "id" attribute to the anchor tag. jQuery is looking for the id not a href.
LOOK AT THIS Demo
Works like a charm :)
$('.uib_w_4').click(function () {
alert('Now I will ask you if your login is ok ! to simulate Login Form');
if (confirm('Login with success !?')) {
letsAnimate();
} else {
// Do nothing!
alert('Login Failed');
};
});
function letsAnimate() {
$('html,body').animate({
scrollTop: $("#acc_management_page").offset().top
});
};
Also check your CSS file, if content div is not set properly (height, position fixed/relative etc) , could generate some unexpected behavior.
LOOK AT THIS Demo
I had same problem, but finally I've found the div class that is responsible for scrolling and managed to scrollTop it using css (I've found that XDK scrolling is implemented in the same way - I'm just resetting it to unscrolled params value):
$('.afScrollPanel').css('transform', 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)');

Categories