Javascript HTML button click not working - php

I've created a login system using HTML, JavaScript, Ajax and PHP.
I'm trying to implement the log out function now, here's what I have:
First there is a div in my html, which says welcome to anyone on the site not logged in:
<div id="welcome" style="postion:absolute; top:0; float:right;">Welcome to SIK!!!!</div>
I then have a JavaScript function which is called when a user is logged in or registered to amend the div to say hi to the specific user, and show a log out button.
function show_logged_in(success)
{
var is_logged_in = success;
var dataString = {"reg":invalid, "login":invalid,"is_logged_in":is_logged_in};
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data:dataString,
dataType:'JSON',
success: function(username) {
alert("User is shown");
user = username;
$('#welcome').html('<p>Hi ' + user + '</p><p><button id="logout_but"
type="button">Log Out</button></p>');
},
error: function() {
alert("ERROR in show_logged_in");
}
});
}
And then when the user clicks logout, in my main js file there is a function:
$("#logout_but").click(ui.logout);
here is my main js file altogether:
$(document).ready(function(){
//----------Login/Register Gui --------------
$('#load-new').hide();
$('#reg').hide();
$('#login').hide();
//create new instance of gui class
var ui = new Gui();
//if login_but is clicked do ui.login function
$('#login_but').click(ui.login);
//if reg_but is clicked do ui.register function
$('#reg_but').click(ui.register);
//if login_sumbit button is clicked do ui.login_ajax function
$("#login_submit").click(ui.login_ajax);
$("#reg_submit").click(ui.register_ajax);
$("#logout_but").click(ui.logout);
});
So now you can see the order of the calls, and also the click function that is called for the logout button is:
this.logout = function() {
alert("clicked");
var dataString = {"is_logged_out":invalid};
$.ajax({
type:"POST",
url:"PHP/class.logout.php",
data:dataString,
dataType:'JSON',
success: function(success){
alert("User is logged out");
$('#welcome').html('<p>Welcome to SIK</p>');
},
error: function() {
alert('ERROR in log out');
}
})
}
As you can see I have and alert at the top of the last function I posted to show me if the function is actually being called.
My problem is when I click the logout button nothing happens. I also don't see the alert, thus the problem is occurring on the click.
Any help with this situation would be great.

That's because you create the logout button dynamically and AFTER the click handler is trying to attach itself to the element in your main js file. As a result, the handler doesn't find the #logout_but element and therefore doesn't attach to anything.
To fix that, you could use a delegate instead of a click handler:
Replace this:
$("#logout_but").click(ui.logout);
with
$("#welcome").on("click", "#logout_but", ui.logout);

Related

Posting to a PHP script with Ajax (Jquery)

I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick

calling on a complex function with onClick (ajax)

So I have this chunk of code here (below). It waits for a video to finish playing and then it looks up a cookie, sends that info to a php script through ajax, gets back a url from json, and reloads an iframe with a new url.
So I think you'll agree, it's sorta a lot going on.
Its purpose is to advance ONE forward in a playlist of videos. I am trying to create a button area where a user can click a >> sort of button and go forward. Which is exactly what this function does.
Rather than starting from scratch with a new function, is there a way to activate all of the above function functionality (ajax and all) when the user clicks that button?
<script>
function ready(player_id)
{
$f('play').addEvent('ready', function()
{
$f('play').addEvent('finish', onFinish);
});
function onFinish(play)
{
var now_video_var = $.cookie('now_video');
console.log ('player ' + now_video_var + ' has left the building');
var intermediate_integer = parseInt(now_video_var);
var request2 = $.ajax({
url : "geturl.php",
data : {intermediate_integer : intermediate_integer},
type : 'post'
}).done(function(data) {
var gotfrom = jQuery.parseJSON(data);
var NEWURL = gotfrom[1] ;
console.log(gotfrom);
console.log(data);
console.log(gotfrom[1]);
var theiframeforrealyo = document.getElementById('play');
$(theiframeforrealyo).attr("src", "http://player.vimeo.com/video/" + gotfrom[1] +"?api=1&player_id=play&title=0&byline=0&portrait=0&autoplay=1");
var new_video_var = intermediate_integer +1;
$.cookie('now_video', new_video_var);
console.log ( 'cookie function ok: the cookie is....');
console.log ($.cookie('now_video'));
});
}
}
window.addEventListener('load', function() {
//Attach the ready event to the iframe
$f(document.getElementById('play')).addEvent('ready', ready);
});
</script>

