jQuery append is executed when leaving the page aswell - javascript

I'm experiencing a really weird behaviour. I call a function when I change to a page (jQuery Mobile event "pagebeforeshow") like so:
$("#library").on("pagebeforeshow", function(event){
player.loadFiles();
});
The function I call looks like this:
Player.prototype.loadFiles = function(dir) {
dir = dir == undefined ? 'file://~' : dir;
if(dir.indexOf(data.lastDir) != 0){
console.log("fired");
$("li.item").remove();
$.ajax({
url: 'http://' + data.ip + ":" + data.port + '/requests/browse.xml',
data: 'uri=' + encodeURIComponent(dir),
dataType: "xml",
success: function (data, status, jqXHR) {
if(dir.indexOf(data.lastDir) != 0){
var html = "";
$(data).find("element").each(function(){
html += '<li class="item">' + $(this).attr('name') + "</li>";
});
$("#filelist").append(html);
$(".item").addClass("ui-li ui-li-static ui-btn-up-a ui-first-child ui-last-child")
}
},
error: function (jqXHR, status, error) {
alert("fail")
}
});
data.lastDir = dir;
}
}
Now it works fine if I visit the page for the first time. It appends the listitems to the ul #filelist and sets the variables right. Now when I leave the page it adds them again. The "fired" is not shown in the console though. If I visit the page again, they aren't added again, but if I leave it again they are. I can't figure out, why it's behaving like this and would be thankful for any tips!
stiller_leser

Related

JSON parsing and listing data in PhoneGap not working

I'm working on making an API call in PhoneGap. I wrote a function and calling it from a button click event, and I'm getting a response too, but I want to know how to display it. I have tried, but it's not working.
function getContactList() {
console.log("Entering getContactList()");
$.ajax({
url: "https://api.androidhive.info/contacts/",
dataType: "json",
cache: false,
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success: function(json) {
console.log("====CONTACTLIST ---->", json);
$(json).find("contacts").each(function() {
var html = '<li>' + $(this).find("name").text() +
' ' + $(this).find("name").text() + '</li>';
$('#contacts').append(html);
});
}
});
}
You're receiving JSON string which is then automatically converted by jQuery to a JavaScript object, so you can interact with it directly and shouldn't convert it to a jQuery object like $(json). Change the code inside your success to this:
for (var i = 0; i < json.contacts.length; i++) {
var c = json.contacts[i];
var html = '<li>' + c.name + ' ' + c.email + '</li>';
$('#contacts').append(html);
}
Note: it seems that there is an error in your code, you're using the find("name") twice. I changed it to name & email, but you can use any property of the contacts that you're getting.

JQuery click 1 does nothing

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

Load specific html page with href and GET request response

First, I think my title isn't very clear and very representative of what I want to achieve, but I couldn't make it clearer ...
Ok so I have a Leaderboard, created from this ajax call:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var tb = document.getElementById('Leaderboard');
while(tb.rows.length > 1) {
tb.deleteRow(1);
};
var keys = Object.keys(data);
for( key of keys) {
var username = data[key].username;
var score = data[key].score;
var row = $('<tr id = "row' + tb.rows.length + '"><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
if(tb.rows.length > 11){
tb.deleteRow(tb.rows.length -1);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
So as you can see in the Leaderboard, when clicking on a username, it opens a new page with the result of a GET request (/leaderboard/:username). My question is how can I skin this page, or even better load an html file in this page, but while keeping accessible the result of the GET request to use it inside?
That may not be clear, and that's maybe a reason why my title is not really fitting ... But anyway if you have some ideas i'll take them !!
Thanks

Jquery ajax call throws empty JS exception?

This function works on one page but not another. I've added all sorts of logging to try to find the error, but cannot. The output of this code on the broken page is:
[13:59:56.427] "here"
[13:59:56.428] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[13:59:56.428] "fileName=undefined"
[13:59:56.428] "lineNumber=undefined"
[13:59:56.428] "columnNumber=undefined"
[13:59:56.428] "here6"
That tells me it's getting into the exception handler, completely skipping my ajax() call, but it's not telling me the exception.
function test(server, port, username, password, spanId) {
spanId = "#" + spanId;
$(spanId).html("<img src='/images/ajax-small.gif'/>");
console.log("here");
try {
$.ajax({
dataType: "json",
type: "GET",
url: "/admin/test.html?server=" + server + "&port=" + port + "&username=" + username + "&password=" + password,
success: function(json){
console.log("here2");
if (json.httpStatus == "200") {
// Change the image to show success
$(spanId).html("<img src='/images/accept.png' title='success'/>");
}
else {
console.log("here7");
// Change the image to show failure
$(spanId).html("<span style='color:#b22222;'>" + json.httpStatus +"</span> <img style='vertical-align: middle;' src='/images/cancel.png' title='placeholder'/>");
}
console.log("here8");
$(spanId).tooltip({ content: json.msg});
},
// Display the URL
beforeSend: function(b,c,d) {console.log("beforesend: " + c.url);},
error: function(b,c,d) {console.log("here5");}
});
}
catch(e) {
console.log(e);
for (var i in e)
console.log(i + "=" + i[e]);
}
console.log("here6");
}
What could I do further to debug this?
UPDATE: Output of code on a working page
Here's the output of the exact same code but on the page where it is working:
[15:01:20.158] "here"
[15:01:20.159] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A"
[15:01:20.159] "here6"
[15:01:21.661] GET https://localhost/images/accept.png [HTTP/1.1 200 OK 2ms]
[15:01:21.599] "here2"
[15:01:21.600] "here8"
So it obviously gets through the ajax call with flying colors. No errors, nothing. How can I find the problem on the page where it doesn't work?

Array and while loop: make unique clickable

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

Categories

Resources