I've searched the database but haven't really found anything that would answer my question. I'm new with Ajax so I'll try to describe it as good as I can.
I am trying to build a rating system for images with only two options: Accept/Reject.
I have a paginated gallery with 10k images and they all need to be rated (for the competition). There's a special system for rating (accepting/rejecting) and then there's this overview gallery. Every thumbnail that has already been rated should display a clickable text/image, for example "Accepted", depending on the database value. You'd be then able to click on this text/image and it would change to "Rejected" and the mysql database entry would also change at the same time.
Left: initial state of the "Accepted" image. /
Right: changed value of the button (text or image) and updated database.
(source: shrani.si)
So what would be the easiest way to do this? There are hundred images on each paginated site with these buttons below, and you have to be able to change the value back and forth (many times, something like editable star rating system with only two stars, heh).
As you said ajax should be used and I advice you to use jquery functions
Then viewing the images should be simple for you when you loop through the database result
while looping you should test the value of the image is it accpted or rejected in order to link it with the associate JS function that I will talk about later and in that function an ajax request should be made to update that row
function change_status_image(id,status,clicked)
{
$.post("update.php",{image_id:id,image_status:status},function(data){
//your callback to do something like update the value of the button
});
}
This will make an ajax request and sends two variables image_id and image_status in the update.php you should use something like this
$q = mysql_query("UPDATE tbl_name SET column_name = '".mysql_real_escape_string($_POST['image_status'])."' WHERE image_id = '".mysql_real_escape_string($_POST['image_id'])."' ";
about the function make a div or button and link the onclick att to change_status_image
for example
<img onclick="change_status_image(img_id,reverse_current_status)" >
Use jQuery. You need two scripts:
/rate.php
/rate.js
rate.php looks like this:
<?php
// If there are values in $_POST['edits'], then this is an ajax call.
// Otherwise just display the gallery
if ((!empty($_POST['edits']) && (count($_POST['edits']))) {
foreach ($_POST['edits'] as $edit) {
alter_image($edit); // some function to update the database
}
echo "success";
exit;
}
$images = get_images(); // Some function to get the images from the database
?>
<?php foreach ($images as $image): ?>
<div class="gallery-image">
<img src="<?php print $image -> src ?>" />
<button>Accept</button>
<button>Reject</button>
<input name="id" value="<?php print $image -> id ?>"/>
</div>
<?php endforeach; ?>
rate.js looks like this:
$(function() {
// attach click event handler to buttons
$('.gallery-image').on('click', 'button', function() {
var $this = $(this),
ajaxSettings = {
url: '',
type: 'post',
data: {
edits: [
{
id: $this.parent().find('input[name=id]').val(),
action: $this.html()
}
]
},
success: function(response) {
if (response === 'success') {
// something to indicate success
} else {
// something to indicate error
}
}
}
$.ajax(ajaxSettings);
})
})
Related
I'm currently working on a project in school and I'm trying to use php and sql to create a web front end with a database back end. I have tried to research this thoroughly, but I have had no success. I am trying to click on a link and run an SQL query based on the ID of the link that was clicked.
Code is pastebin'd below:
https://pastebin.com/sH6DXtQU
I believe it is something to do with;
$_Post or $_Get
So essentially I'm trying to click on one of the actors names ad it display all the films they have been in, as you can see at the bottom of the page i have made a very basic attempt at showing the films using actorID form (1-6). If possible without any jQuery but if it is necessary i will use it. Any help will be greatly appreciated.
If you don't want to refresh the page you need an XHR request, AJAX request in Jquery. If you don't want to use Jquery it's fine , there is a way to do it in vanilla Javascript but it's way harder to understand.
const req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', false);
req.send(null);
if (req.status === 200) {
console.log("Received: %s", req.responseText);
} else {
console.log("Error: %d (%s)", req.status, req.statusText);
}
for a GET request. I suggest you look at the mozilla website for more documentation
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
So your having a anchor link like the following, on click of that you want all the data of the films they have acted
View Page
<!-- I am assuming that your having $row as actor details, so below you store the actor id in a attribute data-actorid and once the user clicks on the link make sure you call the event ONCLICK -->
<a class="actor_movies" href="#" data-actorid = <?php echo $row['actorid']; ?>>
<?php echo $row['actor_name']; ?>
</a>
/* I am assuming you have jQuery running. As the code I am writing needs jQuery Library */
<script type="javascript">
$(.actor_movies).on('click', function(){
actor_id = $(this).attr('data-actorid');
$.ajax({
'url' : 'actor_movies.php'
'type' : 'POST',
'dataType' : 'JSON',
'data' : {actor_id:actor_id},
success : function(retObj){
/* retObj will have the json encoded code which you can loop and do whatever you want here */
$.each();/* Even you can use for loop as per your convenience. */
}
});
});
</script>
actor_movies.php
/* Include your db connection file */
include_once 'db_connect.php';
/* Check if the connection type is of POST */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
/* filter_input get your input from specified HTTP request and even you can add filter validation and other things to it */
$actor_id = filter_input(INPUT_POST, 'actor_id', FILTER_VALIDATE_INT);
$actor_movies_query = mysqli_query('SELECT * FROM movies WHER actor_id = '.$actor_id);
$actor_movies = array();
if(mysqli_num_rows($actor_movies_query) > 0){
while($actor_movie = mysqli_fetch_assoc($actor_movies_query)){
$actor_movies[] = $actor_movie;
}
}
header('Content-Type: application/json');
echo json_encode(['actor_movies' => $actor_movies]);
}
I have a div on my page '.php'
<div id="force_id"></div>
This prints an id for each product on the page. Ex: 126500
How do I assign this value of the other PHP variable (not click, on load for example)
I use it here :
$limit = ?????? (Value should be the id value here. For example 126500)
$plans = mysql_fetch_array(mysql_query("select * from motors WHERE prod_id = '$limit'"));
Thank you in advance ...
If you are looking for something on-load then you will need to use Javascript with some sort of Ajax call.
Your javascript would need to grab the id and then pass that to .php as a POST or GET variable.
However, it would probably be better for you to pass the ID with the page request. So your link to .php would look like this:
<a href='page.php?id=126500'>Link</a>
Obviously you can auto generate these. Then in .php you just get the value from GET:
$limit = $_GET['id']
Then you can use it in your SQL query (you should look at PDO rather than mysql_query to protect yourself from SQL injection hacks).
Some more detail on the GET option.
Your initial HTML for the menu choice of products to look at would look like this:
<h1>Select the Product you want to see</h1>
<ul>
<?php
$result = /* SELECT MY PRODUCT CODES */
foreach($result AS $row){
echo "<li><a href='product.php?id=".$row['id']."'>Product ".$row['name']."</a></li>";
}
?>
</ul>
Then your product.php file would have this:
if(isset($_GET['id'])){
$limit=$_GET['id'];
$plans= /* SELECT FROM MOTORS USING $limit */
foreach($plans AS $row){
echo 'Product name:'.$row['name'];
echo "<img src='".$row['img_path']."' />";
...
}
}else{
echo 'Sorry, unrecognised product';
}
You should do further validation on $_GET['id']; for example check that it is a number and within a range that you would expect for your product_id's
More detail on the POST option using Javascript & JQuery.
If you have a specific reason for wanting to do POST, or for some reason you only want to publish the ID code on the one page then you could do it like this:
In your HTML I would use a data attribute in a div:
<div id='product' data-id='12650'></div>
In Javascript (I've assumed JQuery but the approach would be the same with other libraries) you would add to your 'onload' function (i.e. do this after the page has loaded):
$('#product').each(function(){
var id=$(this).data('id');
$.ajax({
type: 'POST',
url: 'product_content.php',
data: {'id':id},
success: function(msg){
$(this).html(msg);
},
error: function(msg, status,err){
$(this).html("Product not Found");
}
});
});
Finally you need a page to respond to the Ajax call product_content.php :
$limit=$_POST['id'];
/* DO SOME VALIDATION ON $limit HERE OR USE PDO AS PROTECTION */
$plans= /* SELECT FROM MOTORS USING $limit*/
foreach($plans AS $row){
echo 'Product name:'.$row['name'];
echo "<img src='".$row['img_path']."' />";
...
}
I should point out I've not tested this code, so keep an eye out for typo's if you copy it directly.
If you're using form, you can put the div's value inside an input[hidden] inside the form. Something like this:
$('#your_form').on('submit', function(){
your_div = $('#your_div').attr('id');
$('#hidden_field_used_on_form').val(your_div);
return true;
})
I am developing a plugin for WordPress system for some custom media review purpose. I have setup most of the things but few more.
Currently I stuck on the part to update database on click ( onlink ) to update table value using AJAX. Refer below code. It has while loop and I want to use AJAX within the loop to update media status. I am not sure is this the right way or there is another simple way to make it happen. Any suggestion would be appreciated.
Code:
<?php
$media_item = mysql_query($media_sql);
if ($media_item) {
echo '<ul class="rm-media-list">';
while ($media = mysql_fetch_array($media_item)) {
$m_uid = $media['user_id'];
$m_uname = $media['user_login'];
$media_class = new q2a_review_media;
$thumb_path = $media_class->rm_thumbnail_url($pid,$m_uid);
$media_url = $media_class->rm_media_url($pid,$m_uid);
$mediaid = $media['id'];
$image_name = $media['image_name'];
echo '<li>';
echo '<span class="rm-media-user">',$m_uname,'</span>';
echo '<a href="'.$media_url.$image_name.'" rel="lightbox['.$pid.']" title="Post: '.$pid.' | '.$ptitle.' | Image: '.$image_name.' | by: '.$m_uname.' " ><img src="'.$thumb_path.$image_name.'" alt="'.$media['image_name'].'" width="56" class="rm-thumbs-list" /></a>';
echo '<span class="rm-action-links"><a href="#" id="approve-'.$mediaid.'" >Approve</a> | <a href="#" id="delete-'.$mediaid.'" >Delete</a></span>';
echo '</li>';
}
} else {
echo 'No media found';
}
echo '</ul>';
?>
Database Table:
My Plugin Page Output
In above image you can see link called Approve | Delete Here I want to make interaction with database using ajax. When admin click on Approve it will update value from 0 to 1 in status column and when Delete than it will delete the row and images from the directory. Hope I posted enough data to understand. If not please let me know I will try to add some more information.
Million thanks.... :)
Firstly, your statement echo '</ul>'; needs to be in the if part of the loop.
Your AJAX code doesn't have to be inside the while loop. Here is how you can manipulate your code to make an AJAX request.
Let's first modify your <a> tag slightly:
Approve
This change allows you to have a group of buttons with class="approve-button" and id="the id of the item you want to approve"
Now, we can use some JavaScript to make an AJAX request. For convenience, I will use jQuery to make this request:
<script type="text/javascript">
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('.approve-button').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
Make an AJAX request
$.ajax({
url: "some-page.php", //This is the page where you will handle your SQL insert
type: "post",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
</script>
As far as some-page.php goes, this is what you need to do:
Have your SQL statements that will make the changes to he database
To access the ID attached to the approve button that was clicked, you can use the $_POST array since the AJAX request was of type "post". Specifically, this is where your ID is stored: $_POST['id']
FYI: To import jQuery on your page, you can use:
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
I have a comics website, Hitting Trees with Sticks, that allows a user to get next, previous, or random comic id by pressing next or simply pressing arrow keys.
Since images are stored in a database, the only way for me cycle through these images on the client side was to store them in a javascript array, and store the php $imgid in a javascript variable as imgIndex. Then I could alter that index on the client side when they press keyboard keys.
When the user presses a key, I'm using pushstate to alter the imgid in the URL, but that's not actually updating the server side $imgid. I need to update the server side $imgid because I'm associating a liking function with each specific ID... but currently, the total likes associated with an img ID won't refresh/update when I press a key to get a new image.
My solution was to not only use the PushState to update the URL, but when a key is pressed, I use a $.post, and send the updated imgIndex to the php script.
Here are snippets:
KeyInput.php: This is the client-side javascript:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($site)) ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
$(document).keydown(function (e) {
var key = e.which;
var rightarrow = 39;
var leftarrow = 37;
var random = 82;
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
window.history.pushState(null, null, '.?action=viewimage&site=comics&id=' + imgIndex);
$.post('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
//alert(data);
}
);
}
viewimage.php This is the file that originally gets the $imgid, then it calls the keyInput.php script to accept key input... that alters the javascript imgid. For testing purposes, I've tried using $.post and $.get AJAX to send the updated imgid, as you can see below, that's $newID = $_POST['_newImgId];. When I echo out $newID, it says it's not defined.
<?php
/*
Controls display of comic on the viewComic template
*/
include 'include/header.php';
global $site, $imgid;
$cat = (isset($_GET['cat']) ? ($_GET['cat']) : null);
$site = (isset($_GET['site']) ? ($_GET['site']) : null);
$title = (isset($_GET['title']) ? ($_GET['title']) : null);
$imgid = $_GET['id'];
include './scripts/keyinput.php';
$newID = $_POST['_newImgId];
echo $newID; //THIS SHOULD ECHO THE UPDATED ID, but it says it is not defined
Any thoughts?
Thanks!
I think the problem with your code is that you are using your Ajax code after the page has already loaded, while trying to change the $_get variables for the initial page load. AFAIK, you need to update the entire page for the "Facebook like" button to change it's ID. Another option would be to use an Iframe. From what I can see, the button's data-href attributes always leads to http://hittingtreeswithsticks.com/ - and that can only be changed by reloading the page using a different attribute.
If you don't mind loading a page for each picture, this can work out for you:
<!-- This is the Like button code -->
<div [...] data-href="http://www.hittingtreeswithsticks.com/<?php echo $_get['id']; ?>"></div>
and the address for this page would be: http://www.hittingtreeswithsticks.com/?id=PAGE_ID
EDIT
Using AJAX, you are calling for data from the backend to be used in the client side, without having to reload the entire page. This data can then be used to alter the code in the client side. In your code, the data is being sent back to you but you are not using it at all, that's why it doesn't work:
$.get('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
// This is where you should make use of the data received
}
);
EDIT #2
If you want to dynamically change the Like button's url, take a look at this answer.
Here is a fiddle of the working example:
http://jsfiddle.net/TkFma/4/
The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston"
success: function(data){
alert('done');
});