hash jquery and call ajax - php

I'm thinking to do a image gallery dynamic and i'm looking for a solution simalar to facebook but using the url hash.
I would like receive dettails about this type of call ajax for get information dinamically without refresh the page, this is the right way for do what i'm looking for? There is some issue with the old browser?
<html>
<head>
//jquery.js
</head>
<body>
<!-- #nameimage is the name of the big image that will be loaded,
so this hash will be used for the call ajax. -->
<img src="url-thumb-image1">
<img src="url-thumb-image2">
<img src="url-thumb-image3">
<img src="url-thumb-image4">
<div class="image-big"></div>
</body>
</html>
Jquery
$(document).on('click','a', function(){
var hash = window.location.hash; // nameimage
// very simple ajax
BASE_URL = 'http://localhost/';
$.ajax({
type: "POST",
url: BASE_URL + 'get_image',
data: "name_image=" + hash,
success: function(result) {
// print result on div
$('.image-big').html(result);
},
error: function(){
alert('Error on ajax call');
}
});
});
PHP
<?php
$name_image = $_POST['name_image'];
$path = 'main_folder/image/';
echo '<img src="'.$path.$name_image.'.jpg">';
// and i can cache the results
?>

var hash = window.location.hash; // nameimage needs to instead look at the href of the anchor tag, the window location hash hasn't been updated yet at that point.
var hash = $(this).attr("href");

