lazyload is not defined (…) - javascript

I have news-list with 5 news on the screen and when user clicks on Load more button - i need to load 5 more news etc.
I have id of the next page gotten from back-end (ex. 2).
But when i click on the button Load more i got an error - lazyload is not defined (…). How to fix this?
And i'm not sure about var url = "./" + {{$nextPage}};
Any help is appreciated. Thanks
<a id="button-more" class="button button--blue load-more" onClick="lazyload.load()"> -> here its an error
var lazyload = lazyload || {};
(function($, lazyload){
var buttonId = "#buttonId",
loadingId = "#loading-div",
newsContainer = ".news-list__list";
lazyload.load = function() {
var url = "./" + {{$nextPage}};
$(buttonId).hide();
$(loadingId).show();
$.ajax({
url: url,
success: function(response) {
if(!response || response.trim() == "NONE") {
$(buttonId).fadeOut();
$(loadingId).text("No more news to load!");
return;
}
appendContests(response);
},
error: function(response) {
$(loadingId).text("Sorry, there was some error with the request. Please refresh the page");
}
});
};
var appendContests = function(response) {
$(buttonId).show();
$(loadingId).hide();
$(response).appendTo($(newsContainer));
};
})(jQuery, lazyload);

Related

Ctrl+Click on link that renders partial view

I got a link that renders partial view using AJAX.
Here is my link code:
<a href="#" onclick="LoadChildCategories(#i.CategoryId,
#i.IsTrading.ToString().ToLower())">#i.Name</a>
And here is LoadChildCategories function code:
function LoadChildCategories(id, isTrading) {
var link;
if (isTrading === false) {
link = '#Html.Raw(#Url.Action("NonTradingCategories", "Home",
new {categoryId = -1}))';
} else {
link = '#Html.Raw(#Url.Action("ModelList", "Home", new {categoryId = -1}))';
}
link = link.replace("-1", id);
$.ajax({
url: link,
method: 'GET',
success: function(data) {
$("#viewPartial").html(data);
}
});
}
When I click it without CTRL it's ok, partial view renders into my div. But when I click it with CTRL partial view renders into current tab and then another tab opens at Index page.
And when I rightclick on link and select to open it in another tab then nothing happens at current tab and new tab opens at Index page.
So, is there any ways to handle that?
I found pretty nice solution, so I modified project according to this solution: Make an MVC Application into a SPA with AJAX and History.js
1) Make controller methods return View, not PartialView and add one line of code than will check is it an AJAX request:
public ViewResult Category(int id)
{
ViewBag.IsAjaxRequest = Request.IsAjaxRequest();
var node = CategoriesHandler.Instance.First(x => x.CategoryId == id);
var childCategories = CategoriesHandler.Instance.Where(x => x.ParentId == node.Id).ToList();
ViewBag.Message = node.Name;
return View(childCategories);
}
2) Edit _ViewStart.cshtml like that:
#{
Layout = ViewContext.ViewBag.IsAjaxRequest == true ? null : "~/Views/Shared/_Layout.cshtml";
}
3) Prepare links to be managed via AJAX:
#i.Name
4) Create container for views at _Layout.cshtml
#/*Some layout stuff*/
<div id="bodyContent">
#RenderBody()
</div>
#/*Other layout stuff*/
5) Prepare helper javascript file like that:
$(function () {
var contentShell = $('#bodyContent');
var History = window.History, State = History.getState();
$(".ajaxLink").on('click', function (e) {
e.preventDefault();
var url = $(this).data('href');
var title = $(this).data('title');
History.pushState(null, title, url);
});
function navigateToURL(url) {
$('#bodyContent').html('<div class="loader"> </div>');
$.ajax({
type: "GET",
url: url,
dataType: "html",
cache: false,
success: function (data, status, xhr) {
$('#bodyContent').hide();
contentShell.html(data);
$('#bodyContent').fadeIn(500);
},
error: function (xhr, status, error) {
$('#bodyContent').hide();
alert("TEST_Error");
}
});
}
History.Adapter.bind(window, 'statechange', function () {
State = History.getState();
if (State.url === '') {
return;
}
navigateToURL(State.url);
});});
6) Do not forget to include your javascript files into the bundle!

AJAX preloader/throbber getting

Below is an AJAX function I'm trying to use to show a loader gif during the request and hide when successful. Basically I started out with the function inside of the response.success which used to work by itself. It creates short urls and sets it to the value of an input field. And I was shown the rest that wraps that function, but i'm getting a 404 error in the console for failure to load resource. I'm sure this is a straightforward answer, I'm too new to tell but I think I'm close. Any help is much appreciated, thanks.
function getShare(url)
{
$('#loader').show(); // show loading...
$.ajax({
dataType: "jsonp",
jsonpCallback:'apiCallback', // this will be send to api as ?callback=apiCallback because this api do not want to work with default $ callback function name
url: 'http://b1t.co/Site/api/External/MakeUrlWithGet',
data: {'url':url},
success: function(response){
$('#loader').hide(); // hide loading...
//respponse = {success: true, url: "http://sdfsdfs", shortUrl: "http://b1t.co/qz"}
if(response.success){
{
var s = document.createElement('script');
var browserUrl = document.location.href;
//alert(browserUrl);
if (browserUrl.indexOf("?") != -1){
browserUrl = browserUrl.split("?");
browserUrl = browserUrl[0];
}
//alert(browserUrl);
var gifUrl = $('#gif_input').value;
var vidUrl = $('#vid_input').value;
//alert(gifUrl + "|" + vidUrl);
url = encodeURIComponent(browserUrl + "?gifVid=" + gifUrl + "|" + vidUrl);
//alert(encodeURIComponent("&"));
s.id = 'dynScript';
s.type='text/javascript';
s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
document.getElementsByTagName('head')[0].appendChild(s);
}
function resultsCallBack(data)
{
var obj = jQuery.parseJSON(JSON.stringify(data));
$("#input-url").val(obj.shortUrl);
}
}
},
error:function(){
$('#loader').hide();
}
});
}

How to use the url hash to load a particular page after a refresh?

So, I am using url hashes that helps me to bring particular content up on hashchange. Now when i'm on some particular content and i refresh the whole page, i'm having that hash in the url and still not getting the content indicated by that hash.
Say my url is :
http://localhost/user and i clicked on details and it turned my url into following :
http://localhost/user#!detailsand i'm having the details page.
But having the above as my url when i reload the page, the hash remains same and there is no change in hash which does not invoke the function that i've bind with the hashchange event.
Also i cannot get the hash to the server side without sending ajax request everytime a user reloads using beforeunload.
Any Suggestions?
My code :
var pages = {};
pages['home'] = ""; pages['details'] = ""; pages['reviews'] = ""; pages['favs'] = "";
pages['likes'] = "", pages['gallery'] = "", pages['visited'] = "", pages['coupons'] = "";
$(window).bind('hashchange', function(event) {
var curr_hash = event.target.location.hash;
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
});
function load_page(page, toload){
// alert(pages[toload]);
if(pages[toload] == "") {
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: 'POST',
url: page,
data: post_data,
dataType: "html",
success : function(data) {
page[toload] = data;
$('.right-pane').html(data);
},
error : function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
console.log(xhr.responseText);
alert(thrownError);
}
});
}
else {
$('.right-pane').html(page[toload]);
}
}
You need to run the code attached to hashchange on load, in case someone refreshes the page, or even types it directly in to the browser. Try this:
var hashUpdate = function(curr_hash) {
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
}
$(window).bind('hashchange', function(e) {
hashUpdate(e.target.location.hash);
});
window.location.hash && hashUpdate(window.location.hash); // onload, if there was a fragment in the URL
$(function(){
var curr_hash = window.location.hash;
var page_to_load = curr_hash.substr(2);
var loadurl = "/ci_theyaw/user/user_" + page_to_load;
load_page(loadurl, page_to_load);
});

