Can any of you see why the div (#welcome) is not being updated in the below code?
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;
change_div();
},
error: function() {
alert("ERROR in show_logged_in")
}
});
function change_div(){
$('#welcome').style.display = 'block';
$('#welcome').innerHTML = "Welcome" + user + "to SIK";
}
}
The response from the ajax called is simply grabbing the username from the session variable. and it is returning correctly.
And when it returns i would like the div to show up and say welcome.
But for some reason the div is not being updated.
Here is the html:
<div id="welcome" style="display:none; postion:absolute; top:0; float:right;">...</div>
You can't do
$('#welcome').style.display = 'block';
$('#welcome').innerHTML = "Welcome" + user + "to SIK";
with jquery. This is because with $('#welcome') you are grabbing the jQuery object, not the DOM element.
To do this with jQuery:
$('#welcome').html('Welcome' + user + 'to SIK').show(); // Brought up in comments
$('#welcome').show(); // Old
$('#welcome').html('Welcome' + user + 'to SIK'); // Old
Or if you really want to grab the DOM Element:
$('#welcome')[0].style.display = 'block';
$('#welcome')[0].innerHTML = "Welcome" + user + "to SIK";
#Jeff Shaver is right but Pass user as argument change_div(user);
then
function change_div(user){
$('#welcome').show();
$('#welcome').html('Welcome' + user + 'to SIK');
}
try this friend..
$.ajax({
type:"POST",
url:"PHP/class.ajax.php",
data:dataString,
dataType:'JSON',
success: function(username) {
alert("User is shown");
user = username;
change_div(user);
},
error: function() {
alert("ERROR in show_logged_in")
}
});
function change_div(user){
$('#welcome').css("display","inline");
$('#welcome').append("Welcome" + user + "to SIK");
}
The display property does not exist.
$('#welcome').style.display = 'block';
Use this instead:
$('#welcome').css({"display":"block"});
I'd stick to pure JS with this code.
var welcome = document.getElementById('welcome');
function change_div(){
welcome.innerHTML = "Welcome" + user + "to SIK";
welcome.style.display = 'block';
}
Related
I'm making a script that when a user clicks a button a popup box displays with a text box of the tweet and a button for the user to retweet what's in the text box. In the script it's suppose to tell the user if it has retweeted successfully. The thing is that it tells the user it's successfully retweeted before the user has clicked the retweet button in the pop up box.
Seems as though just by clicking the button that activates the pop up box display is when the code activates a successful retweet message though nothing has been retweeted on the users end.
I'm not very familiar with javascript, my guess it's not the php code that's making the faulty logic but the javascript code. Here is what I have below.
(function($) {
$(document).ready(function() {
$.getScript("http://platform.twitter.com/widgets.js", function(){
twttr.events.bind('tweet', function(event) {
var targetUrl = event.target.src;
var query = getQueryParams(targetUrl);
click_callback(query.url);
});
});
});
})(jQuery);
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
function click_callback(id){
var user = "<? echo $data->id;?>";
document.getElementById("Hint").style.display='block';
$("#Hint").html('Confirming Tweet...');
$.ajax({
type: "POST",
url: "plugins/rt/complete.php",
data: "id="+ id + "&user=" + user,
success: function(msg){
$("#Hint").html('Tweeted! Success!');
removeElement('boxes', id);
}
});
}
function removeElement(parentDiv, childDiv){
if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
}
I think this is what's causing it within the code:
function click_callback(id){
var user = "<? echo $data->id;?>";
document.getElementById("Hint").style.display='block';
$("#Hint").html('Confirming Tweet...');
$.ajax({
type: "POST",
url: "plugins/rt/complete.php",
data: "id="+ id + "&user=" + user,
success: function(msg){
$("#Hint").html('Tweeted! Success!');
removeElement('boxes', id);
}
});
}
Basically what I'm trying to do is have a search bar. The user should input the state and city. Once I get the state and city, update the html with the result. The problem is once i enter an invalid state or city, it gives me an error in the console. What i want is an alert telling the user that they have made a mistake in entering the city or state. I tried using a try and catch/ ajax error function but it doesn't seem to work. Need some help thanks !
$(document).ready(function() {
setTimeout(function(){
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search= $('#search');
var searchsubmit= $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
try {
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}catch(err){
alert(err.message);
}
});
});
I think that adding the error callback should work, here is a jsbin:
https://jsbin.com/ciwosoqeye/edit?html,js,output
var searchresult = '';
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/" +
searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
},
error: function(jqxhr, errorString, ex) {
alert(ex);
}
});
as defined in the doc
Without knowing what error message you are getting or what parsed_json looks like with a bad request, this is only a guess but parsed_json probably doesn't have a location property and/or a city property when bad data is passed in. I'm guessing that is causing the error. If this is the case, you can check for the existence of parsed_json.location and parsed_json.location.city before trying to access them and display the error if they don't exist.
$(document).ready(function() {
setTimeout(function() {
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search = $('#search');
var searchsubmit = $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
if (parsed_json.location && parsed_json.location.city) {
var location = parsed_json.location.city;
var temp_f = parsed_json.current_observation.temp_f;
alert("Current temperature in " + location + " is: " + temp_f);
} else {
alert(err.message);
}
}
});
});
});
Setting a break-point at the beginning of the success callback and inspecting parsed_data would help in debugging this sort of thing.
I understand that I can get the facebook id by doing:
FB.api('/me', function(response) {
alert('Your id is ' + response.id);
});
However, I want to have the user login and then grab that id in a different file so I can handle it. Right now I have:
var id = "";
var fburl = "http://graph.facebook.com/" + id + "?callback=?"
$(function(){
$("#fb-profile-picture")[0].src = "http://graph.facebook.com/" + id +"/picture";
$.getJSON(fburl, function(data){
console.log(data);
$("#name").append(data.name);
$("#user-id").append(data.id);
});
});
and if I manually enter the id in the id var it works however I'd like to be able to grab that response.idas the value and use it in this other javascript file but I haven't figured out how to.
Assuming you
cannot control which of the scripts is executed first
you are working in an environment with a global window object
part one is only executed once
you are using jQuery
making a global and firing an event might be a solution, although not considered best practice.
Script 1:
FB.api('/me', function(response) {
window.fbCustomId = response.id;
console.log(window.fbCustomId);
$(window).trigger('fbResponseLoaded');
});
Script 2:
function renderProfile() {
var fburl = "//graph.facebook.com/" + window.fbCustomId + "?callback=?"
$(function () {
$("#fb-profile-picture")[0].src = "//graph.facebook.com/" + window.fbCustomId + "/picture";
$.getJSON(fburl, function (data) {
console.log(data, window.fbCustomId);
$("#name").append( $('<span>').text(data.name) );
$("#user-id").append( $('<span>').text(data.id) );
});
});
}
if (window.fbCustomId) {
renderProfile();
} else {
$(window).on('fbResponseLoaded', renderProfile);
}
I want to show a div if the comment field is empty out instead of showing an alert. How can I do this? My other question is, the data is displayed after some seconds. During that loading period is possible to to add a loading image?
<script type="text/javascript">
$(function () {
// on post comment click
$('.bt-add-com').click(function () {
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
if (!theCom.val()) {
alert('You need to write a comment!');
} else {
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post=' + <? php echo $id_post; ?> +'&name=' + theName.val() + '&email=' + theMail.val() + '&comment=' + theCom.val(),
success: function (html) {
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function () {
$('.new-com-bt').show('fast');
$('.new-com-bt').after(html);
})
}
});
}
});
});
</script>
I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );