Improving this AJAX function to update a "like this" link - php

I asked a question about this but the post degenerated into confusion which lost the gist of the problem. Basically I'm trying to set up ajax so that a "like" or "unlike" link updates a database and shows the new status without having to refresh the page.
So I have a "view.php" page with links which are produced by a PHP loop. They look like this:
<div class="tools">
like
</div>
<div class="tools">
unlike
</div>
Note that each link has two classes: firstly a "like" class, and then either a "do_like" class or a "do_unlike" class, according to whether it's a link to "like" or a link to "unlike" respectively. (Originally I only had the "do_like" and "do_unlike" classes, which I was using to transform the link via css into a rollover-type image/icon, but I added the "like" class as well, for the ajax - see below.)
When a user clicks one of these links, the receiving processor.php script takes the variable-value pairs from the query string, and uses them to update a database, and then build a new form of the link, which it echoes out. The new form of the link is such that a "like this" link turns into an "unlike this" link, and vice-versa. So for the first "like" link above, the database returns:
processor.php?c=cars&p=2&s=d&u=d&pid=999999990
It's the "u" variable in the query string which determines whether or not the processor.php page will either insert the data into the database in the case of a "like" (u=i), or delete the data from the database in the case of an "unlike" (u=d). (I'm using prepared PDO statements for the database inserts/deletions.)
I'm using jquery/ajax to insert this newly built link in place of the one that was clicked, without having to refresh the page.
To do this, in the "view.php" page I included jquery.js and used the following javascript function:
<script type="text/javascript">
$(function() {
$("a.like").click(function(e){
e.preventDefault();
var link = $(this);
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
});
});
});
</script>
The problem is, although this function sends the data to the processing script OK, and changes the link's href attribute in the page without a page refresh (I can see it's doing this OK by copying the link in the browser after a click), it doesn't change the link's text, class or title. So I as it is, I have to refresh the page to see any visual cues that the link has in fact changed (I might as well just use a header redirection in the processor.php page).
How can I modify the function (or change it) so that it also replaces the link's text, class and title? So that (for example, transforming a "like" link):
like
becomes:
unlike
?

You need to change the class and the title then also:
[...]
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
link.toggleClass('do_like do_unlike');
link..attr('title', 'change title here');
});

Use an if condition to check the current state and update the attributes.
$(function () {
$("a.like").click(function (e) {
e.preventDefault();
var link = $(this);
var alreadyLiked = (link.text() == "UnLike") ? true : false;
$.get(link.attr('href'), function (data) {
link.attr('href', data);
if (alreadyLiked) {
link.removeClass("do_unlike").addClass("do_like").text("Like").attr("title", "Click to LIKE this photo");
}
else {
link.removeClass("do_like").addClass("do_unlike").text("UnLike").attr("title", "Click to UN LIKE this photo");
}
alreadyLiked = !alreadyLiked;
});
});
});
This code will work. Tested. Assuming every time the get request gives you the url (for deleting/inserting ) correctly.

This is based on both Shyju's and Pitchinnate's responses (so thanks to both!), and it works a treat using the css rollover link-transformation method (I also included a fade effect):
<script type="text/javascript">
$(function() {
$("a.like").click(function(e){
e.preventDefault();
var link = $(this);
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
link.toggleClass('do_like do_unlike');
var titleState=(link.attr("title") == "Click to LIKE this photo") ? "no" : "yes";
if(titleState=="yes")
{
link.attr('title', 'Click to LIKE this photo');
}
else
{
link.attr('title', 'Click to UNLIKE this photo');
}
});
$(this).parents('div.tools').fadeOut(1000);
$(this).parents('div.tools').fadeIn('slow');
});
});
</script>

Related

How to prevent reloading of a page after clicking on a hyperlink but redirect to that page and work out the necessary code written over there?

