Update <head> balise on Jquery/Ajax navigation Wordpress - javascript

I am doing an ajax navigation for a wordpress website. I update the #content with fade, this is ok, but I want to just update my head with my new page head, I don't find!
$(document).ready(function () {
//hash change
$(window).hashchange(function () {
//on retrouve le vrai lien
var arg = window.location.hash.substring(3);
var link = 'http://ladresse.graphsynergie.com/' + arg;
$.ajax({
url: link,
processData: true,
dataType: 'html',
success: function (data) {
data = innerShiv(data, false);
var contenu = $(data).find("#contenu");
//problem part
var head = $(data).find('head').text();
document.head = head;
//problem part end
$('#contenu').fadeOut('200', function () {
$(this).html(contenu.html()).fadeIn('200');
});
}
});
});
//end
//détection d'un hash onload
if (window.location.hash.substring(3) != '') {
$(window).trigger('hashchange');
}
});

Have in consideration that .text() will only retrieve the "text" contained inside the html tags, review the jQuery documentation. I think that what you actually want is to use the .html() method.
So, I think that you may want to replace those 2 problematic lines of code with this:
$("head").html($(data).find("head").html());
Update:
Apparently all browsers strip out anything that it's not inside the "body" when they create the DOM object. The thing is that when you do: "$(data)" jQuery creates a DOM object with the content of the "data" variable, and your browser decides to ignore all the elements that are not inside the "body" tag, therefore in the internal DOM object that jQuery handles the "head" element is not there anymore. So you will have to find a workaround.
Try this, put these lines of code just after the line "success: function (data) {":
var headIni = data.toLowerCase().indexOf("<head");
var headEnd = data.toLowerCase().indexOf("</head>");
headIni = data.indexOf(">", headIni + 1) + 1;
var headHTML = data.substring(headIni, headEnd);
And then, replace the line that I initially suggested for this one:
$("head").html(headHTML);
This should do the job. I'm sure that there must be more elegant ways to do it, but hopefully this will be good enough for you.
Update 2:
If you follow this link you will find a much better way to do it. Just add the library "jquery.ba-htmldoc.js" that you will find there, and then do this:
$("head").html($.htmlDoc(data).find('head').html());

To overwrite the content of your "< head >" tag use
$("head").html('NEW STUFF IN HEAD');

Related

jQuery in a wordpress template page

I am developing a tool for my Wordpress website using jQuery, I am quite new at this but what I'm trying to do is not that hard.
My script is enqueued, i've read that with the NoConflict mode i can't use $ so I use jQuery instead.
function Calculator()
{
var result = jQuery('result');
if (jQuery('day').value == "" || jQuery('month').value == "" || jQuery('year').value == "") {
return;
}
result.update('<span class="result">processing</span>');
jQuery('form').request({
onComplete: function(transport) {
result.hide();
result.update(transport.responseText);
new Effect.Appear(result, { duration: 0.5 } );
}
});
}
My problem is I got error everywhere :
update is not function
request is not function
etc...
There is something i'm obviously doing wrong but can't figure out what...
thanks a lot !
The errors you are seeing ("update is not function request is not function") describe the problem - those really are not jQuery functions.
It looks like you're trying to update an HTML element with ID or class "result". To do that, use .html():
var result = jQuery('.result'); // "." to select the element with class result
result.html('something');
For .request, it looks like you are trying to do a POST or GET of a form. If so, use .ajax(), .post(), or .get(). Note though you'll need to add a few more details, eg:
jQuery('form').ajax({
type: "POST",
url: someurl,
data: somedata,
onComplete: ...
});
Also, if your Calculator() function can be called while the page is loading, make sure it (or whatever calls it) is wrapped in document.ready:
jQuery(document).ready(function () {
...
});
An unrelated issue, to check the value of say a form input with class "day", you need to use:
jQuery('.day').val()
if you are fetching the value using class then you have to do it like this:
jQuery('.result').val()
or if using id use it like:
jQuery('#result').val()
in jquery we use .val() function to get value instead of value.
Is update, request exists in jquery?
you can use like this rather than writing again and again.
var j = jQuery.noConflict();
j(".result").html("<span>Processing..</span>");

