How call variable outside function .each with Jquery? - javascript

I want to be able to access the value of a nested each() function outside of the function.
I have code below or http://jsfiddle.net/z36UK/6/
HTML:
<div id="wrap">
<ul data-role="listview" data-filter="true" data-filter-placeholder="Search..." id="ds-canho">
</ul>
</div>
Javascript:
$(document).ready(function() {
var urlx=[];
parseXml();
alert(urlx);
console.log(urlx);
$.mobile.loading( "show" );
$.ajax({
type: "GET",
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27http://saigonpearl.info/home/notype/-0-trang-chu.html%27%20and%20xpath%3D%22%2F%2Fdiv%5B%40class%3D%27tindang%27%5D%22&diagnostics=true',
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("div.tindang").each(function() {
var url = $(this).find('a').attr("href"),
urlx= url.replace('#menutop','');
$("ul#ds-canho").append('<li>' + $(this).find('h3').text() + '</li>');
$('ul#ds-canho').listview('refresh');
$.mobile.loading( "hide" );
});
}
});

Please update below js code
$(document).ready(function() {
$.mobile.loading( "show" );
$.ajax({
type: "GET",
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27http://saigonpearl.info/home/notype/-0-trang-chu.html%27%20and%20xpath%3D%22%2F%2Fdiv%5B%40class%3D%27tindang%27%5D%22&diagnostics=true',
dataType: "xml",
success: parseXml
});
$( document ).ajaxComplete(function() {
parseXml();
});
function parseXml(xml) {
window.urlx = '';
$(xml).find("div.tindang").each(function() {
var url = $(this).find('a').attr("href"),
urlx = url.replace('#menutop','');
$("ul#ds-canho").append('<li>' + $(this).find('h3').text() + '</li>');
$('ul#ds-canho').listview('refresh');
$.mobile.loading( "hide" );
});
}
});
EDIT
Add FSFIDDLE

It's not about the each, is it? You can easily put the urlx variable there and assign to it from the inside:
function parseXml(xml) {
var urlx;
$(xml).find("div.tindang").each(function() {
var url = $(this).find('a').attr("href"),
urlx = url.replace('#menutop','');
$("ul#ds-canho").append('<li>' + $(this).find('h3').text() + '</li>');
$('ul#ds-canho').listview('refresh');
$.mobile.loading( "hide" );
});
console.log(urlx);
// if you wanted an array, use `urlx = [];` and `urlx.push(…);`
}
However, where you currently have placed the log and alert statements is
before the ajax request
outside of the ajax request callback
which means that it cannot work. You need to put them inside the callback, because you cannot return the data outside of it.

Related

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

Load ajax after page load

This is the first time that I'm using ajax with jquery and I'm new on jquery I have a structure
$(document).ready(function(){
data_url = $('.lazy_content').attr("data-url");
data_id = $('.lazy_content').attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
});
});
<div class="lazy_content" data-url="/ajax/yorumlar/#Model.OtelBilgileri.seflink" data-target-id="ajax-content-1">
<h4 class="tur-main-baslik">COMMENTS</h4>
<div id="ajax-content-1"></div>
</div>
<div class="lazy_content" data-url="/ajax/trustyou/#Model.OtelBilgileri.seflink" data-target-id="ajax-content-2">
<h4 class="tur-main-baslik section-head">POSTS</h4>
<div id="ajax-content-2"></div>
</div>
as you see I have data-url this data url has my ajax-file and I'm getting my ajax file but after page loading nothing work..whats wrong with my code ?
Put your code inside $( document ).ready()
and I think you need to change your code like :
$(document).ready(function() {
data_url = $('.lazy_content').attr("data-url");
data_id = $('.lazy_content').attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
})
})
Or iterate with each class i.e .lazy_content
$( document ).ready(function() {
$('.lazy_content').each(function(){
data_url = $(this).attr("data-url");
data_id = $(this).attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
})
})
})
Depending on where the javascript is in the HTML the DOM may not have loaded at the point you run the script.
encapsulating your javascript within the jquery 'on DOM loaded' function ( $(document).ready( function() { ) will fix that problem, code as follows.
$(document).ready( function() {
$('.lazy_content').on("load", function() {
data_url = $(this).attr("data-url");
data_id = $(this).attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function() {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function(data) {
$(data).each(function(index, el) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
});
}
})
});
});
Load evnet is Only usable in window,img element.
If You use Jquery load function, You can use callback function.
$("#target").load("append.html",function(){
// callback
});
another way, you append scripts below target html.