ajax inject html into a div but keep the html elements including their ids

I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};

Linked JavaScript is loaded multiple times when done with AJAX

I am experiencing the strangest behaviour on our website, and it is making things incredibly slow.
My team and I have a website running entirely on AJAX. So for the login, I have some js ajax that loads the login box into our index page. The html containing the login box has a script link in the head. This script listens for the login form submission, and sends the form data to the server for authentication through ajax.
The html that contains the login box only gets loaded once, but the js file that it links to gets loaded multiple times. The amount of times change. From 5 times to 15 times and I cannot see a pattern or anything. This happens everywhere on our site, not just at login time.
This issue really has me stumped and I'm totally stuck. Is it because I have ajax in a js file that is loaded in initially with ajax?
I would really appreciate your insight and help!
EDIT:
As requested, some code:
This is a stripped down version of loadContent() in the Interface.js file. This specific function loads all site content into the content area on index.php. When the page is refreshed, the first thing sent to the function is the location of the login.php file, containing the login box:
loadContent: function(page) {
var self = this;
//just some animations to make things look good
$(self.error).fadeOut(150, function() {
$(self.content).fadeOut(150, function() {
$(self.loading).fadeIn(150, function() {
$.ajax({
url: page,
success: function(data) {
//response data
var $response = $(data);
$(self.content_1).html($response);
//definitions for contentbox-2
self.contentHeading_2.html("Replies:");
self.content_2.html(postReplies);
//redisplay the content after it has loaded in.
$(self.loading).fadeOut(150, function() {
$(self.content).fadeIn(150, function() {
// Content faded in
});
});
},
error: function() {
$(self.loading).fadeOut(150, function() {
$(self.error).fadeIn(150, function() {
// Error faded in
});
});
}
});
});
});
});
this.page = page;
}
And then the login.php file:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" src="js/login.js"></script>
</head>
<body>
<div class="padded loginphp">
<div id="loginbox">
<!-- the login box comes here
</div> <!-- #loginbox -->
</div>
</body>
</html>
And the login.js file:
$(document).ready(function() {
$('#honeyloginform').submit(function(event) {
//event.preventDefault();
login();
return false;
});
});
function login() {
$('.errorinputfields').removeClass('errorinputfields');
if (isEmpty($('#username'))) {
$('#username').addClass('errorinputfields');
$('#username').focus();
return;
}
if (isEmpty($('#password'))) {
$('#password').addClass('errorinputfields');
$('#password').focus();
return;
}
$('#honeyloginform').fadeOut(100, function(){
$('#loginbox .loading').fadeIn(300, function(){
var pword = $('#password').val();
var remember = "no";
if ($('#remember').is(':checked')) {
remember = "yes";
}
var JSONobj = {
username: $('#username').val(),
password: pword,
rem: remember
};
$.ajax({
url: 'ajax/login.php',
data: JSONobj,
success: function(data) {
//alert(data);
var JSONobj = JSON.parse(data);
if (JSONobj.Success) {
Interface.login(); //just loads the landing page after login
//window.setTimeout('location.reload()', 300);
} else {
$('#loginbox .loading').fadeOut(300,function(){
$('#honeyloginform').fadeIn(300);
});
$('#username').focus();
$('#loading-message').text(JSONobj.Message).show();
}
}
});
});
});
}
I've managed to find the problem, and fix it!
I've made a change to my interface layout, and as a result, the three selectors, $(self.error), $(self.content) and $(self.loading) each contain more than one element, where it always only contained one each.
This seems to cause the callback functions to be compounded or something, as everything inside the final callback in loadContent() was called 9 times.
So it was a simple case of redefining the selectors, so that they refer to one element each.

ajax jquery doesnt work on ie

Hey guys. I'm usign a js/ajax script that doesnt work with internet explorer. Firefox its ok.
Btw the head tag, im using this:
$(document).ready(function () {
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "http://pathfofolder/js/loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
The loader.php contain the php code to get pages, something like:
switch($_GET['page']) {
case '#link1' : $page = 'contenthere'; break;
}
echo $page;
So, on the links, i'm using Link 1 to load the content into the div content.
The script does works well with firefox, but with internet explorer it doesnt load the content. Could someone pls help me to fix this?
It not go into the success function at all on IE, and i'm getting no html error from IE too.
Best Regards.
Make sure your html is sounds. FF tends to auto fix the syntax.

Categories