Ajax auto-load by counter

I got this code from some template, it gets executed by clicking on the tabs to fetch posts into the page. All I want is to have an edited copy of this code to fetch posts by timer aside from clicking on the tabs. I have tried the setInterval but it didn't work, I appreciate any help I am so new to Ajax and JQuery.
jQuery(document).ready(function($) {
setInterval(function(){
e.preventDefault();
var bt = $(this);
var bts = bt.parent().parent();
var where = $(this).parent().parent().parent().next();
var nbs = bt.parent().parent().data('nbs');
var nop = bt.parent().parent().data('number_of_posts');
cat = bt.data('cat_id');
if (cat === '') {
cat = bt.data('parent_cat');
}
where.parent().find('.show-more').find('.nomoreposts').remove();
jQuery.ajax({
type: "post",
url: nbtabs.url,
dataType: 'html',
data: "action=nbtabs&nonce="+nbtabs.nonce+"&cat="+cat+"&nbs="+nbs+"&number_of_posts="+nop,
cach: false,
beforeSend : function () {
where.parent().append('<i class="nb-load"></i>');
},
success: function(data){
where.hide().html(data).fadeIn('slow');
bts.find('li').removeClass('active');
bt.parent().addClass('active');
where.parent().find('.nb-load').remove();
}
});
}, 5000)
})
You have to get started to some degree before we can really help you code-wise. We can't just write the code for you because we do not know what elements you want updated and how.
All I can advise you is the Jquery Ajax method is how this code retrieves url responses:
jQuery.ajax({
type: "post",
url: "<name of your url or maybe servlet>"
success: function(data){
// data is the response from your url
// in the code sample, data was html that was inserted to an element
}
});
You can put this ajax call in a function and use setInterval. You can place the setInterval call on your Jquery.ready() function.
Your first issue is that you're trying to call jQuery.setInterval, not setInterval. jQuery.setInterval is not a function, so calling it will just give you an error.
The next issue is that your script tries to alter a bunch of elements, using the clicked element as a starting point. This is bad practice because of situations like this, where changing how to function is invoked can completely break the script. Without knowing what all of this:
var bt = $(this);
var bts = bt.parent().parent();
var where = $(this).parent().parent().parent().next();
var nbs = bt.parent().parent().data('nbs');
var nop = bt.parent().parent().data('number_of_posts');
is, it's pretty difficult to give advice. The safest bet is to replace $(this) with jQuery(".nb-tabbed-head li a"), but that might cause issues because $(this) refers to only one element, whereas jQuery(".nb-tabbed-head li a") may refer to multiple.
Really the biggest issue is that you're trying to use code that a) is poorly-written and b) you don't understand yet. I highly recommend learning about AJAX, events, the DOM, and jQuery before you make a serious attempt at this. It's almost impossible to create a good product when you're gluing together pieces of code that you don't understand that were written by someone that you don't know.

Autorefresh div with javascript

I have been looking around for the simplest way to refresh a particular div on my page, automatically, every x seconds.
So far I've got:
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('time').innerHTML = Date();
}
However the last part where the innerHTML is set to the date function is what I'd like replaced by the content of the "time" ID, and not an actual date print.
I know I could load an iframe, or externa html page, but I would like to simply call upon an existing div on the page instead of having to change the existing content. Is that possible?
Thanks!
Edit: What I mean is I have a a div that looks like this on the page:
Some stuff
I would like to have that div refreshed every x seconds, so yes, you may ignore the Date() part of my example, I simply found that code as is but when I tried to remove the .innerHTML part it just does nothing, I think lol!
Are you looking for something like this?
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
var now = new Date();
document.getElementById('time').innerHTML = now.getHours() + ":" + now.getMinutes() + ":" +now.getSeconds();
}
</script>
NOTE: The OP is actually wanting to reload a script in an ad service already included on the page. The following does not help with this; however, due to the way the question was asked, I'm leaving this answer since I think it could help others looking for the following type of solution. Just be aware this does not demonstrate how to "rerun" already included (presumably global and non-function'd) code.
Say I have the following div I'd like to dynamically refresh:
<div id="refresh">Refreshes...</div>
jQuery offers the $.ajax group of functions that allow you to dynamically request a page and use the response as HTML. For instance:
$(document).ready(function(){
var $refresh = $('#refresh'),
loaded = 1,
data = {
html: $.toJSON({
text: 'some text',
object: {}
}),
delay: 3
};
var refresh = function(){
$.ajax({
url: "/echo/html/",
data: data,
type: "GET",
success: function(response) {
$refresh.html($refresh.html() + '<br/>#' + loaded);
loaded++;
setTimeout(refresh, 3000);
}
});
};
refresh();
});
http://jsfiddle.net/Ah3jS/
Note, I'm using jsFiddle's echo/html/ functionality here as well. The data variable is tuned to working with this for demonstration purposes. In reality, the data sent with the request is either GET or POST variables like you work with normally. Also, I don't use response in success, but that's because it doesn't return anything in jsFiddle's demo mode.
jQuery make's this stuff pretty easy. Really, I'd think about using it instead of most other approaches (requirements notwithstanding).

