How can I make an AJAX application similar to nodebb? - javascript

I am very new to ajax and am really struggling. My end goal is to make a forum software like nodebb. I've already made a php forum but decided not to use it because it just seemed old unlike faster looking forums like nodebb. What I'm trying to understand is how to make multiple tabs that display different information each but keep the same data for the header. I understand this is probably a very simple thing to do, but currently I am unable to accomplish this.
https://dogecraft.net is a great example of what I'm trying to accomplish.
If you click on the different tabs, it loads information in each one. I tried this but I had trouble with the url. When I reloaded, it simply just loaded my new file and that's not what I want.
(Yes, I am using a local jquery file. Jquery isn't the issue.)
I've tried w3schools but didn't find really helpful information
I've also tried many other websites.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$( "#one" ).click(function(){
$("#div1").load("/one/").hide().fadeIn();
window.history.pushState("object or string", "Title", "/one/");
});
});
$(document).ready(function(){
$( "#two" ).click(function(){
$("#div1").load("two.html").hide().fadeIn();
});
});
</script>
</head>
<body>
<button id='one'>Page one</button> <button id='two'>Page two</button>
<h2>This text never changes :)</h2>
<div id="div1"></div>
</body>
</html>
I would like to have a homepage 'index.html/php'
I need a button to load one page of content (one.html/php) and then another button that loads another page of content (two.html/php).
On refresh, I would like it to keep the same content that was on the homepage including the buttons in the header.

You could make an Ajax call to your html/php to retrieve the html code and then inject the content on your div. Here is an example:
$(document).ready(function() {
$("#one").click(function() {
$.ajax({
url : 'http://myserver.com/myhtmlpage.html',
success : function(html) {
$("#div1").html(html);
}
});
});
$("#two").click(function() {
$.ajax({
url : 'http://myserver.com/myphppage.php',
success : function(html) {
$("#div1").html(html);
}
});
});
});
When you click a button, an ajax call is made, and if succesful, the success function will be called. The first parameter has the html code of the webpage you requested. Then you can use the html function of jQuery you can inject it on your div.
A couple of tips:
You might want to use only one onready function, no need to declare it several times
You might consider returning a json object with the data instead of a php page. This will be useful later on if you consider using a framework such as Angular or Vue. If you can generate a JSON file on your php such as this:
{
"name": "John"
}
Then you could do something like this:
$("#two").click(function() {
$.getJSON({
url : 'http://http://myserver.com/myphppagethatservesjson.php',
success : function(json) {
$("#div1").html("<h1>My name is " + json.name + "</h1>");
}
});
});
Then it will render "My name is John".
This could be improved a lot,but I hope it could help you a bit.

Related

Get FB statuses without using PHP

I basically want to pull the text only from statuses I've written on facebook (no comments, likes, etc) for a website written in classic ASP. So it cannot be PHP coded.
It can be in ASP or just JS and HTML, ideally I'd like to spit out what's returned (top 10) in a loop, each status nested in a div, that way I can put them in one surrounding div using some jquery that shows one at a time, animating the transition.
Sounds so easy, Facebook's graph (v2) api seems reasonable but I'm just stuck as every example I can find is PHP based. I'm not sure where to start. I see from the API i'll need an access_token (should I create an App and use AppID|SecretID for permanency?) and I'll need my profile ID (no probs).
Can you offer a good starting point or example I can easily customise? I'd like to keep code to a minimum.
here a simple tutorial i used for a previous full javascript implementation
http://codesamplez.com/development/access-facebook-graph-api-using-javascript-sdk
and here the official documentation :
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
It took some reading but here is the pure JS solution with no ASP or PHP. You need to go into FB developer section and create a blank app and make it active/live. You'll need the App ID, the App secret and you'll need your Facebook Page ID (found at the end of the URL of your Facebook page.
I only wanted to show posts I've made as page manager so I do an IF statement checking it's a 'shared_story' so i'm not showing others posts/comments etc.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_UK/all.js', function(){
FB.init({ appId: 'Your_App_ID_Here' });
FB.api(
"/Your_Page_ID_Here/posts?access_token=Your_App_ID_Here|Your_App_Secret_Here&limit=50",
function (response) {
if (response && !response.error) {
var $ul = $('#statuses');
for(i=0;i<response.data.length;i++) {
if(response.data[i].message && response.data[i].status_type != 'shared_story') {
$ul.append($('<li>').html(response.data[i].message + '</li>'));
}
}
}
}
);
});
});
</script>
</head>
<body>
<ul id="statuses"></ul>
</body>
</html>

How to refresh or reload a div's content using Ajax

This is somehow. i normally use jquery's load to load content from page A into page B , so loading a div's content into itself in order to just refresh it doesn't make much sense. What's the solution for this?
$('#A').load('pageX.php #A');
Please note that both #As are on pageX making it the same #A
This somehow interferes with the JavaScript in a bad way after that "load" i don't know why.
So these is simply to refresh a div.
An id must to unique in html document otherwise you'll end up having expected results for JavaScript.
In your case you need to remove duplicate id's
Something like this
$('#A').load('pageX.php #B');
or this will work:
$('#B').load('pageX.php #A');
Because of people coming to this question, if I were to do this again now, I would do it like this.
HTML
<html>
<body>
<div class="divToRefresh"></div>
</body>
</html>
JavaScript(JQuery)
<script>
$(document).ready(function(e) {
$.refreshDiv = function(arg){
var d = {someVariable_you_can_send:arg}
$.ajax({
url:'url_to_div_content',
data:d,
type:"POST"}).done(function(result){
$('.divToRefresh').html(result);
});
};
//////////call this for the first time//////////
$.refreshDiv('some value');
//////////////////////////// and then refresh it after a certain interval if you need to
window.setInterval(function(){
$.refreshDiv('some value');
}, 1000*60*60*60);
});
</script>

