Does anyone know why this Ajax wont work? - ajax

I have some code, some to change the class of a div, the rest to load content into the ajax div.
The ajax div however, does not load content. Why might this be?
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var otherClasses = favorites.className;
if (otherClasses.contains("Active")) {
everyone.className = 'statusOptionActive';
favorites.className = 'statusOption';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var otherClasses = everyone.className;
if (otherClasses.contains("Active")) {
favorites.className = 'statusOptionActive';
everyone.className = 'statusOption';
}
}
function loadXMLDoc(event) {
$.ajax({
url: "../home/" + event.data + ".php",
type: "GET",
success: function (result) {
$("#centreCont").html(result);
}
});
}
}
</script>
These divs start the ajax code (or should do at least)
<div id="everyone" class="statusOptionActive" onclick="loadXMLDoc('indexEveryone')">Everyone, everywhere</div>
<div id="favorites" class="statusOption" onclick="loadXMLDoc('indexFav')">Favourites Only</div>
Why won't it work :(

DEMO
Delete your div onclick event,since already you are manipulating your click event in the script.
Edited div
<div id="everyone" class="statusOptionActive">Everyone, everywhere</div>
<div id="favorites" class="statusOption">Favourites Only</div>
And I don know what argument you are passing in to loadXMLDoc('indexFav'); and loadXMLDoc('indexEveryone'); apart from that your javascript code is correct.
Hope this helps
Thank you

One obvious problem I can see is that you pass a string to loadXMLDoc, then you try to access .data on that string.

Related

Page navigation using ajax in codeigniter