Mootools appending html after an ajax request

I have an ajax call that looks like this,
$('campaignType').addEvent('change', function(){
alert($('campaignType').value);
var request = new Request({
method: 'get',
url: '/admin/admin_' + $('campaignType').value + '.php',
onRequest:function() {
alert('Request has been made, please be patient')
},
onComplete:function(response) {
$('campaignForm').append(response);
}
}).send();
});
Essentially what happens is depending on what the value of `$('campaignType') some HTML is returned from another file, however I cannot seem to get the HTML to append on to my container. Any one care to give me some advice?
Thanks
Dimitar's solution is close but is a bad solution as it recreates the whole element contents and destroys attached event handlers. A better solution would be:
Element.implement({
append: function(newhtml) {
return this.adopt(new Element('div', {html: newhtml}).getChildren());
}
});
this is actually what Request.HTML internally does.
.append is not a valid element prototype in mootools.
if you want to append html to an existing one, then you can either MAKE .append valid by defining in your site lib/core bit (I would consider this if you use it a lot):
Element.implement({
append: function(newhtml) {
// silly name, does not say to me you are appending html. rename to appendHTML
return this.set("html", this.get("html") + newhtml);
}
});
or in your onComplete do:
var cf = $('campaignForm');
cf.set("html", cf.get("html") + this.response.text);
have fun :)
If you're using mootools 1.2.4 you can change Request to Request.HTML and use append option. (Not sure that append option was in older versions)
$('campaignType').addEvent('change', function(){
new Request.HTML({
method: 'get',
url: '/admin/admin_' + $('campaignType').value + '.php',
append: $('campaignForm')
}).send();
});
I think you like to use onSuccess instead of onComplete

Using domready for AJAX calls

Is there a way to know that the elements are on a document before I try to access them with JQuery?
Code Snippet:
var s = new AjaxCall(someurl);
s.oncomplete = function(response) {
var container = $('container_id');
container.innerHTML = response;
var ul = $('some_id'); }
The response is some HTML returned by the Ajax call.
This response updates the contents of a div and then I access an element that was created by the innerHTML (the ul in the code).
If the response is large, I believe there would be times that some elements would not be rendered when I will try to access them. Does domready work for AJAX calls, and could this solve my problem?
You seem to have forgotten to use #, as it should be $('#some_id');, and not $('some_id');. I suggest instead to just use document.getElmenetById. It reads more clearly and is much more efficient than contextual-based ID matching.
var some_id = document.getElmenetById("some_id");
Regarding your question of the element "not being available," don't worry. The innerHTML setter performs a synchronous operation. If a tag with a matching ID is parsed from that, then the corresponding element will be available immediately after setting the innerHTML.
If you were using jQuery, your success function for the request would be:
$.ajax({
url: "test.html",
cache: false,
success: function(resp){
var ul = $("#containerID").html(resp).find("#ElementInRespID");
//do something with ul
}
});
This will put the result in the container, find the element you want in there and set the ul variable to it.

Categories