I think you need to remove the hash:
var hash = window.location.hash.substr(1);
But maybe the hash isn't defined yet at that moment. So it's better to use
$(document).on('click','a', function(e){
var hash = e.currentTarget.href.substr(1)
...

Related

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

Click image to call php function

I need to click an image and it should run some php script that sets a php variable and reloads the same page.
I know it sounds simple but i've tried every different way I can think of and i'm guessing it's just something basic i've missed.
I've tried onclick of the image, a href and a onclick, making the image the 'submit button' of a form etc..
Any response would be appreciated.
<a href="#" class='lang'><img src="/images/flags/it.png" alt="it_IT" /></a>
<a href="#" class='lang'><img src="/images/flags/fr.png" alt="fr_FR" /></a>
I want the image alt value to pass it,
How it is possible please give some idea..
try this:
Lets say that the PHP variable you want to change is $my_var:
Set it like this:
if(isset($_GET['VarValue']) And !empty($_GET['VarValue'])){
//if it is passed and not empty store it
$my_var = $_GET['VarValue'];
}
else{ die(''); }//else don't let them display the page.
In the image put an On Click Listener hat call this function PHP_var();
In JavaScript add this function:
function PHP_var(){
location = "?VarValue=The_Value_That_You_Want_To_Set";
}
And the URL must be like this when you first call this page(lets say it is http://www.example.com/script.php?VarValue=The_First_Valeu_Of_Variable).
The function will change the VarValue value and will reload the page
try
$('.lang img').on('click',function(){
var lang = $(this).attr('alt');
var postdata = 'lang='+lang;
$.ajax({
type:'POST',
data:postdata,
url:'process/yourscript.php',
success:function(data){
// more processing here
}
});
return false;
});
Use onclick="ajaxFunctionName()" to call an ajax function which executes your script
<a href="javascript:;" onclick="ajaxFunctionName()" class='lang'><img src="/images/flags/it.png" alt="it_IT"/></a>
<a href="javascript:;" onclick="ajaxFunctionName()" class='lang'><img src="/images/flags/fr.png" alt="fr_FR"/></a>
function ajaxFunctionName() {
$.post({
var lang = $( this ).children('img').attr('alt');
url: "script.php?lang="+lang
}).done(function() {
// do something
});
}
or
<img class='lang' src="/images/flags/it.png" alt="it_IT"/>
$('.lang').click(function(){
$.post({
var lang = $( this ).attr('alt');
url: "script.php?lang="+lang
}).done(function() {
// do something
});
});

HTML Get URL parameter

I want to change url without reload the page because Im using AJAX function to reload a div.
The problem is that when the AJAX load the div, it doesn't read the url parameter.
My code (I've already load the jquery.js etc.) :
index.php
<a href="#page=1" onClick='refresh()'> Link </a>
<a href="#page=2" onClick='refresh()'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh() {
$("#test").load("mypage.php"); //Refresh
}
</script>
<div id="test">
</div>
mypage.php
<?php
if (isset($_GET['page'])){
$page = $_GET['page'];
}
echo $page;
?>
PHP can't read the fragment without reloading the page. This can be done using JS.
Below the script I use to read the parameter values without reloading the page. I don't think it's the best method there is, as there are plugins you could use to do the same (and much more), but it works. I found it online some time ago, but unfortunately I don't remember where :(
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.hash.slice(1);
urlParams = {};
while (match = search.exec(query)) {
urlParams[decode(match[1])] = decode(match[2]);
}
})();
You would then get the parameter value with:
urlParams['page']
If you will work a lot with hash urls, you should check out this plugin: http://benalman.com/projects/jquery-bbq-plugin/
Getting after # hash tag:
With PHP (Required page load)
parse_url() fragment index thats you need
$url = parse_url($_SERVER['REQUEST_URI']);
$url["fragment"]; //This variable contains the fragment
With jQuery: (Not required page load)
var hash = $(this).attr('href').split('#')[1];
var hash = $(this).attr('href').match(/#(.*$)/)[1];
Demo (Used without hash tag)
index.php
Link | Link2
<script type="text/javascript">
$(".myLink").click(function(e) { // when click myLink class
e.preventDefault(); // Do nothing
var pageId = $(this).attr('data-id'); // get page id from setted data-id tag
$.ajax({
type:'POST',
url:'mypage.php', // post to file
data: { id: pageId}, // post data id
success:function(response){
$("#test").html(response); // write into div on success function
}
});
});
</script>
<div id="test"></div>
mypage.php
<?php
// get with $_POST['id']
echo "Loaded Page ID: ".($_POST['id'] ? $_POST['id'] : "FAILED");
?>
You need to pass a page parameter to the URL you're requesting.
Try this:
<a href="#page=1" onClick='refresh(1)'> Link </a>
<a href="#page=2" onClick='refresh(2)'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh(pageNumber) {
$("#test").load("mypage.php?page="+pageNumber); //Refresh
}
</script>
It is possible for you to pass parameters through the load() function in jQuery.
There are 2 common ways of doing so:
Using get:
JS:
$('#test').load('mypage.php?page=mypage');
PHP:
<?php
if (isset($_GET['page']))
{
$page = $_GET['page'];
}
echo $page;
?>
Or using data as a post:
JS:
$('#test').load('mypage.php', { page: mypage });
PHP:
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
echo $page;
?>

AJAX: Open content in another div

I'm working with AJAX on a website and I'm currently making some pages to load on a certain div: "pageContent". Now I have another content I want to be opened on another div: "reproductor". I want to open 'page' in 'pageContent' div and 'play' in 'reproductor' div. I don't know how to modify my script.js and load_page.php files in order to make it work. Here's what I got:
HTML:
<script type="text/javascript" src="js/script.js"></script>
PAGE
PLAY
<div id ="pageContent"></div>
<div id="reproductor"></div>
script.js:
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').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(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
load_page.php:
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else
echo 'There is no such page!';
?>
I forgot to mention: I have my 'pages' content in a folder named 'pages' and my 'play' content in another named 'plays'.
Thanks for your help!
The easiest way to load content from a resource that serves HTML into an element is to use load:
$('#reproductor').load('public_html/plays/play_1.html', function(){
//stuff to do after load goes here
});
You could also apply this technique to the other div you are trying to load content into.
If I understand, your have two groups of links (for pages and a play list) each one to be loaded in a different container. Here is something you can try: mainly I eliminated the global variables and put the current hash inside each containter's data, and separated the management of the two groups of links.
In this code I supposed you have a separate load_play.php file. If not, then you can use the same page for both kind of links, but you'll have to merge loadPlay with loadPage, change loadPage(newHash) to loadPage(newHash, linkType) and change the ajax parameter from 'page='+newHash to 'number='+newHash+'&type='+linkType, and do the corresponding changes server side in your PHP page. I would recommend you to create two separate PHP files in order to manage the two types of content.
I remember you where doing something with the hash of the current page's url, you can still set it in the ajax's success, inside the loadPage function.
Here is a working sfiddle example with some console calls (open browser's console) but without the ajax call.
UPDATE:
I updated the code, so your can manage the dynamically added links (new content loaded via AJAX) and fixed the management of urls with hashes, which was broken because of the new code.
<div id="#page">
PAGE 1
PAGE 2
PLAY 1
PLAY 2
PLAY 3
<div id ="pageContent"></div>
<div id="reproductor"></div>
</div>
And this is the javascript:
$(document).ready(function(){
$('#pageContent').data('currentPage', '');
$('#reproductor').data('currentPlay', '');
//This will allow it to work even on dynamically created links
$('#page').on('click', '.pageLink', function (e){
loadPage(this.hash);
});
$('#page').on('click', '.playLink', function (e){
loadPlay(this.hash);
});
//And this is for managing the urls with hashes (for markers)
var urlLocation = location.hash;
if(urlLocation.indexOf("#page") > -1){
$('.pageLink[href='+ urlLocation +']').trigger('click')
}
});
function loadPage(newHash)
{
//This is the current Page
var curHash = $('#pageContent').data('currentPage');
//and this is the new one
newHash = newHash.replace('#page', '');
if(curHash===newHash){
//If already loaded: do nothing
return
}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg).data('currentPage',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
function loadPlay(newHash)
{//Similar to loadPage...
var curHash = $('#reproductor').data('currentPlay');
newHash = newHash.replace('#play', '');
if(curHash===newHash){return}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_play.php",
data: 'play='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#reproductor').html(msg).data('currentPlay',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
Check this and comment if this is what you need, or I got something wrong :)
There are a number of reasons why the following is not an ideal solution. The most glaring would be security - by modifying the href attribute of the link before clicking it, the user can certainly get your server to serve up any html on your server.
EDIT I've removed my original answer, because I can't recommend it's usage.
As Asad suggested, you can also use jQuery load and pass it the relevant url using some of the code above
function loadPage(url)
{
// remove the hash in url
url=url.replace('#','');
// extract page or play - only works for four letter words
var contentType=url.substr(0,4);
// extract the number
var contentId=url.substr(4);
if ( $contentType == "page") {
$("#pageContent #loading").css('visibility','visible');
$("#pageContent").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#pageContent #loading").css('visibility','hidden');
} else if ( $contentType == "play") {
$("#reporductor #loading").css('visibility','visible');
$("#reproductor").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#reporductor #loading").css('visibility','hidden');
}
}

How to get parameters from a link that callls a jQuery function?

I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>

Categories