IN codeigniter I am repeatedly using the controllers to load all the templates of my page....
I have divided the page into header, top navigation, left navigation and content and footer.
This is what I do at present
public function get_started() {
if (test_login()) {
$this->load->view('includes/header');
$this->load->view('includes/topnav');
$this->load->view('includes/leftbar');
$this->load->view('login_nav/get_started');
$this->load->view('includes/footer');
} else {
$this->load->view('errors/needlogin');
}
}
Is there any jquery-ajax helpers or plugins in codeigniter which would allow me to keep header footer and topnavigation static and allow me to load specific views using ajax.
thanks in advance..
You can use the constructor to set your static header:
//in your controller
public $data;
function __construct()
{
$this->data['header'] = 'static_header';
$this->data['static_footer'] = 'static_footer';
}
function get_started(){
if (test_login()) {
$this->data['subview'] = 'login_nav/get_started';
} else {
$this->data['subview'] = 'errors/needlogin';
}
$this->load->view('template',$this->data);
}
function get_page(){
$view = $this->load->view('your_dynamic_view','',TRUE);
print json_encode(array('success' => TRUE, 'view' => $view);
}
// in your template.php
<div id="header"><?php echo $this->load->view('header');?></div>
<div id="subview"><?php echo $this->load->view('subview');?></div>
<div id="footer"><?php echo $this->load->view('footer');?></div>
// in your script - used to load dynamic view on you subview div
<script type="text/javascript">
$.get('controller/get_page',{},function(data){
if(data.success){
$('#subview').html(data.view);
}
},'json')
</script>
Message me if there's a problem with my code
Happy coding ---> :D
The answer from PinoyPal is theoreticaly correct, but it didn't work for me in practice because it lacks one major detail: a route.
Take a look at this part of their script:
// in your script - used to load dynamic view on you subview div
<script type="text/javascript">
$.get('controller/get_page',{},function(data){
if(data.success){
$('#subview').html(data.view);
}
},'json')
</script>
Here in place of 'controller/get_page' there should be a url for an actual GET request. This is how it is generally supposed to look:
$("a.your_navigation_element_class").on('click',function(e){
e.preventDefault(); //this is to prevent browser from actually following the link
var url = $(this).attr("href");
$.get(url, {}, function(data){
if (data.success){
$('#subview').html(data.view);
}
},'json')
});
Now here's a question: where will this GET request end up? In the default controller route, that's right. This is why you need to 1) modify your request url and 2) set up a route, so that this request will be passed to an ajax-serving controller. Or just add an ajax-serving function to your default controller and re-route ajax requests to it.
Here follows how it should all look wrapped up
In ...\application\controller\Pages.php:
class Pages extends CI_Controller {
...
public function serve_ajax ($page) {
$view = $this->load->view($page, '', TRUE);
print json_encode( array('success' => TRUE, 'view' => $view);
}
...
}
In ...\application\config\routes.php:
...
$route['ajax/(:any)'] = 'pages/serve_ajax/$1';
On your page:
...
<body>
...
<div id="page"></div>
...
<script>
$("a.navigation").on('click',function(e){
e.preventDefault();
var url = $(this).attr("href");
$.get("/ajax" + url, {}, function(data){
//The trailing slash before "ajax" places it directly above
//the site root, like this: http://yourdomain.com/ajax/url
if (data.success){
$('#page').html(data.view);
}
},'json')
});
</script>
</body>
And you're all set.

Passing mutiple arguments with AJAX. Values come from DIV

I am trying to pass two arguments thought ajax. The variables I am pulling from are in a div and are done on the fly. I can easily pass the date_time but I need to be able to pass a variable "id" also. The date is in an array that is being loaded and changes. The ID does not change for this page.
This is the javascript. Below that will be my div. All attempts to append this have failed. Any ideas?
<div class='letter' width=600 date_time=\"$date_time\" id=\"$id\">
....doing stuff here.....
</div>
function OnScrollLetters () { var div = document.getElementById ("userLetter");
var info = document.getElementById ("info");
if(div.scrollTop == (div.scrollHeight - div.clientHeight))
{
$('div#loadMoreComments').show();
$.ajax({
url: "get_letters_for_profile_scroll.php?lastComment="+ $(".letter:last").attr('date_time'),
success: function(html) {
if(html){
$("#userLetter").append(html);
$('div#loadMoreComments').hide();
}else{
$('div#loadMoreComments').replaceWith("<center><h1 style='color:red'>End of Letters</h1></center>");
}
}
});
}
}
This is my div.
<div class='letter' width=600 date_time=\"$date_time\" id=\"$id\">
....doing stuff here.....
</div>
Try place a "=" between parameter name and value
..."&id="+$(".letter:last").attr('id')

Passing the signed_request along with the AJAX call to an ActionMethod decorated with CanvasAuthorize

This is a follow-up to AJAX Call Does Not Trigger Action Method When Decorated With CanvasAuthorize
So I found the following links and it seems that this is a common problem:
http://facebooksdk.codeplex.com/discussions/251878
http://facebooksdk.codeplex.com/discussions/250820
I tried to follow the advice by prabir but I couldn't get it to work...
Here's my setup:
I have the following snippet in the page where the button that triggers the whole post to facebook is located:
#if (!string.IsNullOrEmpty(Request.Params["signed_request"]))
{
<input type="hidden" id="signedReq" value="#Request.Params["signed_request"]" />
}
And then I have this snippet (inside a script tag inside the same page):
var signedRequest = $('#signedReq').val();
$('.facebookIcon').click(function () {
var thisItem = $(this).parent().parent();
var msg = thisItem.find('.compItemDescription').text();
var title = thisItem.find('.compareItemTitle').text();
var itemLink = thisItem.find('.compareItemTitle').attr('href');
var img = thisItem.find('img').first().attr('src');
postOnFacebook(msg, itemLink, img, title, signedRequest);
});
And finally, inside an external js file I have the following function:
/*Facebook post item to wall*/
function postOnFacebook(msg, itemLink, pic, itemTitle, signedReq) {
console.log(signedReq);
var siteUrl = 'http://www.localhost:2732';
$.ajax({
url: '/Facebook/PostItem',
data: {
'message': msg,
'link': siteUrl + itemLink,
'picture': siteUrl + pic,
'name' : itemTitle,
'signed_request': signedReq
},
type: 'get',
success: function(data) {
if(data.result == "success") {
alert("item was posted on facebook");
}
}
});
}
But signedReq is always undefined. And I'm not really sure I should be passing the 'signed_request' field inside the data object. Any thoughts?
Make sure you hidden input field is being populated.
Also, when you try to pull the ID of the input field via JQuery, you might not be referencing the proper element since .NET butcher's ID's of anything that's run on the server.
When I use the hidden input field trick, I set the jquery value like so:
var signedRequest = $('#<%=signedReq.ClientID %>').val();
This way, I'm getting the identifier that .NET is giving to the HTML element.
Hope that helps.
Just a guess - in your hidden field: id="signed_request" instead of id="signedReq"

Update using Prototype and Ajax

I am using Ajax and Prototype. In my code, I need to update the contents of a div.
My div:
<div id="update">
1. Content_1
</div>
My code:
Element.update($("update"),"2.Content_2");
Expected output:
<div id="update">
1.Content_1
2.Content_2
</div>
How can I do this in Ajax and Prototype?
AJAX usually means you are executing a script on the server to get this result.
However, in your example it looks like you simply want to append some text.
To append text you could simply add the text to the end of the innerHTML:
$("update").innerHTML = $("update").innerHTML + "2.Content_2";
If you are wanting to execute a server script, I'd do this: (I haven't used Prototype for a while, things might have changed)
function getResult()
{
var url = 'theServerScriptURL.php';
var pars = '';
var myAjax = new Ajax.Request(
url,
{
method: 'post',
parameters: {},
onComplete: showResult
});
}
function showResult(originalRequest)
{
$("update").innerHTML = originalRequest.responseText;
}
This code will call 'theServerScriptURL.php' and display the result in the div with id of 'update'.

