run selected link in background, update url and icon of link? - php

I'm not quite sure how to word this.. but here goes :)
I have links similar to :
<img src='go.png'>
<img src='go.png'>
<img src='go.png'>
When someone clicks on the first link I want to run go.php?go=4a in the background, and change the icon on the link to stop.png, but also change the URL of this link to go.php?stop=4a.
If they think click the same link, I'd want to revert all this back to what it was.
Effectively making each link a go / stop toggle !
I seem to think jquery can do this, but I can't find any examples.
Anyone any ideas ?
Thanks :)

Provided you have jQuery loaded, and you have a container x which serves as your page content, you can use $.ajax to load dynamic content to the container and have it load/stop like:
$(function () {
$('a.tip').on(' click', function () {
var $this = $(this),
container = $('#x'),
prevHTML = container.html(),
req = {};
if ($this.hasClass('go')) {
req.abort();
container.html(prevHTML);
$this.find('img').attr('src', 'go.png');
$this.removeClass('go');
} else {
$this.find('img').attr('src', 'stop.png')
.end().addClass('go');
req = $.ajax({
url: 'go.php?go=' + $this.attr('id'),
type: 'get',
success: function (data) {
container.html(data);
$this.removeClass('go');
}
});
}
});
});
p.s. This is a rough example to get you started. Cheers!

As far as I know - what you want is not possible. Changing the URL refreshes the page, so your ajax will be lost in the nick of time.
You can use anchors though (for example if you're on go.php, you can change the url to go.php#go4a, and with the proper coding, you will be able to make the page work as if the AJAX ran.
About reverting, you will need to use a flag to see its state, then do the appropriate reverts. Not sure what you need, so this is all the information I can give you.

Related

Dynamically load PHP within a main page

I'm pretty new when it comes to PHP and AJAX, so I keep running into issues, and after scouring the web for ideas, I've come up short. I'm looking for a method to dynamically load content (PHP/HTML mixture) on one main page. The main page would include navigation, and once a link within this navigation is clicked, the content in the main content div would change. Pretty simple, right, but I've been a big struggle bus on this topic.
The method I've liked the best so far is CSS-Tricks Rethinking Dynamic Page Replacing Content which uses the HTML5 History API. I liked that it allowed the use of the back and forward browser buttons, but I could not get it to work in Chrome.
This isn't your typical "help me figure out what's wrong with my code" question, so I apologize in advance. Mostly I'm looking for a bit of advice on how best to find a solution to this problem.
Go with Ajax... I was in a similar situation a couple of weeks ago. I didn't know much about it, but this site is quite helpful:
http://www.w3schools.com/ajax/ajax_example.asp
It has simple examples that will help you to understand how the calls work.
I hope it helps. It is difficult to give more specific advice since you don't explain much about your application.
This can be done with AJAX, you will need a content/view/page anchor to determine what content is loaded, then you can use that to load content from your php,
Heres a snippet of jQuery code that uses #hash to determine content, so http://example.com/#home will do an ajax request for $_POST['view']='home'
$(function(){
// Detect hashchange (browser back/forward buttons)
$(window).bind('hashchange', function() {
load_content();
});
// Init content
load_content();
});
function load_content(){
//get the hash
var page = window.location.hash;
page = page.substring(1);
if(page == ''){
page='home';
}
//get the content, replace any - with / so php can route to sub actions ect
$.post("./", { 'view': page.replace("-","/") },
function(data) {
//load the content into the load container
$("#load").html(data).fadeIn('slow');
});
}
<div id="load"></div>
Then you can simply find the route to your script within php with:
$route = explode('/',$_POST['view']);
$controller = (!empty($route[0])) ? $route[0] : null;
$action = (!empty($route[1])) ? $route[1] : null;
Here is a simple example to make you understand :
Make an ajax call on click of the navigation links,
<p id="test">CLICK ME</p>
<p id="result">Your result</p>
Ajax code within the script tags is as follows :
$(document).ready(function() {
$("#test").click(function(){
$.ajax({
url : 'testing.php',
type : 'GET',
async : 'true',
cache : 'false',
success : function(data, textStatus, xhr)
{
$('#result').empty().html(data);
},
});
});
});
Note : the ajax call url can be php or html page or even text file where you have the result to be shown on the main page division.

Can a variable go to a hidden PHP page using jQuery?

My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>​
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});​
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>​
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,

PHP post and get value to a jQuery box page, refresh page as `msnbc.com`

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 :).

POSTing data to the server, behind the scenes

I'm building a website which has a page that users can add content to, and they can rearrange the divs to whichever position and size they want. I'd like to have a save button which saves the current position of each div; however, I don't want the page to refresh each time (I'm also going to have an auto-save, which will have to save the information in the background).
I can't figure out how to post the data to the server though, without causing the page to reload. I figure I need some kind of AJAX request, but can't find anything that tells me how to do that (all the AJAX examples I can find seem to be about reading data from the server). I think I'm just starting to go round in circles now, but I can't get my head around this at all - I know it's probably not a hard thing to do, but I keep getting confused by the different examples.
So, first of all, is this the best way to do it? And, if so, can someone point me to a straightforward example of posting data via AJAX? I'm already using jQuery, so can use that for the Ajax as well.
Thanks.
Super simple AJAX with jQuery:
$.ajax({
url: '/save-the-stuff-url',
type: 'POST',
data: {
// information about your divs, etc.
'foo' : 'bar'
},
success: function(response) {
// if the AJAX call completes successfully, this function will get called.
alert('POST successful!');
}
});
Give it a shot!
Here, try this for AJAX:
$.post("example.php", {
from : "ajax", // put some info in these - they are the params
time : "2pm",
data : "save"
},
function(data) { // callback function - data always passed to it
$("#success").html(data); // do something with that data
}
);
And put this somewhere:
<span id='success'></span>
And then, try this example for example.php:
<?php
if(isset($_POST['from']) and $_POST['from'] == 'ajax'){
echo "<span style='color: green;'>Saved!</span>";
}
else {
echo "<span style='color: red;'>Failure!</span>";
}
?>
And then just modify these to fit your needs, probably changing the file of target. Whatever the script outputs is what is given to the ajax request. This means that if this was my PHP script:
<?php echo "Aloha!"; ?>
And this was my javascript:
$("#output").load("myScript.php");
Then #output would have "Aloha!" in it.
Hope this helps!
Please go through the Jquery site for various examples of post.
HTH
and the jQuery docs pages are a great way to learn jQuery.. the page for post is http://docs.jquery.com/Post
you may also want to look at jQuery draggables if you're not using that yet..
http://docs.jquery.com/UI/API/1.8/Draggable
you can fire a save tied to your draggable object being let go rather easily with
$( ".selector" ).draggable({
stop: function(event, ui) { ... }
});

How to tell a page to load a JS function based on variables being sent

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.

Categories