Ajax Request on another's success ( jQuery )

I want to run the another ajax request on one's success.
THE CODE
$(document).ready(function(){
$('*[data-load-template]').each( function () {
var template = $(this).data('load-template');
var element = $(this);
$.ajax({
url : "templates/" + template + '.tpl',
method : "GET",
success : function (htmlData) {
$.ajax({
url : "data/" + template + '.json',
method : "GET",
success : function (jsonData) {
console.log(jsonData); // why isn't this one working???
}
});
element.html(htmlData); // this is working
}
});
});
}); // dom ready event
My question is why isn't this code working and how to make it work.

How to unbind or turn off all jquery function?

I have constructed an app with push state. Everything is working fine. However in some instances my jquery function are fireing multiple times. That is because when I call push state I bind the particular js file for each page I call. Which means that the same js functions are binded many times to the html while I surf in my page.
Tip: I am using documen.on in my jquery funciton because I need my function to get bound to the dynamical printed HTML through Ajax.
I tried to use off in the push state before printing with no success!
Here is my code:
var requests = [];
function replacePage(url) {
var loading = '<div class="push-load"></div>'
$('.content').fadeOut(200);
$('.container').append(loading);
$.each( requests, function( i, v ){
v.abort();
});
requests.push( $.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(data){
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
$('a').off();
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
})
);
}
$(window).bind('popstate', function(){
replacePage(location.pathname);
});
Thanks in advance!
simple bind new function with blank code
$( "#id" ).bind( "click", function() {
//blank
});
or
used
$('#id').unbind();
Try this,
var requests = [];
function replacePage(url) {
var obj = $(this);
obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
var loading = '<div class="push-load"></div>';
$('.content').fadeOut(200);
$('.container').append(loading);
$.each(requests, function (i, v) {
v.abort();
});
requests.push(
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data) {
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
obj.bind("click", replacePage); // binding after successfulurl ajax request
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
}));
}
Hope this helps,Thank you

replacing xml tags using replace function dont works

<lb/>pis est) les oultragerent grandement les
<lb/>appellans Trop diteulx, Breschedens,
<lb/>Plaisans rousseaulx, Galliers, Chien-
i want to replace the tag with so that i can parse it easily should i use simple replace function of javascript or some regular expresions also!!!!
//open the document xml
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "GP.xml",
dataType: "xml",
success: parseXml
});
});
//pasre the document
function parseXml(xml)
{
//find head and its text in the line breaks
$(xml).find("div").each(function()
{
$("#output").append($(this).replace(/\n/g, "<br>");
});
}
Change this line:
$("#output").append($(this).replace(/\n/g, "<br>");
To this:
$("#output").append($(this).html().replace(/\n/g, "<br />");
With $(this) you get the object, but not the content of the object. For this you need the .html().
EDIT:
The $(this) referse to the $('#output') not the div.
$(xml).find("div").each(function() {
var thistext = $(this);
$("#output").append(thistext.text().replace(/lb/g, "br"));
});
EDIT2:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "lp.xml",
dataType: "xml",
success: parseXml
});
});
//parse the document
function parseXml(xml) {
//find head and its text in the line breaks
$(xml).find("div").each(function() {
var thistext = $(this);
alert(thistext.text());
$("#output").append(thistext.text().replace(/lb/g, "br"));
});
}

Categories

Resources