I'm making a blog type webpage, with a div that has a 'like' and 'dislike' button, and a rating above which is a mysql query of likes/(likes+dislikes). When a user clicks like or dislike, I want to add their vote to the db, and dynamically change the rating value without reloading the page. Here's a little snippet of the html, I have barely worked with javascript, so any help would be great.
<div class="narrow_right_container">
<?php
$popularity = get_popularity($row);
?>
<div class="yellow_bg">Rating: <?php echo $popularity . "%"; ?></div>
<div style="margin-left:2px;">
<div class="dislike">
<img src="ui_images/dislike.png"/>
<span>Dislike</span>
</div>
<div class="like">
<img src="ui_images/like.png" />
<span>Like</span>
</div>
</div>
</div>
You would not actually be changing a PHP value--once the page is output to the browser, consider PHP gone--you can't interact with it because it's on the server. Instead, think of interacting with the document that's in the browser.
The best way to do this is to make an ajax call to a server-side script. That server-side script can commit the like or dislike to the database, and then return the new rating, which you can insert in place of the old one using javascript.
You'll probably want to check out some tutorials on javascript and ajax, as it seems you have a more general need for a tutorial than for a specific problem. In other words, if you fill in your knowledge gaps on the general subject, you'll be able to solve your specific problem quite easily.
You will want to create some PHP code for handling the saving to the database on the Server side. You will POST the like / dislike value information to this server side script. If possible, I would use jQuery's AJAX helper to post data to the PHP page you just created.
Something like this:
$.ajax({
url: "whatever.php",
type: "POST",
data: {Like: true},
success: function(data){ /* update view */}
});
You will have to use ajax to accomplish this. Its not possible to alter PHP variables VIA javascript.
You will have to call an Ajax function that will handel the database work and after its done that, you will have to update the count using javascript. This will give the allusion that the count was updated while the count will also be updated in the database (from the Ajax)
Here is a great example of how you could accomplish this:
Example Code
Live Demo
$('.like').click(function(){
rate(1);
})
$('.dislike').click(function(){
rate(-1);
})
function rate(_val){
$.ajax({
url: 'ajax/rate.php?val='+_val,
success: function(data) {
alert('Rate was performed.');
$(".narrow_right_container").find(".yellow_bg").append("Rating: "+data+"%");
}
});
}
in rate.php:
if(isset($_GET['val'])){
$sql = "UPDATE.........."; //do an update to your rate table
echo get_popularity($row); //return rating to ajax
}
Related
So here I am posting my first PHP function that I am proud of but I just recently learned about AJAX and wanted to test it out. Unfortunately I can't get it to work.
My experience: PHP (3 weeks). CSS3, HTML, Basic Javascript.
My Problem: Getting AJAX to work. I want ajax to get my data from the php file which gets the votes from my test server (Xampp) database. So each time the user clicks on good or bad AJAX should display the new results without refreshing the page. The issue is however that: A) My if statements work by checking isset($_POST) which wont work anymore if I call by AJAX. B) Preventing refresh. C) Making AJAX update after every click. I know im nearly there, im just missing something and I dont know exactly what it is to be honest.
What I tried: Checked my database connection. Checked if my php code worked without ajax and it does perfectly fine (I am just displaying half of the functionality here, a lite version, for the sake of simplicity). Tried to change submit to button. Cache clearing. Jquery is in the head of my document and the path is correct. Watched tutorials and read the documentation but I am just not heading anywhere, probably due to lack of experience.
Edit: Sessions and everything php works fine. I my session start and database connection are included on the very top.
Summary: How do I fix this ajax so that it always updates my numbers?
Let me know if you want me to explain parts of my php code. Im willing to comment the parts if neccesary.
JQUERY / AJAX CODE
function vote() {
var request = $.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html'
});
request.done(function(vote_sum) {
$("#votes").html(vote_sum);
});
}
HTML CODE:
<div id='votes'></div>
<form id="good" action="" method="post">
<input type="submit" name="good" onclick="vote()" value="+">
</form>
<form id="bad" action="" method="post">
<input type="submit" name="bad" onclick="vote()" value="-">
</form>
In HTML you don't need <form>, you are doing it with AJAX, right?
<div id='votes'></div>
<button onclick="vote('good');">+</button>
<button onclick="vote('bad');">-</button>
In JavaScript, it is easier to use post rather than ajax function
function vote(gb) {
$.post("php/core/voting_system.php", { vote: gb }, function(vote_sum) {
$("#votes").html(vote_sum);
});
}
In PHP, extract the vote and use it as needed (add validation/sanitation):
$vote = $_POST['vote']; // either 'good', or 'bad'
// do what you need with it
TL;DR version:
You didn't include a data field inside your $.ajax call. Also, your script isn't checking which button was pressed.
The long version
When you're performing your $.ajax call, you fail to attach any data to the request. This can be done easily like so:
$.ajax({
method: 'POST',
dataType: 'json',
data: ...someJSONData...
});
Usually, you're going to want to pass JSON to anything, because it can contain complex object structures that you would usually want to communicate between the client and the server. You're clearly not in this example, but if you're trying to learn this stuff, it's better to start off the right way.
Both javascript and php make using the JSON format extremely easy: JS JSON.stringify() and JSON.parse(), PHP json_encode() and json_decode().
function vote(e) {
// e.target.id stores the id of the button that was clicked
var data = {vote: e.target.id}
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
... callbacks and other properties ...
});
}
document.getElementById("good").addEventListener("click", vote);
document.getElementById("bad").addEventListener("click", vote);
This would be a simple example of how you could solve your problem. If you did a simple var_dump in your php script after running the data through json_decode() you would get a nice associative array:
[
'data' => 'good',
]
I hope this illustrates how easy it is to pass data around in this format.
Also notice I defined the event handlers in the javascript. This is generally better, because you keep all your javascript in one place and it makes things cleaner and easier to debug.
Like Jay said you're not sending POST data through the AJAX. You also need to echo your results from PHP.
function vote(event) {
event.preventDefault();
$.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html',
data: 'bad='+$('input[name="bad"]').val()+'&good='+$('input[name="good"]').val(),
success: function(data){
var votes = $("#votes").val().empty();
$("#votes").html(data+votes);
}
]);
}
For one of my wordpress site php files, I have the following code:
<div class="tabs">
Items
</div>
<div class="section" id="tab1">
<?php get_template_part('page/tab1'); ?>
</div>
So, it will call the tab1.php file into the div id="tab1"section.
However, I want to make it so that the get_template_part is only executed or called when the Items tab is clicked.
What would be the jQuery to call or execute the get_template_part function?
EDIT:
So, what I am trying to achieve is similar to Ajax. Since the get_template_part function won't be called till the "Items"tab is clicked, the browser does not have to call unnecessary files and slow down the page.
Let me know if you think this is the best way to do it.
Thanks!
Though the idea behind is already illustrated by Raphael in his answer, I intervene to add some details.
the best way to use AJAX with Wordpress is to use its built-in way of handling it, and that by sending requests to wp-admin/admin-ajax.php( I know the “admin” part of the file name is a bit misleading. but all requests in the front-end (the viewing side) as well as the admin can be processed in admin-ajax.php, with a lot of benefits, especially for security. And for the server-side code php that will be executed, it should be placed in functions.php.
Your jQuery code will look something like:
$(document).ready(function() {
$('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'yourFunction', id: tab_id}),
success: function(data){
$('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
infunctions.php of your theme (or directly in your plugin file), add:
add_action('wp_ajax_yourFunction', 'yourFunction');
add_action('wp_ajax_nopriv_yourFunction', 'yourFunction');
and define in the same file yourFunction callback function like this:
function yourFunction() {
// get id
// your php code
die();
}
For the javascript part, take a look at ajax() and its shorthand get(). And for the best practices using AJAX with Wordpress, there are many tutorials on the web (I will be back to give one). Good luck
Edit:
As it is mentionned by Karl, you can use .load() instead of ajax(), It should be noted that .load() is just a wrapper for $.ajax(). It adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...) which internally calls .ajax().
But my original answer is on how to organize php code respecting Wordpress best practices.
You can't really call a PHP function from javascript because by the time the browser sees the page, the PHP has already executed (or in your case, not executed )
The only way for you to do what you want is to spin the PHP function off into a separate script and then call that file using AJAX. Have the script echo HTML, and then insert the HTML into the tab1 div in the AJAX callback.
I think the easiest solution for you would be to use the jQuery load() function. It is the easiest way to achieve what you describe. The only issue that when someone clicks the header, there will be a delay to get the subitems as they do not exist yet (which would be the case for any situation where you delay the load.
HTML:
<div class="tabs">
Items
</div>
<div class="section" id="tab1"></div>
JS:
$(function () {
//wait for the page to finish loading
$('#items_id').click (function (e){
//watch for the items header to be clicked
e.preventDefault();
//prevent it from opening a link
$('#tab1').load('tab1.php');
//load the tab1.php file, or whatever file INTO the div
});
})
On my page I have a search result that contains a list with users where each is followed by an "addfriend" button. Each row contains a username and userID. Meanwhile the ID of the user that requested the searchresult is stored in a Session variable.
When the addfriend-botton is clicked the following 2 things should happen:
Store the userID and $_SESSION['userID'] is a MySQL table which describes the relationship.
Do NOT refresh the page (this the core of my problem) but stay focussed and change the state of the button to e.g. "friend request send". I'm thinking of GetElementByID().style method.
I was thinking of this:
<a href="#" onClick="addFriend('<? echo $_SESSION['userID'];?>','<? echo $rij['userID']; ?>')">
which calls the javascript function addfriend
I was hoping to catch the two ID's like this:
<script>
function addfriend(id1, id2)
{
//server side php code where I use value of
//the client-side javascript variables: +id1+ and +id2+ .
}
</script>
Is this at all possible or I'm I thinking the wrong way? Any suggetions on how to accomplish this?
You are in the right way, inside your addFriend() function, you can call one php file (via AJAX) and send the IDS without refresh the page. I think better you work with Jquery in this case, something like this:
<script>
function addfriend(id1, id2)
{
$.ajax({
type: 'POST',
url: 'yourPHPfile.php',
data: { your_id_1:id1, your_id_2:id2 },
success: function(data){
if(data){
alert('Done!');
}
},
dataType: 'text'
});
}
</script>
And in your PHP File you can do this:
<?php
//receive Ids
$id1 = $_POST['your_id_1'];
$id2 = $_POST['your_id_2'];
//do something here
echo "OK!";
<?
to do this work you need download and add the jQuery plugin in your page, rather into head tag
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
Good work and don't give up! (:
You can do this using AJAX (asynchronous JavaScript and XML), which is really just a fancy term for "sending stuff to a server with JavaScript and getting a response back, without reloading the page". There's nothing special about AJAX; it just involves using plain old JavaScript to send an HTTP request.
Check out jQuery, a JavaScript library that handles most of the technical stuff for you. Specifically, look at its post() function, which allows you to send data to a PHP script using the $_POST system variable. There are lots of clear examples on that page.
Note that you don't need jQuery to use AJAX; jQuery is just a library that makes things easier. If you really want to learn how the JavaScript side of AJAX works, try following one of the many tutorials out there, such as Mozilla's or this one.
AJAX is the answer you're looking for.
It sounds like you already have a basic understanding of this, but to clarify, Javascript executes on the client side, and PHP executes on the server side. So you would have to make a call back to your server in order to interact with PHP/MySQL.
The purpose of AJAX is to do this without requiring a page refresh.
hi i am a new programer
i want to replace the content of current php page from another php page using ajax without refreshing page.
the content to be replaced is in div's.
both pages (current and another) has same div's
HTML Div's are:
<div class="category-container">
<div class="category-image"></div>
<div class="category-desc">#<p>text</p></div>
<div class="rating5" >Editors' rating: </div>
<div class="category-download-btn">Download</div>
<div class="category-buy-btn">Buy</div>
</div>
can anyone tell me how i can do it. it will be a great help.
also can you provide me ajax code not jquery.
thanks.
Have a look at jQuery's load, the section on loading page fragments:
The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted.
To get the div content on another page into an analogous div on the current page, use something like:
$('#content').load('other-page.php #content');
// ^ target div ^ same div on the other page
this is usual jquery.ajax call
function getVotes(id){
$.ajax({
type: 'get',
url: 'ay/templates/backend/_votes_partial.tpl.php',
data: 'charity_id=' + id,
success: function(data) {
$('#shadow').fadeIn('slow');
$('#popupContact').fadeIn('slow');
$('#content').html(data);
}
});
}
the simplest way would be:
$.get("pageurl",function(data){
$("yourdiv").html(data);
});
use jquery.ajax its easy... old way of making ajax calls was too much complicated, jquery made it easy,
you need to install jquery library,include it in ur head tag and go thorough following link for clear understanding, its much easy
Jquery.ajax
You're correct in assuming jquery is the way to go. I'm far from an expert, but this should help. The docs are straightforward.
Generally, jQuery follows the find something then do something approach.
Find something ---> watch for some action on some element (like changing a select box or clicking a link)
Do something ---> make an ajax call to the php page you want replace the current div with the new div
The jQuery documentation is here with an example at the bottom that shows exactly what you're trying to do http://api.jquery.com/jQuery.post/
Some other helpful jQuery commands for this task could be...
http://api.jquery.com/appendTo/
http://api.jquery.com/remove/
http://api.jquery.com/clone/
Hope this helps.
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) { ... }
});