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

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)');

Related

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

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);
}
});
});

Using browser console to send ajax data

I have a PHP quiz page which posts answer data on clicking the answer by a function called answer() via ajax then loads the question and answer contents if the answer is correct by loadQuestion() function also via ajax. Here is a part of my code:
<ul class="choices">
<li><span id="a0"><?php echo $questionDetail['a'.$answerOrder[0]]; ?></span></li>
<li><span id="a1"><?php echo $questionDetail['a'.$answerOrder[1]]; ?></span></li>
</ul>
<div id="countdown"><div class="saniyeLoading" style="display: none;"></div></div>
<ul>
<li><span id="a2"><?php echo $questionDetail['a'.$answerOrder[2]]; ?></span></li>
<li><span id="a3"><?php echo $questionDetail['a'.$answerOrder[3]]; ?></span></li>
</ul>
<script type="text/javascript">
function answer(elm){
countdown.stop();
var answer = $(elm).text();
$.ajax({
type: 'POST',
url: "/soru",
data: {act: 'soru', answer: answer},
success:function (data) {
if(data == "success"){
setTimeout(loadQuestion, 300);
} else {
location.href = "/yanlis";
}
}
});
}
function loadQuestion() {
$.ajax({
type: 'POST',
url: "/",
data: {act: 'ysoru'},
success: function (data) {
try {
data = $.parseJSON(data);
$("#questionDetailQuestion").text(data.questionDetail['question']);
$("#a0").text(data.questionDetail['a0']);
$("#a1").text(data.questionDetail['a1']);
$("#a2").text(data.questionDetail['a2']);
$("#a3").text(data.questionDetail['a3']);
$('.saniyeLoading').hide();
countdown.start();
} catch (e) {
}
}
});
}
</script>
My problem here is that people can manipulate the answer() function by writing a simple for loop in the browser developer console. Something like this:
for(i = 1 ; i <= 4; i ++ ) {
$.ajax({
type: 'POST',
url: "/soru",
data: {act: 'soru', answer: $('#a' + i).text()},
success:function (data) {
if(data == "success"){
loadQuestion();
}
}
});
}
I have found a temporary solution by removing onclick="answer(this);" and replacing answer() function with $('.choices a').click(). Then I'm validating if there is a click event in my PHP page by sending the event via my ajax page.
Would there be a better solution to this problem? I've tried tokens but the problem is as I'm loading questions via ajax, I will have to save the token in an hidden input etc, they can get also get the token and send it.
While there is no way you can stop user from using console to manipulate your code. I can suggest following:
You can put server side limit on number of Ajax requests accepted from single user.
Adding captcha code, if you see unusual activity
Obfuscate your code and AJAX call format, so it requires more effort from user to analyze code and will stop most of people
Use dynamically generated image with answers "radio buttons" located at random locations and submitting back x and y position of user click event and use server-side logic to match click position with answer option
Use sessions on the server-side to track each user's correct and incorrect guesses, and enforce the rules.
As long as you rely on the client side to "play nice", you're exposing your application to the will of the end user.

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.

Can Ajax update a dynamic navigation menu?

I'm using a PHP function to determine what links are being displayed:
<?php
//amend toplinks if logged in
if($general->loggedIn()){ ?>
<nav class = "memberHeaderArea">
<ul>
<li>
Profile<span class="user icon"></span>
</li>
<li>
Log out<span class="lock icon"> </span>
</li>
</ul>
</nav>
<?php
//toplinks for when not logged in
}else{ ?>
I've just changed the structure of my login to use Ajax and it works perfectly with the exception of the nav. It still shows login / register until a page refresh is called. Obviously the reason for using Ajax was to avoid the page refresh, but is there a way I can update these links within the success function?
success: function(data) {
$("#statusLogin").hide();
if(data.success == true){
$('#loginContent').slideToggle();
}else{
// alert("data.message... " + data.message);//undefined
$("#error").show().html(data.message);
}
From what I've found, it looks like I may need to assign the nav's id and then use Ajax / jQuery to target that. But I'm not sure how. Any help greatly appreciated.
This is a basic (and dummy) stuff for checking login status with AJAX after page loading. Probably you want more serious check then if(true) and an echo call, but it will be something like this :) Check the fiddle below, so you can see the html and the css too...
$.getJSON('/echo/json/').done(function (data) {
console.log("Call returned");
if (true){
//successful login
$('#loggedin').slideToggle();
}else {
//unsuccessful login
$('#login').slideToggle();
}
}).fail(function (data) {
console.log("Call failed");
$('#login,#error').slideToggle();
}).always(function (data) {
console.log("Always running");
});
JSFiddle

Categories