jquery .load() function only working the first time

So I have a website I am working on just as a personal website that uses jQuery and jQuery UI
Previously I have been using hidden html code and just using jquery to show it.
But its making my html file messy so I wanted to use jquery's .load() to do the same thing but from an external file.
Right now, its set to a .click function.
For my hidden html it shows it every time when I click a particular element.When you click on a different element it. It hides the first one. I am doing it by having a div with 2 classes. The problem is when I tried to load html into a hidden div, and then show it and hide it, it only worked the first time.
Enough talk, here is my code. #1 works , #2 only works on the first click. And leaves imagearea blank every time after.
$(".jquery").click(function(){
clearImageArea();
hideThumbnails(5);
showThumbnails();
$("#1").click(function(){
$(".imagearea").html(js);
$(".jscode").show(1000);
$(".title").text("Extending jQuery");
});
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html");
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
now my hidden stuff in my html file
First my html and js code is loaded into here from jqueryEx.html and is being hidden elsewhere in my javascript via $(".hidden").hide(); and loaded then into into imagearea via .html() and shown via .show()
<div class="jquery2 hidden">
</div>
My other div looks like this which is put into imagearea by clicking on #1
<div class="jscode hidden">
<div class="block">
//lots of js code escaped out into html
</div> <!-- end of block-->
</div>
elsewhere in my JS code at the beginning I have var js=$(".jscode"); to load it into the js variable you saw earlier.
if you want to see an out of date example of what I am working on
go to www.3realsoft.com (only cs and js work on skills)
if you want to see any additional parts of my code, just ask. Most of it is there on my website though.
I got to this item in my search results, when I was trying to have a button both load and refresh the content, and the load was working but the refresh was not working.
Here's a shorter version of the solution, setting Cache to false was the key. Solution found over at this other link, but I'm posting this concept here because if Google dropped me in this item, others looking for the same will also probably find themselves here. Props to John Millikin, make sure to go over to his answer and upvote him: Stop jQuery .load response from being cached
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$('.detail-expand').click(function () {
var detailRowElement = $(this).closest('.session-row-tr').next();
var detailElement = detailRowElement.find('.detail-row-div');
var sessionId = detailElement.data("sessionId");
detailElement.empty();
detailElement.load('/Admin/WebLogPartial/' + sessionId, function () {
$.bootstrapSortable(true, 'reversed');
});
detailRowElement.show();
});
});
</script>
Anything that depends on the HTML being loaded must be done in the callback function, because the first A in AJAX stands for asynchronous.
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html", function() {
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
I'm not really sure what you're trying to do with .html(jquery2), since the argument to .html() is supposed to be a string, not a jQuery object. Maybe you meant:
var jquery2 = $(".jquery2").html();

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

Tracking outgoing links with Javascript and PHP

I have tried it using jQuery but it is not working.
<script>
$("a").click(function () {
$.post("http://www.example.com/trackol.php", {result: "click"
}, "html");
});
</script>
out
To get the best results you should change two things in your approach
Use onmousedown instead of click - this way you get a few extra milliseconds to complete the tracking request, otherwise the browser might not start the connection to your tracker at all as it is already navigating away from the original page. The downside is that you might get some false-positive counts, since the clicking user might not finish the click (eg. keeps the mousebutton down and moves the cursor away from the link) but overall it's a sacrifice you should be willing to make - considering the better quality of tracking.
Instead of an Ajax call ($.post('...')) use an image pre-fetcher (new Image().src='...'). The fact that the tracker is not an image is not relevant in this case because you don't want to use the resulting "image" anyway, you just want to make a request to the server. Ajax call is a two way connection so it takes a bit more time and might fail if the browser is already navigating away but the image pre-fetcher just sends the request to the server and it doesn't really matter if you get something back or not.
So the solution would be something like this:
<script>
$(document).ready(function() {
$("a").mousedown(function (){
new Image().src= "http://www.example.com/trackol.php?result=click";
});
});
</script>
out
Instead of using JavaScript to call a php tracking script, you could just link to your tracking script directly and have it in turn redirect the response to the ultimate destination, something like this:
out
and in the PHP script, after you do your tracking stuff:
...
header("Location: $dest");
As mentioned, the problem is you’re not running the script after the DOM has loaded. You can fix this by wrapping your jQuery script inside $(function() { }, like so:
This works:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tracking outgoing links with JavaScript and PHP</title>
</head>
<body>
<p>Test link to Google</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
$('a').click(function() {
$.post('http://www.example.com/trackol.php', { result: 'click' }, 'html');
});
});
</script>
</body>
</html>
See it in action here: http://jsbin.com/imomo3

Categories