My question may sound confusing but actually it's not. Let me clear you the things. The scenario is I've following HTML code:
/*This is the hyperlink I've given for example here. Many such hyperlinks may present on a webpage representing different question ids' */
<a delhref="http://localhost/eprime/entprm/web/control/modules/questions/manage_question_issue.php?op=fixed&question_id=21679" title="Fixed" href="#fixedPopContent" class="fixed" data-q_id="21679" id="fix_21679">Fixed</a>
/*Following is the HTML code for jQuery Colorbox pop-up. This code has kept hidden initially.*/
<div class="hidden">
<div id="fixedPopContent" class="c-popup">
<h2 class="c-popup-header">Question Issue Fix</h2>
<div class="c-content">
<h3>Is question reported issue fixed?</h3>
Yes
No
</div>
</div>
</div>
Now upon clicking on this hyperlink I'm showing a pop-up(I've used jQUery Colorbox pop-up here. It's ok even if you are not familiar with this library.) On this pop-up there are two buttons Yes and No. Actually these are not buttons, these are hyperlinks but showing as a buttons using CSS. Now my issue is when user clicks on hyperlink 'Yes' the page is redirecting to the href attribute value and the page reloads.
Actually I want to get to the page mentioned in href attribute but the page should not get reload or refresh. How to achieve this? Following is the jQuery code for colorbox pop-up as well as for Yes and No buttons present on this pop-up. I've tried this much but it didn't work for me. The page is getting redirected and reloaded.
My code is as follows:
$(document).ready(function() {
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$('#fixedPop_url').attr('href', action_url1);
$(".fixed").colorbox({inline:true, width:666});
$("#fixedPop_url").click(function(event) {
event.preventDefault();
$("#fix_"+qid).hide();
$("#notfix_"+qid).show();
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
});
So you need to load the page at the url but not navigate to it.
You can use .load() .
So in your case, lets say that your pop container div class is .popup, and the div where you want to load the urls content has an id say #container.
$(".popup a").on('click', function(e){
e.preventDefault();
var url = $(this).attr('delhref');
$("#container").load(url);
});
Few things to keep in mind,
This will mostly not work for urls pointing to any other domain. (Same Origin Policy)
Any content loaded with this function (.load()) shall be inserted within the container and all the incomming scripts if any shall be executed.
You can do that with history.js. Here is an example;
HTML:
Delete
Update
<div id="content"></div>
JS:
var History = window.History;
if (!History.enabled) {
return false;
}
History.Adapter.bind(window, 'statechange', function() {
var State = History.getState();
$('#content').load(State.url);
});
$('body').on('click', 'a', function(e) {
var urlPath = $(this).attr('href');
var Title = $(this).text();
History.pushState(null, Title, urlPath);
return false;
});
You can see code here: jsfiddle code
You can see demo here: jsfiddle demo
Note: Urls in example cannot be found. You need to update it according to your needs. This simply, loads content in href without refreshing your page.

PHP AJAX JQUERY load page

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>

JS: Changing this function to handle a link click

Following the example here Very Simple jQuery and PHP Ajax Request – Ready to use code
I've been successful in creating a drop down list that passes the value to an external PHP script and returns the HTML output back to a "div" on the same page and it works great.
What I want to do now is post values when I click on link instead of building a drop down list. So ...if I created this link:
Route Number 2
I want "2" passed to that external PHP script and the content changed on the " div " as it currently works with the dropdown. I don't know how to change the javascript to handle this or what "foo.php" really needs to be.
Here's the current javascript from that example:
<script type="text/javascript">
$(document).ready(function() {
$('#route_number').click(function() {
routenumber = $('#route_number').val();
$.post('api.php', { route_number : routenumber }, function(res) {
$("#mainlayer").html(res);
});
});
});
</script>
And here's what the dropdown portion of the HTML looks like:
<select name="route_number" id="route_number">
<option value="notchosen">Please Choose A Route</option>
<option value="2">Riverfront</option>
<option value="11">Magazine</option>
<option value="16">Claiborne</option>
</select>
<div id="mainlayer">
</div>
So, to be clear, instead of a dropdown that passes values, I want to create links that accomplish the same result.
Thanks in advance,
dan -
Create a class, capture its (meaning whatever link you clicked on) value, then post.
<a class="RouteNumber" href="foo.php?route_number=2">Route Number 2</a>
$(function(){
$('a.RouteNumber').on('click',function(event){
// prevent the browser's default action for clicking on a link
event.preventDefault();
// break href attribute into array, then parse desired value as int
var routenumber = $(this).attr('href').split('='),
rtnum = parseInt(routenumber[1]);
$.post('api.php',{route_number:rtnum},function(res){
$("#mainlayer").html(res);
});
});
});
If you don't need to parse the integer out of it (if a string is good enough), you don't need that second variable. You can just use routenumber[1] in the post data.
Just a heads up, I modified the jQuery to use the .on() syntax. .click() is shorthand for it, but I like using .on() just because it allows for less potential codewriting if you want to do more (like mouseenter/mouseleave, for example) because you can combine them into a single codeset.
I had hoped simply fixing #LifeInTheGrey's example would've sufficed, but there are some things I would've done differently that probably need some explaining.
Your HTML could look something like this:
<a class="route" href="foo.php?route_number=2" data-route="2">Route Number 2</a>
The JavaScript would look something like this:
$(function() {
var fill_div_with_response = function(res) {
$("#mainlayer").html(res);
};
var handle_error = function(res) {
alert('something went wrong!');
};
$(document.body).on('click', '.route', function(event) {
// prevent the browser's default action for clicking on a link
event.preventDefault();
// grab route number from data attribute
var route = $(this).data('route');
// make that post request
$.post('api.php', {route_number: route})
// handle the response
.done(fill_div_with_response)
// handle errors
.fail(handle_error);
});
});
The example uses delegated events. They're cheap to initialize and consume the least amount of memory.
The example handles errors. Most answers to questions like these neglect that. errors happen. Always. Make people aware of that. Surely throwing an alert() is not the thing you want to be doing, but it's still better than simply ignoring errors completely.
The example uses Deferreds (Promises) rather than callbacks, as this usually makes code much cleaner.
We're defining the callbacks fill_div_with_response() and handle_error() at the root closure to prevent redefining them on the next click. There's no need to feed the garbage collector.
The data attribute poses the optimal alternative to <option value="123"> in the way that it prevents you from having to parse the href attribute to extract that number from a string.
since you want to make a menu, I would modify your markup
<ul name="route_number" id="route_number">
<li value="2">Riverfront</li>
<li value="11">Magazine</li>
<li value="16">Claiborne</li>
</ul>
then simply process that list:
$('#route_number').find('li').click(function () {
var routenumber = $(this).attr('value');
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
EDIT1: As an improvement (as you seem to be pretty new to this stuff) you could use the data with altered markup as such:
<ul name="route_number" id="route_number">
<li data-routenumber="2">Riverfront</li>
<li data-routenumber="11">Magazine</li>
<li data-routenumber="16">Claiborne</li>
</ul>
Then the code would be:
$('#route_number').find('li').click(function () {// add click event manager to each li
var routenumber = $(this).data('routenumber');// get routenumber of clicked
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
Alternate code using .on() form
$('#route_number').on('click, 'li', function () {//click event manager for ul/li
var routenumber = $(this).data('routenumber');// get routenumber of clicked
$.post('api.php', {
route_number: routenumber
}, function (res) {
$("#mainlayer").html(res);
});
});
Note that this last form binds to the #route_number element so you could add more menu options during processing and they would still work. This is also better than attachment to the document as it is a more focused approach to the event attachment.
My understanding of your question is that the functionality you have is fine, and you just need to change the look to a piece of text from a dropdown. If so, good news! You can keep (almost) the same JavaScript.
Right now, your JavaScript is getting the value of your select box, sending it via AJAX, and using the returned value. The only change you need is to get the 'value' of the text clicked.
You don't want to use a link, since that's designed to take the user someplace. Instead you can use a span and format it to look like a link, or even a button if you want that kind of look.
You will also need to change $('#route_number').val();, probably to something passed by the click event. For example:
<span id="route1" class="routeSpan" onclick="sendVal(1)">Route 1 Name</span>
<span id="route2" class="routeSpan" onclick="sendVal(2)">Route 2 Name</span>
And your JavaScript:
function sendVal(routeVal) {
$.post('api.php',{route_number:routeVal},function(res){
$("#mainlayer").html(res);
});
}

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

Categories