Get current page URL from a firefox sidebar extension

I'm writing a sidebar extension for Firefox and need a way to get the URL of the current page so I can check it against a database and display the results. How can I do this?
I stumbled over this post while looking for an answer to the same question.
Actually I think it's as easy as
alert(window.content.location.href)
See also https://developer.mozilla.org/en/DOM/window.content
window.top.getBrowser().selectedBrowser.contentWindow.location.href;
might work, otherwise I think you need to use:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.getBrowser().selectedBrowser.contentWindow.location.href;
This seems to work fine for me
function getCurrentURL(){
var currentWindow = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var currBrowser = currentWindow.getBrowser();
var currURL = currBrowser.currentURI.spec;
return currURL;
}
https://developer.mozilla.org/En/Working_with_windows_in_chrome_code
If you need to access the main browser from the code running in a sidebar, you'll something like what Wimmel posted, except the last line could be simplified to
mainWindow.content.location.href
(alternatively you could use 's API returning an nsIURI).
Depending on your task, it might make sense to run the code in the browser window instead (e.g. in a page load handler), then it can access the current page via the content shortcut and the sidebar via document.getElementById("sidebar").contentDocument or .contentWindow.
If you need only domain and subdomain;
Usage;
PageDomain.getDomain(); // stackoverflow.com
PageDomain.getSubDomain(); // abc.stackoverflow.com
Code;
PageDomain = {
getDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var domain = PageDomain.extractDomain(new String(docum.location));
return domain;
},
getSubDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var subDomain = PageDomain.extractSubDomain(new String(docum.location));
return subDomain;
},
extractDomain: function(host) {
var s;
// Credits to Chris Zarate
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
host=host.split('.');
if(host[2]!=null) {
s=host[host.length-2]+'.'+host[host.length-1];
domains='ab.ca|ac.ac|ac.at|ac.be|ac.cn|ac.il|ac.in|ac.jp|ac.kr|ac.nz|ac.th|ac.uk|ac.za|adm.br|adv.br|agro.pl|ah.cn|aid.pl|alt.za|am.br|arq.br|art.br|arts.ro|asn.au|asso.fr|asso.mc|atm.pl|auto.pl|bbs.tr|bc.ca|bio.br|biz.pl|bj.cn|br.com|cn.com|cng.br|cnt.br|co.ac|co.at|co.il|co.in|co.jp|co.kr|co.nz|co.th|co.uk|co.za|com.au|com.br|com.cn|com.ec|com.fr|com.hk|com.mm|com.mx|com.pl|com.ro|com.ru|com.sg|com.tr|com.tw|cq.cn|cri.nz|de.com|ecn.br|edu.au|edu.cn|edu.hk|edu.mm|edu.mx|edu.pl|edu.tr|edu.za|eng.br|ernet.in|esp.br|etc.br|eti.br|eu.com|eu.lv|fin.ec|firm.ro|fm.br|fot.br|fst.br|g12.br|gb.com|gb.net|gd.cn|gen.nz|gmina.pl|go.jp|go.kr|go.th|gob.mx|gov.br|gov.cn|gov.ec|gov.il|gov.in|gov.mm|gov.mx|gov.sg|gov.tr|gov.za|govt.nz|gs.cn|gsm.pl|gv.ac|gv.at|gx.cn|gz.cn|hb.cn|he.cn|hi.cn|hk.cn|hl.cn|hn.cn|hu.com|idv.tw|ind.br|inf.br|info.pl|info.ro|iwi.nz|jl.cn|jor.br|jpn.com|js.cn|k12.il|k12.tr|lel.br|ln.cn|ltd.uk|mail.pl|maori.nz|mb.ca|me.uk|med.br|med.ec|media.pl|mi.th|miasta.pl|mil.br|mil.ec|mil.nz|mil.pl|mil.tr|mil.za|mo.cn|muni.il|nb.ca|ne.jp|ne.kr|net.au|net.br|net.cn|net.ec|net.hk|net.il|net.in|net.mm|net.mx|net.nz|net.pl|net.ru|net.sg|net.th|net.tr|net.tw|net.za|nf.ca|ngo.za|nm.cn|nm.kr|no.com|nom.br|nom.pl|nom.ro|nom.za|ns.ca|nt.ca|nt.ro|ntr.br|nx.cn|odo.br|on.ca|or.ac|or.at|or.jp|or.kr|or.th|org.au|org.br|org.cn|org.ec|org.hk|org.il|org.mm|org.mx|org.nz|org.pl|org.ro|org.ru|org.sg|org.tr|org.tw|org.uk|org.za|pc.pl|pe.ca|plc.uk|ppg.br|presse.fr|priv.pl|pro.br|psc.br|psi.br|qc.ca|qc.com|qh.cn|re.kr|realestate.pl|rec.br|rec.ro|rel.pl|res.in|ru.com|sa.com|sc.cn|school.nz|school.za|se.com|se.net|sh.cn|shop.pl|sk.ca|sklep.pl|slg.br|sn.cn|sos.pl|store.ro|targi.pl|tj.cn|tm.fr|tm.mc|tm.pl|tm.ro|tm.za|tmp.br|tourism.pl|travel.pl|tur.br|turystyka.pl|tv.br|tw.cn|uk.co|uk.com|uk.net|us.com|uy.com|vet.br|web.za|web.com|www.ro|xj.cn|xz.cn|yk.ca|yn.cn|za.com';
domains=domains.split('|');
for(var i=0;i<domains.length;i++) {
if(s==domains[i]) {
s=host[host.length-3]+'.'+s;
break;
}
}
} else {
s=host.join('.');
}
// Thanks Chris
return s;
},
extractSubDomain:function(host){
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
return host;
}
}
From a Firefox extension popup ;
You'll need
"permissions": [
"activeTab"
]
in your manifest or possibly tabs instead of activeTab
async function getCurrentTabUrl(){
let tabs = await browser.tabs.query({active: true, currentWindow: true}) ;
return tabs[0].url ;
}
let hostUrl = await getCurrentTab();
alert(hostUrl);
This works from a firefox "popup" extension.
browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT})
.then(tabs => browser.tabs.get(tabs[0].id))
.then(tab => {
console.log(tab);
});
Hallo,
I have tried to implement this in JavaScript, because I need that in my project too, but all three possible solutions didn't work. I have also implemented a small site to test it, but this also didn't work.
Here is the source code of the small site:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function Fall1 () {
alert(window.top.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall2() {
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
alert(mainWindow.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall3() {
alert(document.getElementById("sidebar").contentWindow.location.href);
}
</script>
</head>
<body>
<form name="Probe" action="">
<input type="button" value="Fall1"
onclick="Fall1()">
<input type="button" value="Fall2"
onclick="Fall2()">
<input type="button" value="Fall3"
onclick="Fall13()">
</form>
</body>
</html>

Resources