I have a website, that uses PHP to select the content,
<div>
<? include ("navigation.php"); // navigation.php generates the menu ?>
</div>
<div>
<?
$type = $_GET["type"];
switch ($type) {
case "page" :
include "Text.php";
break;
case "news":
include "news_2.php";
break;
default :
include "main.php";
}
?>
</div>
The url is of the format domain.com/index.php?type.
I need to change the block #content without reloading the whole page, how can I do this?
As you've tagged the question with "jquery" I assume you know what that is, and that you're loading it into your page.
All you need to is give your div and ID... content here
And then use a bit of jquery.. in its simplest form just to load your content from 'myurl.php' into 'mydiv' when the page has finished loading:
$(document).ready(function() {
$("#mydiv").load("myurl.php");
});
You'll no doubt want some logic to determine what loads, and under what circumstances. If you need to pass data back to the URL then you'll need to go for jquery ajax ($.ajax). Its all pretty easy, loads of examples on the web, and good docs on the JQuery website.
This would best be done with Ajax. I like using jQuery's ajax function. Something like this:
function load(page){
var datastring='ANY DATA YOU WANT TO SEND';
$.ajax({
type: "POST",
url: 'your/pagehtml/',
data: "bust="+Date()+datastring,
dataType: "html",
cache: false,
success: function(html){
$('#content').html(html)
}
});
return false;
}
You wouldn't need to send the page in the URL this way. Anytime you change the url, you must be loading a different page. Outside of .htaccess rewrite. Which isn't what you need.
Fire this on click or whatever you want.
If you're using jQuery, it's pretty easy. You didn't post what is supposed to trigger the change, so I'll assume you have a list of links in another element with an id of nav.
Read more about the jQuery Ajax request here: http://api.jquery.com/jQuery.ajax/
//run on page load
$(function(){
//bind a click event to the nav links
$("#nav a").bind("click", function(e){
//keep the links from going to another page by preventing their default behavior
e.preventDefault();
//this = link; grab the url
var pageLocation = this.href;
//fire off an ajax request
$.ajax({
url: pageLocation,
//on success, set the html to the responsetext
success: function(data){
$("#content").html(data.responseText);
}
});
});
});
I'd also suggest doing some code cleanup like caching your $("#content") element on the load event (something like window.container = $("#container"), and using window.container later on), but I left it as-is so that everything remains clear.
Related
I have to create a simple website with various pages (5-6). Now I have one "master" page called index.php like this:
<html>
<head></head>
<body>
<div id="content"></div>
</body>
</html>
This page has also other div's on it, like a header where I show some images etc. and is styled with a css.
Now when the user clicks on a link in the menu bar, whatever page I want to show is loaded via jQuery/AJAX into the content div. I do this here:
$(document).ready(function () {
// Per default load home.php
var url= "home.php";
$.ajax({
url: url,
success: function(data){
$('#content').html(data);
}
});
$('#register').click(function() {
var url= "register.php";
$.ajax({
url: url,
success: function(data){
$('#content').html(data);
}
});
});
// more pages here..
});
This works perfectly fine and I am happy with the result, now on to the problem.
On some of these pages (like register.php) I have forms that I submit. Now once I submit the form and do various things like database operations etc. I want to redirect to one of the other pages and maybe show a short information message. What I do to redirect in the php file is the following:
header('Location: ../app/index.php');
I got this somewhere from a code snippet, so I am not sure if this is the proper way to do this. Because I have per default set the index.php to load my home.php content, it always redirects to my home.php content and I was happy with this. But what if I want to redirect to another page, lets say go.php? How would I do this? Is this even possible from php or do I need to do this with javascript/jQuery?
I am a bit lost here, have tried searching for it but didn't come across exactly this issue here.
For submit form and database connection :
you can use onclick function to handle actions for submit button :
example in .JS file
$(document).ready(function(){
$('#submit').click(function(){
var input = $('#textfiel').val();
$.post("ajaxHandle.php",
{data:input }
).success(function(responce){
$('#responceMessage').prepend(responce);
/* This is the field on your index.php page where you want to display msg */
});
});
});
ajaxHandle.php file:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$inputData = $_POST['data'];
/* your database code will be done here you can find user input data in $inputData */
echo "registration successful"; /* this string will be get in var responce in .JS file */
}
To redirect page dynamically :
you can use .load() function for example :
$('#content').load('../app/register.php');
use this http://api.jquery.com/load/ reference to use it.
I'm using the code below to load the results from a database query in a PHP page:
click me
$('.item > a').click(function(){
var url = $(this).attr('href');
$('.item-popup').fadeIn('slow');
$('.item-content').load(url);
return false;
});
All works fine right now, but the next bit of functionality is a problem. Inside results.php which ajax loads into .item-content, I have another link that is supposed to update and increment click counts for that link, also without refreshing. The functional PHP bits all work fine. My only problem is the jQuery/AJAX aspect of things.
Maybe I'm going about it the wrong way, but what I really want to do is have a page with a container that loads the result of of a database query from a PHP page, but also in that container, I have a link/button whose click count I want to be able to save and update all without refreshing.
EDIT
I guess the most important question I need answering is: When the ajax on index.php loads the content of results.php into the container in index.php, do browsers treat the newly loaded ajax content as part of the parent page (index.php) or is it still treated as a different page loaded into the container like an iFrame?
If say for example it is click event then you need to write
$('input element').on('click',function() {
// write code over here
})
Dont know for sure if you want this, When returning the data in the load function you will have to add a link like this in the resultant HTML which will be clickable:
Now in javascript you need to catch the click event of the link like this:
<script type="text/javascript">
$(function(){
$(".item-content").on("click", ".clickable", function(){
var counter = $(this).data('counter');
var id = $(this).data('id');
$.ajax({
url : //your url here,
data : {'id' : id, 'counter' : counter },
type : 'POST',
success : function(resp){
//update the counter of the current link
$(this).data('counter', parseInt( $(this).data('counter') )+1 );
//whatever here on successfull calling of ajax request
},
error : function(resp){
}
});
});
});
</script>
Finally, I find some article in http://code.google.com/intl/en/web/ajaxcrawling/docs/getting-started.html msnbc use this method. Thanks for all the friends.
Thanks for your all help. I will study it for myself :-}
Today, I updated my question again, remove all of my code. Maybe my thinking all wrong.
I want make a products show page.
One is index.php, another is search.php (as a jquery box page). index.php has some products catagory lists; each click on product catagory item will pass each value to search.php. search.php will create a mysql query and view products details. It(search.php) also has a search box.(search.php can turn a page to show multiple products; the search result looks similar to a jQuery gallery...).
I need to do any thing in search.php but without refreshing index.php.
I tried many method while I was thinking: Make search.php as an iframe (but can not judge search.php height when it turn page and index.php without refresh); use jquery ajax/json pass value from index.php to search.php, then get back all page's value to index.php. (still met some url rule trouble. php depend on url pass values in search.php, but if the value change, the two page will refresh all. )
so. I think, ask, find, try...
Accidental, I find a site like my request.
in this url, change search word after %3D, only the box page refresh
in this url, change search word after = the page will refresh
I found somthing in its source code, is this the key rules?
<script type="text/javascript">
var fastReplace = function() {
var href = document.location.href;
var siteUrl = window.location.port ? window.location.protocol+'//'+window.location.hostname +':'+window.location.port : window.location.protocol+'//'+window.location.hostname;
var delimiter = href.indexOf('#!') !== -1 ? '#!wallState=' : '#wallState=';
var pieces = href.split(delimiter);
if ( pieces[1] ) {
var pieces2 = pieces[1].split('__');
if ( pieces2[1] && pieces2[1].length > 1) {
window.location.replace( unescape(pieces2[1].replace(/\+/g, " ")));
}
}
}();
</script>
If so. in my condition. one page is index.php. another is search.php.
How to use js make a search url like
index.php#search.php?word=XXX&page=XXX
then how to pass value from one to another and avoid refreshing index.php?
Still waiting for help, waiting for some simple working code, only js, pass value get value.
Thanks to all.
I have read your problem, though I can not write complete code for you (lack of time ) So I can suggest you to what to do for your best practice
use dataType ='json' in jQuery.ajax function and
write json_encode() on B.php
and json_decode() on A.php or $.getJSON()
Alternate:
Read
jQuery.load()
assuming you really want to do something like here: http://powerwall.msnbc.msn.com/
I guess they are using a combination of ajax-requests and something like this: http://tkyk.github.com/jquery-history-plugin/
make shure that the navigation (all links, etc.) in the box works via ajax - check all the links and give them new functionality by js. you can write some function which requests the href url via ajax and then replace the content of your box. ...
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
//update url in addressbar
change_box_links(output_area);
}
});
});
});
}
it is upgradeable but shell show the main idea...
addendum[2011-05-15]
Get away from thinking you will have two files, that can handle some many "boxes". i mean you can do this but it's worth it.
but to be able to set up your templates like normal html page you could use the above script to parse the ajax requested html pages.
build your html-pages for
viewing the content,
viewing the search result
, etc.
on your main page you have to provide some "box" where you can display what u need. i recommand a div:
<div id="yourbox"></div>
your main page has buttons to display that box with different content, like in the example page you have showed us. if you click one of those a JS will create an ajax call to the desired page:
(here with jquery)
$('#showsearch_button').bind('click', function(){showsearch();});
function show_search() {
$.ajax({
url: 'search.php',
success: function(data){
var output_area = $('#yourbox');
output_area.html(data);
$.address.hash('search');
change_box_links(output_area);
}
});
});
for other buttons you will have similar functions.
the first function (see above) provides that the requested box-content can be written as a normal html page (so you can call it as stand-alone as well). here is the update of it where it also provides the hashtag url changes:
jquery and requireing the history-plugin
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
var name = url.replace('/\.php/','');
$.address.hash(name);
change_box_links(output_area);
}
});
});
});
}
and you will need some kind of this function, which will bind the back and forward buttons of your browser:
$.address.change(function(event) {
var name = $.address.hash();
switch(name){
case 'search': show_search(); break;
default: alert("page not found: "+name);
}
});
the above code should give an idea of how you can solve your problem. you will have to be very consequnt with filenames if you just copy and past this. again: it is improveable but shell show you the trick ;-)
im not sure that i fully understood what you want, but correct me if i didnt,
i think u need something like a dropdown that once the user select one item some div inside ur page show the result of another page result..
if so u can do it with jquery .load() and here is an example (no need for json)
Step 1:
Index.php
<p>
brand:<select id=jquerybrand>$jquerybrands</select><br />
Model:<select id=jquerycars></select><br />
</p>
<script type=\"text/javascript\">
$(document).ready(function(){
$('#jquerybrand').change(function(){
var value=$(this).value;
var url='api/quick.php?'+this.id+'='+this.value+' option';
$('#jquerycars').load(url);
});
});
</script>
This will simply show 2 dowpdown boxs (can be text or anything u like). and will add a listener to any change in value. once changed it will submit the id of the field and the new value to api/quick.php , then quick.php responce will be loaded into #jquerycars dropdown.
Step 2 quick.php
if(isset($_GET['jquerybrand'])){
$jquerycars="";
require_once("../lib/database.php");
$sql_db = new database();
$l=$sql_db->Item_in_table("car","sheet1","WHERE `brand`='$jquerybrand';");
foreach($l as $l)$jquerycars .="<option>$l</option>";
echo $jquerycars;//response that will replace the old #jquerycars
}
this will confirm that this is a request to get the query result only, then it will do the query and echo the results.
now once the results come back it will replace the old :)
hope it helps :).
I have a function which loads some content when executed...
IE...
function load_product(product_id) {
$.ajax({
type: 'GET',
url: 'product_image.php',
data: 'product_id='+product_id+'',
success: function(data) {
$('#product_image').html(data);
}
});
}
That works great. But say I want to create a link to a page, so that then something triggers to load up the dynamic content?
IE I link to a page, say
www.blah.com/?product=1
and a few 'divs' on the page that load up different things dynamically for product #1.
The way I currently do it is by doing something:
<?php
if($_REQUEST['product_id']) {
echo '
<script type="text/javascript">
$(document).ready(function(){
load_product(' . $_REQUEST['product_id'] . ');
});
</script>
';
}
And I put that somewhere on the new page being loaded. It works. But is there a better way?
I do something similar but using YepNope.js.
<script>
var hasProduct = <?php echo isset($_REQUEST['product']) ? 'true' : 'false' ?>
yepnope({
test : hasProduct,
yep : 'js_file_to_load.js',
});
</script>
Then you can store all you main js in an external file. This has the added advantage over your method in that, I don't have to load the external scripts for every request just in case $_REQUEST['product'] is set.
You can do this all in JavaScript.
Use 'location.search' to give you the query part of the current URL...
for example, if the url is "www.blah.com/?product=1" then location.search returns "?product=1". Then you can just use split('=') to get part number. Of course, you can also just get the whole URL using 'location.href'... doesn't really matter.
var productNum = parseInt(location.search.split('=')[1]);
You would probably want more checks in there, but that's the basic idea.
I need to create a page that will load divs from an external page using Jquery and AJAX.
I have come across a few good tutorials, but they are all based on static content, my links and content are generated by PHP.
The main tutorial I am basing my code on is from:
http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
The exact function i need is as follows:
Main page contains a permanent div listing some links containing a parameter.
Upon click, link passes parameter to external page.
External page filters recordset against parameter and populates div with results.
The new div contains a new set of links with new parameters.
The external div is loaded underneath the main pages first div.
Process can then be repeated creating a chain of divs under each other.
The last div in the chain will then direct to a new page collating all the previously used querystrings.
I can handle all of the PHP work with populating the divs on the main and external pages.
It's the JQuery and AJAX part i'm struggling with.
$(document).ready(function(){
var sections = $('a[id^=link_]'); // Link that passes parameter to external page
var content = $('div[id^=content_]'); // Where external div is loaded to
sections.click(function(){
//load selected section
switch(this.id){
case "div01":
content.load("external.php?param=1 #section_div01");
break;
case "div02":
content.load("external.php?param=2 #section_div02");
break;
}
});
The problem I am having is getting JQuery to pass the dynamically generated parameters to the external page and then retrieve the new div.
I can currently only do this with static links (As above).
I'm not sure if you've solved this already, but I'm surprised no one's mentioned to use the ajax() function.
This would allow you to define the request type as GET:
function loadContent(id) {
$.ajax({
type: "GET",
url: "external.php",
dataType: 'html',
data: {param: id},
success: function(html){
$("#container").html(html);
},
error: function(){
},
complete: function(){
}
});
}
Just call this function instead of using load. Obviously you'll have to tinker with the code (mainly what goes in the success function) a little, but this should give you a good starting point.
You can use the optional data argument to pass parameters to the GET request. Read the documentation. This is far better than building the URL yourself. You can of course add dynamic generated data to the parameters list.
function loadDiv(evt)
{
// these params will be accessible in php-script as $_POST['varname'];
var params = {name:'myDiv', var1:123, var2:'qwer'};
$.post('http://host/divscript.php', params, onLoadDiv);
}
function onLoadDiv(data)
{
$('#myContainer').html(data);
}
$(document).ready(function() {
$('#divButton').click(loadDiv);
});
In this example server-side script should return inner content of your div. Sure you can return XML-serialized data or JS to eval etc... it depends on task. The example is simplified, so extend it to fit your needs.
This tutorial on loading AJAX content is good:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
Especially the part explaining how to read the results with Firebug.
Use this :
function GetDiv(id) {
$.ajax({
type: "GET",
url: "external.php"
dataType: 'html',
data:id,
success: function(html){
$("#container").append(html);
},
});
}
var params = {
param: 1,
otherParam: 2
};
content.load("external.php #section_div01", params);
will load "external.php?param=1&otherParam=2"