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
Related
What went wrong in this code? I ready many post here on this issue but can't fix my error. I have the following.
HTML Code
<div id="successMessage" style="display:none;"> It worked </div>
<div id="failMessage" style="display:none;"> It failed </div>
<div container>
<div class="modal">
<form>
....
</form>
</div>
</div>
PHP Code
if(!$stmnt->execute()){
echo "Failed!";
}else{
echo "Inserted";
}
AJAX Code
success: function(data){
viewData();
if (data=="Failed!") {
console.log(data);
$("#failMessage").show();
} else if(data=="Inserted"){
console.log(data);
$("#successMessage").show();
}
}
Problem: I would like to display the error in the page not in console. I want to inform the user. Why is it not working with $("#successMessage").show();?
PS: I am using Bootstrap. Also how can I show my messages using one(1) div="msg" tag?
Found a mistake in your code
PHP Code
if(!$stmnt->execute()){
echo "Failed!"; // Check the exclamation mark
}else{
echo "Inserted";
}
AJAX Code
success: function(data){
viewData();
$('#addData').modal('hide');//close the modal.
if (data=="Failed!") { // Add an exclamation mark to correct code
$("#failMessage").show();
//console.log(data); is showing message from PHP
} else if (data=="Inserted") { // Change this else to else if
$("#successMessage").show();
//console.log(data); is showing message from PHP
}
Change "Failed" in ajax to "Failed!". Also, change the else to correct format of else if
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.
I have divided my content in two tabs and switching between two tabs with javascript.
<div class='tab-container'>
<div class='tab-1'>
<?php
$sql="SELECT * FROM posts WHERE status='tab1'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
<div class='tab-2'>
<?php
$sql="SELECT * FROM posts WHERE status='tab2'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
</div>
Php code divides content between tabs through WHERE clause select * from posts where status='tab1'; so to remove post from one tab ajax request given below triggers php code which updates status of content from tab1 to tab2.
<script type="text/javascript">
$(function() {
$(".restore").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Restore?"))
{
$.ajax({
type: "GET",
url: "restore.php",
data: info,
success: function(){
}
});
$(this).parents(".db").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
So that post is removed from tab1. Idea here is to move post from one tab to another through ajax. javascript works good on removing post from one tab however for making that post appear in another tab I have to reload page as I haven't used ajax for that. So problem is I don't get how to add that post dynamically to another tab through ajax without refreshing page.
To get content from ajax call, you have to echo it in server side.
May be something like this
echo "hi, this is new content";
Now in ajax success
success: function(data){
alert(data); this will alert what was echoed in php(hi, this is new content)
}
If you want to add the content to some div in view,
$("class or id for the div").html(data);
In restore.php, you should get the selected post and then then update the status of that post to tab2. And append that result in main php page. You can append the same via restore.php.
Try this
HTML
<div class="tabs" id="d-tab1"></div>
<div class="tabs" id="d-tab2"></div>
<a href="#" class="restore" id="tab1">
<a href="#" class="restore" id="tab2">
JS
$('.restore').click(function(e){
e.preventDefault();
var $tab = $(this);
$.post('restore.php',{id: $tab.attr('id')},function(html){
$('.tabs').hide();
$('#d-'+$tab.attr('id')).html(html).show();
})
})
Or use Jquery tabs https://jqueryui.com/tabs/
Agree with #Niranjan N Raju. But want to add some addition.
Use console.log(data) instead alert(data) as last don't shows object info.
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.
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)');