Albus One Albus One - 1 year ago 107
Ajax Question

jQuery reloading incorrectly

I am making a little script to change website language using PHP and Ajax/jQuery. I want page content to refresh without reloading page. Until now i have made this

$( "a[data-request]" ).click(function() {
var xhr = new XMLHttpRequest();
var request = $(this).attr('data-request');
var what = $(this).attr('data-to');'GET', '{{ site_url }}' + what + '/' + request);
xhr.onload = function() {
if (xhr.status === 200) {
$("#body").load(location.href + " #body");

When i click on link

<a data-request="english" data-to="home/language" href="#">

It succesfuly performs uri request in background and "reloads" #body element, which is whole body

<body id="body">

However instead of reloading whole page content just disappear and wont reappear again. What am i doing wrong?

Answer Source

Replace xhr.onload because it's not implemented in all browsers, use onreadystatechange instead

xhr.onreadystatechange = function () {
  var DONE = 4; // readyState 4 means the request is done.
  var OK = 200; 
  if (xhr.readyState === DONE) {
    if (xhr.status === OK) 
};'GET', '{{ site_url }}' + what + '/' + request); //<-- note must come after above event handler

note : this would wipe your button too(one you clicked to fetch the page).so instead of body load that data in some div.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download