How to change my page title <title></title> after content is loaded in #container div?
$(document).ready(function () {
$("a.view").live('click', function () {
var id = $(this).data("id");
$('#container').load("view.php?" + id);
});
});
If without .load() I retrieve it by get the id via URL, example view.php?id=1
if (isset($_GET['id'])) {
$pageid = intval($_GET['id']);
$select = $db->query('SELECT id, title FROM content WHERE id="'.$id.'"');
$data = $db->fetch($select);
$title = $data['title'];
}
So in my header.php just call it <title><?php echo $title; ?></title>
If in this case file is load after header.php so how can I create dynamic my page title according to current .load("view.php?" + id)?
You can set the document.title property:
document.title = "My new title!";
add a callback function in the .load call, the responseText, textStatus, XMLHttpRequest are all arguments that will be passed to the callback.
function myCallback(responseText, textStatus, XMLHttpRequest)
{
document.title = "Set new title";
}
$(document).ready(function () {
$("a.view").live('click', function () {
var id = $(this).data("id");
$('#container').load("view.php?" + id,myCallback);
});
});
Related
I am trying to pass a string from a query into a javascript function.
An integer will pass into the function but string will not.
echo "<a href='#' onclick='delete_game({$title});'
class='btn'>Delete</a>";
<script type='text/javascript'>
function delete_game(title){
var answer = confirm('Really?');
if(answer){
window.location = 'delete.php?id=' + title;
}
}
</script>
I expected the javascript function to be executed, but instead nothing happens.
Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.
In your HTML, you can do something like
I'm assuming that you are using Blade.
Delete Game
Then in your javascript, you do this using jQuery:
function deleteGame(title){
var answer = confirm('Really?');
if(answer){
$.ajax({
url : "your-php-file.php",
type : 'post',
data : {
title : title
}
})
.done(function(msg){
$("#result").html(msg);
})
.fail(function(error){
console.log(error);
});
}
}
In your PHP you process receiving the data from post $_POST
$title = $_POST['title'];
You can understand better the Ajax function of jQuery here.
A few things:
I would change window.location to window.location.href
Change your echo to:
echo "Delete";
Check if $title is set
var_dump($title);
If you'd like to make it a bit cleaner and are prepared to use jQuery:
Delete
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
var title = $(this).data('title');
var answer = confirm('Really?');
if (answer){
window.location.href = 'delete.php?id=' + title;
}
});
</script>
When request is ajax, i am rendering content section and inserting it to DOM. It is working as expected.
However.. i can't find out the way, how to render multiple sections, like content and title and more in the same time.
Controller:
public function awesome(Request $request) {
if($request->ajax()){
return view('awesome')->renderSections()['content'];
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data);
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});
layouts.app
<title>#yield('title')</title>
<meta name="description" content="#yield('desc')"/>
<a data-request="push" title="AWESOME" href="<?= url('/'); ?>/awesome">Awesome</a>
<a data-request="push" title="RANDOM" href="<?= url('/'); ?>/random">Random</a>
<div id="content">
#yield('content')
</div>
Blade:
#extends('layouts.app')
#section('title', 'Awesome')
#section('desc', 'About awesome')
#section('content')
some text from awesome page
#endsection
Question:
How to render both or more of them in same time? Should i use an array or something else? Please give example or full explanation.
Thanks for any answers.
You can just send a json object of title and content, and then use JS to parse the array and extract both sections. Like so:
Controller
public function awesome(Request $request) {
if($request->ajax()){
$view = view('awesome')->renderSections();
return response()->json([
'content' => $view['content'],
'title' => $view['title'],
]);
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data.content);
document.title = data.title;
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});
I need when I click anchor tag I need load controller function and get data from calling function in the model and send it to view_content page and display data
here is my code
view
<div id="loading"></div>
Click Here
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".company").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var site_url = "<?php echo site_url('site2/home2/'); ?>" +id; //append id at end
$("#loading").load(site_url);
//alert(id);
//alert("aawa");
});
});
</script>
controller
public function home2($id){
$this->load->model('get_click_data');
$data['company_data'] = $this->get_click_data->get_company($id);
$this->load->view('view_content',$data);
}
model
<?php
class Get_click_data extends CI_Model{
public function get_company($id){
$query = $this->db->query("SELECT * from companydetails where id = '$id'");
return $query->result();
}
view_content
<div id="content">
<h3>Welcome to Home Page 12345</h3>
<?php
print_r($company_data);
?>
as you are using codeigniter, try changing to:
...
var id = $(this).attr('id'); //you need to have 'id' attribute in your anchor
$("#loading").load("<?php echo site_url('site2/home2/); ?>" + id, function() {
alert("aawa");
});
...
and in your controller file,
function some_function($your_id) {
//get data
//do something with $your_id
//pass view as string
echo $this->load->view('view_content', $data, TRUE);
}
Update::
to put js variable in your site url, do:
var id = $(this).attr('id');
var site_url = "<?php echo site_url('site2/home2/'); ?>" + id; //append id at end
$("#loading").load(site_url, function() {
alert("aawa");
});
one more update::
if you want to pass multiple parameters to your function from js, you can do:
var id = $(this).attr('id');
var second_param = "some value here";
var site_url = "<?php echo site_url('site2/home2/'); ?>" + id + "/" + second_param;
$("#loading").load(site_url, function() {
alert("aawa");
});
and in your controller function
function some_function($your_id, $other_param) {
do something with $your_id and $other_param
//pass view as string
echo $this->load->view('view_content', $data, TRUE);
}
addition::
in your home2() function your are trying to load view, change
$this->load->view('view_content',$data);
to
echo $this->load->view('view_content',$data, TRUE);
so that its returned as string to your .load() jquery function
its working
<script type="text/javascript">
$(document).ready(function(){
$(".company").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
$("#loading").load('<?php echo site_url('site2/home2/'); ?>'+id);
alert(id);
//alert("aawa");
});
});
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;
?>
I am using jquery + the hashchange plugin from ben alman. Below is a standard way to grab the hash name and load in content
$(window).hashchange(function() {
var hash = location.hash;
var array_url = hash.split('#');
var page = $(array_url).last()[0];
$('#content').load( page + '.php', function(){
});
});
But is there any way to do this by grabbing some other variable assigned on a click function or sorted through php, perhaps?
I am working with a multi-artist portfolio site that hands out unique three-four letter codes to images
I'd like to serve these images up through unique urls. This has to be through ajax for many reasons.
I had difficulty adding other ajax history options because this page is already using ajax pagination (to load this content) and lots of htaccess url modrewrites.
I am thinking this might just be impossible.
Here is my current code
$('a.photo').click(function () {
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
return false;
});
$(window).hashchange( function(){
var hash = location.hash;
var url = ( hash.replace( /^#/, '' ) || 'blank' );
document.title = url;
})
$(window).hashchange();
and my html / php :
$thethumb = customuniqueidfunc();
<a href="[IMG URL]"
class="photo gotdesc nohover" rel="<?php echo $row['description'] ?>"
id="<?php echo $thethumb; ?>">
This works insofar as the image from the href attr loads into the #content div and the hash from the id attr is added as a hash to the url and to the title of the page, but I am lacking any mechanism to combine the click and the hashchange function, so that each hash actually corresponds to the image.
One method I've used for this before is to run a hash polling function. You can see it in action at this page:
http://www.webskethio.com/#services
Here is the javascript for that page:
http://www.webskethio.com/ws.js
Relevant code:
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
$(document).ready(function(){
/* code removed for readability */
setInterval('pollHash()',100); // Important piece
/* code removed for readability */
});
and
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
var url = $(this).attr('href'),
image = new Image();
image.src = url;
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
}
[EDIT :] Here is the full code for your page that should work, provided you can create a page that just outputs the image's location from the database.
var recentHash = "";
var image_url ="";
$(document).ready(function() {
$('a.photo').click(function (event) {
var clickedLink = $(this).attr('id');
location.hash = clickedLink;
event.preventDefault();
});
setInterval('pollHash()',100);
});
function pollHash() {
//exit function if hash hasn't changed since last check
if (window.location.hash==recentHash) {
return;
}
//hash has changed, update recentHash for future checks
recentHash = window.location.hash;
//run AJAX to update page using page identfier from hash
initializeFromUrl(recentHash.substr(1));
}
//AJAX function to update page if hash changes
function initializeFromUrl(fromLink) {
/* code removed for readability */
//take hash from function call or from the URL if not
input = fromLink || window.location.hash ;
//remove # from hash
output = input.replace("#","");
//get the URL of the AJAX content for new page
pageId = output;
if(pageId != ""){
var temp_url = 'http://whitecu.be/user/mountain/'+pageId+'.html';
$.get(temp_url, function(data) {
image_url = data;
image = new Image();
image.src = image_url;
image.onload = function () {
$('#content').empty().append(image);
};
image.onerror = function () {
$('#content').empty().html('That image is not available.');
}
$('#content').empty().html('Loading...');
});
}else{
window.location = "http://whitecu.be/user/mountain";
}
}