I know that this is impossible via PHP supervars, but see this website:
When we navigate on the pages, the title and meta just changes and this affect the facebook too, see:
How he is doing it? I have a ajax navigation system too, and need to set og, but I don't know how to do dinamically as he did.
Just a comment, he have hidden INPUTS with values of the meta:
But I still don't know how he can parse this before the website being rendered.
The URL fragment is NEVER sent to the server. It is used as a reference by the browser. "Traditionally" it is used to scroll to an element with the ID referenced by the fragment, however more recently it has been given some more exotic uses.
In particular, #! is a shebang, and has the meaning that "this page is being loaded by AJAX, but if you load the following relative to the domain, you will get the full page anyway" - this is particularly useful for search engines.
Basically, use AJAX combined with location.hash to get it to work.
it's just some js(jQuery)
<script type="text/javascript">
var current_page = '';
$("a").live("click", function(){
return change_hash(this,1);
});
function change_hash(el,type) {
if(type==1) {
var link = $(el).attr("href");
}
else
{
var link = el;
}
var link_ar = link.split('/#!');
if(link_ar[1]!=undefined) {
if((link_ar[1].length>3)&&(link_ar[1].substr(0,1)=='/')) {
window.location.hash = '#!'+link_ar[1];
return false;
}
else
{
return true;
}
}
else
{
return true;
}
return false;
}
$(function(){
$(window).hashchange( function(){
address = location.hash.replace("#!","");
var skip=false;
if((address.substr(0,1)=='/')&&(address!=current_page)) {
$("#content").html('<div class="content-box"><div class="ajax-loading">carregando...</div></div>');
$("html, body").animate({ scrollTop: 0 }, "slow");
if (address.indexOf(".php") == -1) {
var newaddress = address.replace(/[^a-zA-Z0-9_\.]+/g,"");
if('/'+newaddress!=address) { change_hash('/#!/'+newaddress,2);skip=true; }
address='/PerfilDetalhe.php?user='+newaddress;
}
if(skip==false) {
$.get('http://www.suamusica.com.br'+address, function(htmldata) {
$("#content").html(htmldata);
document.title = $('#metaTitle').val();
$('meta[name=description]').attr('content', $('#metaDescr').val());
$('meta[name=keywords]').attr('content', $('#metaKeywords').val());
$('meta[property="og\\:description"]').attr('content', $('#metaDescr').val());
$('meta[property=og\\:title]').attr('content', $('#metaTitle').val());
$('meta[property=og\\:url]').attr('content', $('#metaURL').val());
$('meta[property=og\\:image]').attr('content', $('#metaImage').val());
$('meta[property=og\\:type]').attr('content', $('#metaType').val());
$('meta[name=DC\\.title]').attr('content', $('#metaTitle').val());
$('meta[name=DC\\.description]').attr('content', $('#metaDescr').val());
$('meta[name=DC\\.subject]').attr('content', $('#metaKeywords').val());
}).fail(function() { $("#content").html('<div class="content-box error-box"><h1>Ooops!</h1><p>A página acessada não existe ou não foi encontrada.</p></div>'); });
current_page = address;
}
$.get('http://www.suamusica.com.br/msg_check.php', function(resp) {
if(resp==1) {
$('#msg-notify').show();
}
else $('#msg-notify').hide();
})
$('.tipsy-s').remove();
}
});
var loc_h_n = window.location.hash.replace("#", "").replace("!", "").replace(".do", ".php")
if(window.location.hash!='#!'+loc_h_n&&window.location.hash!='') {
window.location.hash = '#!'+loc_h_n;
}
$(window).hashchange();
});
</script>
as you can see he returns false on clicks and acts based on the hashtag value
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>
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 have a jQuery script that dynamically changes select menus. The script uses the function populate() everytime a change event occurs in one of the menus. I would like the same script to run after a form submit. To have an idea this is what the script looks like...
$(document).ready(function(){
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function populate() {
if ($('#STATEID').val() == 'AK' || $('#OB_USTATEID').val() == 'DC') {
// Alaska and District Columbia have no counties
$('#county_drop_down3').hide();
$('#no_county_drop_down3').show();
}
else {
fetch.doPost('../../getCounties2c.php');
}
}
$('#STATEID').change(populate);
var fetch = function() {
var counties = $('#countyid');
return {
doPost: function(src) {
$('#loading_county_drop_down3').show(); // Show the Loading...
$('#county_drop_down3').hide(); // Hide the drop down
$('#no_county_drop_down3').hide(); // Hide the "no counties" message (if it's the case)
if (src)
$.post(src, { state_code3: $('#STATEID').val() }, this.getCounties);
else
throw new Error('No SRC was passed to getCounties!');
},
getCounties: function(results) {
if (!results)
return;
var allCities = $("<option value=\"All\">All Counties</option>");
counties.html(results);
counties.prepend(allCities);
var first = getUrlVars()["countyid"];
if (first) {
counties.val(first).attr('selected',true);
}
else {
counties.val("All").attr('selected',true);
}
$('#loading_county_drop_down3').hide(); // Hide the Loading...
$('#county_drop_down3').show(); // Show the drop down
}
}
}();
populate();
});
How can I accomplish that? Any suggestions will be highly appreciated!
Use $(element).submit(function (e) {} ); to catch a submit event. You can even fire it off, by calling $(element).submit().
jQuery docs : http://api.jquery.com/submit/
How to detect tab close in browsers using PHP or Javascript. In other words, How to find if page is refreshed or opened in new tab. I am concerned about tab, not browser.
You can have a listener for the window.onbeforeunload event. You won't be able to detect if the tab is closed from JavaScript, though.
Actually Javascript can tell you if a Tab is going to be closed. Two different methods need to be used (one for IE and one for everyone else).
I wrote a Javascript process to do just what you are asking. Pre-requisites for the process is jQuery and one plugin (livequery - because some of the HTML is dynamically generated after page load). Anyway, here is the js file that does all this (checkclosing.js):
// Global Var
var bodyclicked = false;
var datachanged = false;
var nodirtycheck = false;
// Start the engines :)
$(document).ready(function () {
init();
});
function init() {
bindEvents();
}
function bindEvents() {
// Bind the onClick event for the DOM body
$(document).livequery(function () {
bodyclicked = true;
});
// Bind our event handlers for the change and reset events
$(':input').not('.excludeFromDirtyCheck').bind('change', function () {
if ($(this).hasClass('dataLoader')) {
if (!datachanged) {
return;
}
}
datachanged = true;
$(".hidDataChanged").val("True");
});
$(':reset,:submit').bind('click', function () {
// .NET renders some ASP Buttons as Submit and Reset types
if ($(this).hasClass('notSubmit')) {
return;
}
if ($(this).hasClass('notReset')) {
return;
}
datachanged = false;
$(".hidDataChanged").val("False");
});
// Must have the livequery plugin referenced for this to work
$('.resetchangedform').livequery('click', function (event) {
//alert("resetchanged"); // FIXME
datachanged = false;
// Set our hidden input (on the Administration Master page)
$(".hidDataChanged").val("False");
});
// Must have the livequery plugin referenced for this to work
$('.setchangedform').livequery('click', function (event) {
//alert("setchanged"); // FIXME
datachanged = true;
// Set our hidden input (on the Administration Master page)
$(".hidDataChanged").val("True");
});
// Must have the livequery plugin referenced for this to work
$('.excludeFromDirtyCheck').livequery('click', function (event) {
nodirtycheck = true;
});
// Must have the livequery plugin referenced for this to work
$('.notSubmit').livequery('click', function (event) {
nodirtycheck = true;
});
// Must have the livequery plugin referenced for this to work
$('.dataReloader').livequery('change', function (event) {
nodirtycheck = true;
});
window.onbeforeunload = function () {
//alert("datachanged = " + datachanged + " | nodirtycheck = " + nodirtycheck + " | hidDataChanged = " + $(".hidDataChanged").val());
// Check the hidden textbox
if ($(".hidDataChanged").val() == "True") {
datachanged = true;
}
if (nodirtycheck) {
nodirtycheck = false;
}
else {
if (navigator.appName == "Microsoft Internet Explorer") {
// IE
if (bodyclicked) {
if (datachanged) {
return "You may have unsaved changes...";
}
}
else {
bodyclicked = false;
// Do Nothing
}
}
else {
// Not IE
if (datachanged) {
return "You may have unsaved changes...";
}
else {
// Do Nothing
}
} //if (navigator.appName == "Microsoft Internet Explorer") {
} //window.onbeforeunload = function () {
} // if (nodirtycheck) {
}
Then just include a reference to this file on any page you want to check for a tab close on:
This was built to help prevent users from navigating away from pages with unsaved changes to form values. Yes, I know that most of the time, it is bad practice to prevent the user from closing a tab or navigating away, but in this case - the users requested it and this is an internal application that is not for public consumption.
Any controls that you don't want to be checked for changes prior to letting the user close the tab or navigate away would just be given a class name of excludeFromDirtyCheck.
This may be more than you need, but you can strip off the parts that aren't useful. The basic premise is the same.
I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});