Load Twitter Box in Jquery box via Ajax

I would like to load a twitter popup box in jquery using (ajax?)
Here is my original code, which loads the twitter box in a new window:
function twitter_click() {
var twtTitle = document.title;
var twtUrl = location.href;
var maxLength = 140 - (twtUrl.length + 1);
if (twtTitle.length > maxLength) {
twtTitle = twtTitle.substr(0, (maxLength - 3)) + '...';
}
var twtLink = 'http://twitter.com/home?status=' + encodeURIComponent(twtTitle + ' ' + twtUrl);
window.open(twtLink,'','width=565, height=540');
}
Here is the code for the jquery popup box.
function showUrlInDialog(url, options){
options = options || {};
var tag = $("<div></div>"); //This tag will the hold the dialog content.
$.ajax({
url: url,
type: (options.type || 'GET'),
beforeSend: options.beforeSend,
error: options.error,
complete: options.complete,
success: function(data, textStatus, jqXHR) {
if(typeof data == "object" && data.html) { //response is assumed to be JSON
tag.html(data.html).dialog({modal: options.modal, title: data.title}).dialog('open');
} else { //response is assumed to be HTML
tag.html(data).dialog({modal: options.modal, title: options.title}).dialog('open');
}
$.isFunction(options.success) && (options.success)(data, textStatus, jqXHR);
}
});
}
<img src="twitter_button.jpg>
I don't know anything about coding so if someone can please combine these two scripts so that the twitter content of the first script loads into the jquery popup script that would make my day! Thanks. Pia
Start by changing this:
window.open(twtLink,'','width=565, height=540');
to this:
showUrlInDialog(twtLink, {error: function() { alert('Could not load form') }});
Then to run it, use this:
<img src="twitter_button.jpg>

Click on a link with phantom.js and retrieve the document html

I'm new with phantom.js and I'm trying to navigate on a website page, to click on a link (that calls an AJAX function and changes the document HTML) with phantom.js.
Here is my code:
window.setTimeout(function(){
phantom.exit();
}, 120000);
var page = require('webpage').create();
page.open("http://example.com", function(status) {
if (status !== 'success') {
console.log('{"error":"Unable to load the address for page"}');
phantom.exit();
}
var action = page.evaluate(function() {
document.getElementById("anID").click();
return "clicked";
});
var results = page.evaluate(function() {
return document.documentElement.innerHTML;
});
console.log(action);
window.setInterval(function() {
console.log(results);
phantom.exit();
}, 3000);
});
I'm very confusing as in my "action" function, the click() call is raising that error repeated 3 times:
TypeError: 'undefined' is not a function
phantomjs://webpage.evaluate():3 phantomjs://webpage.evaluate():1
ph.js:121 null
TypeError: 'undefined' is not a function
phantomjs://webpage.evaluate():3 phantomjs://webpage.evaluate():1
ph.js:121 null
TypeError: 'undefined' is not a function
phantomjs://webpage.evaluate():3 phantomjs://webpage.evaluate():1
ph.js:121 null
Also, if I comment the line when I send a click, the action function does not raise an error anymore and returns well the "clicked" console log. But 3 times...
What am I doing wrong ?
Thanks in advance.
I finally managed to achieve my task with this code. I skipped the click action and went directly to the AJAX call:
// phantomjs test.js 'http://www.example.com' 'anID'
var system = require('system');
var page = require('webpage').create();
var url = system.args[1];
var target = system.args[2];
page.onConsoleMessage = function (msg) {
console.log(msg);
phantom.exit();
};
page.open(url, function (status) {
function evaluate(page, func) {
var args = [].slice.call(arguments, 2);
var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
return page.evaluate(fn);
}
page.injectJs('jquery-1.7.2.min.js');
if (status === 'success') {
evaluate(page, function(target) {
$.ajax({
type: 'POST',
url: document.URL,
data: "__EVENTTARGET=" + target,
success: function(msg){
console.log(msg);
}
});
}, target);
}
});

Categories

Resources