We released a site a couple of weeks ago and we are now getting complains that the website doesn't work in Internet Explorer 6-10.
Im using jQuery version: 1.11.0
We are running AJAX to load each page with an anchor. For example. www.site.com/#page2
Im trying to debug the code and see where it fails but I have no idea what is wrong.
The problem people are having is simple, the page doesn't load. All other code except the page call is working. So basically the page is empty.
This is a simplified version of the code:
function retrieve_page(link, lang){
event.preventDefault();
var id = link;
if(id){
document.location = "#"+id;
} else {
document.location = "#hem";
}
if(window.location.hash.substring(1) != "undefined") {
var page = window.location.hash.substring(1);
} else {
var page = "hem";
}
var content;
var request = $.ajax({
type: "GET",
url: "ajax/retriever.php",
data: { page:page },
success: function(data) {
content = data;
}
});
request.done( function () {
$('#page').html(content);
});
}
and this is the ajax/retriever.php file
<?php
$page = $_GET["page"];
$path = "../pages/".$page.".php";
$config = "../core/config.php";
if(!file_exists($path)){
require_once $config;
echo "<div id='no_page'><h1 style='display: block'>".$lang["ERROR"]."</h1><a href='index.php'><h2>".$lang["ERROR_RETURN"]."</h2></a></div>";
exit;
} else {
require_once $config;
require_once $path;
exit;
}
?>
The AJAX function call is example:
<a onclick="retrieve_page('page1', 'sv')">Page1</a>
Thanks in advance!
Can't see how i missed it. Well i solved the issue with simply removing event.preventDefault();
Related
I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
I have a dynamic login header. 2 links, login / register and profile / logout.
I have a php class function that was being used to check if logged in and displaying relevant links, it worked fine.
I then moved to an ajax login as I didn't want a page refresh and the login box drops down and rolls back up. Again, it works fine.
I've noticed a slight issue, by slight I mean very irritating :)
Once logged in, Every single page refresh on new page shows a flicker where 'profile' becomes 'login' and then flickers back again. It only happens when the page is loading and doesn't last long but it's not very nice.
Could someone help me solve it please? I'm pretty new to Ajax/jQuery and spent ages wiht the help of some guys in here getting the ajax/jquery part functional in the first place.
this is script that toggles the login divs
<script>
window.onload = function(){
$(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$("#loggedIn").toggle(loggedIn);
$("#loggedOut").toggle(!loggedIn);
});
}
</script>
Thanks
EDIT: Ajax
function validLogin(){
$('#error').hide();
var username = $('#username').val();
var password = $('#password').val();
if(username == ""){
$('input#username').focus();
return false;
}
if(password == ""){
$('input#password').focus();
return false;
}
var params = {username: username, password: password};
var url = "../loginProcessAjax.php";
$("#statusLogin").show();
$.ajax({
type: 'POST',
url: url,
data: params,
dataType: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= '<img src="../images/loginLoading.gif" /> checking...' ;
},
success: function(data) {
$("#statusLogin").hide();
if(data.success == true){
$('#loggedIn').show();
$('#loginContent').slideToggle();
$('#loggedOut').hide();
}else{
// alert("data.message... " + data.message);//undefined
$("#error").show().html(data.message);
}
},
error: function( error ) {
console.log(error);
}
});
}
Use PHP to hide the unwanted element by doing the following
<?php
$loggedIn = $general->loggedIn();
?>
... Some HTML
<div>
<div id="loggedIn" <?php echo ( $loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged in stuff
</div>
<div id="loggedOut" <?php echo ( !$loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged Out Stuff
</div>
</div>
<script>
var loggedIn = <?php echo json_encode($loggedIn); ?>;
$('#loginForm').submit(function() {
... Handle form submit
... When ajax returns true or false we can set loggedIn and then toggle the containers
});
</script>
// CSS-Stylesheet
#loggedIn,
#loggedOut {display: none}
<script>
$(document).ready(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
if (loggedIn == true) { // i can just guess here...
$("#loggedIn").show();
}
else {
$("#loggedOut").show();
}
});
</script>
Three possible solutions:
If the script element is placed inside the body, move
it to head element.
Use the following script instead:
$(document).ready(function () {
'use strict';
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$('#loggedIn').toggle(loggedIn);
$('#loggedOut').toggle(!loggedIn);
});
Hide both links in the "logged in" div using $('#loggedIn
a).hide(); and then, show them on the window.onload event using
$('#loggedIn a).show();. A bit dirty, bit it may work.
Im trying to send some data to the server through AJAX with the value i get from a JS variable.
Code:
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/'+_src;
}
function guardarCambios() {
$.post("guardarCambios.php",
{url: url},
function(response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
}
alert(url);
}
</script>
The idea is update the user picture with the url i get from aplicarFoto(_src) with the variable url .
The first function (aplicarFoto(_src)) alone works correctly, but when i put the another function (guardarCambios()), the first function doesnt work, therefore the second neither! I dont know why, but it just happens when using ajax functions because i did a test with an alert(url) (sunrrounding the rest of code with comments) in the second function and both work correctly!
Some guess? Thank you!
Your script alone has syntax errors.
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/' + _src;
}
function guardarCambios() {
$.post("guardarCambios.php", {
url: url
}, function (response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
alert(url);
}
);
}
</script>
i look this tutorial
http://tutorialzine.com/2009/09/simple-ajax-website-jquery/
but i don't understand how to make this work with php file with sql, echo ""; etc
If someone can explain, i try everything and nothing appears
Thanks :)
var default_content = "";
$(document).ready(function () {
checkURL();
$('ul li a').click(function (e) {
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pagesContent').html();
setInterval("checkURL()", 250);
});
var lasturl = "";
function checkURL(hash) {
if (!hash) hash = window.location.hash;
if (hash != lasturl) {
lasturl = hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if (hash == "")
$('#pagesContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url) {
url = url.replace('#page', '');
$('#loading').css('visibility', 'visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page=' + url,
dataType: "html",
success: function (data) {
if (parseInt(data) != 0) {
$('#pagesContent').html(data);
$('#loading').css('visibility', 'hidden');
}
}
});
}
load_page.php
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.php'))
echo file_get_contents('pages/page_'.$page.'.php');
else echo 'There is no such page!';
?>
demo.html
< a href="#page1">Page1< /a>
< a href="#page2">Page2< /a>
< a href="#page3">Page3< /a>
< a href="#page4">Page4< /a>
<div id="pageContent">
//loaded ajax page
</div>
in this scenario , link > index.html#page1 will load file 'pages/page_1.php'
but in main index.html just can load html code , not php syntax .
Can I use php command in this case ?
So it looks like the problem here is that in the tutorials example, they simply use an HTML file. For this, file_get_contents() will work fine. However if you want your server to parse PHP code before serving it to the user, you should use the include() function.
From the documentation :
The include statement includes and evaluates the specified file.
The file_get_contents() function behaves silghtly differently :
file_get_contents — Reads entire file into a string
It simply reads the contents of the file, the PHP code is not evaluated/executed/interpreted...
I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...