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>
Related
I will try to word this as clearly as possible.
So I have a link which upon a click will submit some data to my database.
<a href='' id='likePost' ><i class='fa fa-thumbs-up'></i></a>
So when this link is clicked, I would want some data that is relevant to the "post" sent to the PHP file which will then process to the MySQL database.
The current jQuery I have is as follows:
<script type="text/javascript">// <![CDATA[
$(function(){
$("#likePost").click(function(event){
$.ajax({
type:"POST",
url:"functions/likePost.php",
data:"post=<?= $post['unique_post_id'] ?>",
success:function(html){
alert("Liked post = success")
}
});
});
// ]]></script>
One thing at this stage that i'd like to point out is each post has a unique ID which can be called upon with $post['unique_post_id'].
My PHP file code is:
<?php
session_start();
require_once("../global.php");
$unique = $_POST['post'];
/* FIND USER ID OF TARGET (OWNER OF POST) */
$findID = $connection->query("SELECT userid FROM posts WHERE unique_post_id='{$unique}'");
$id = $findID->fetch_assoc();
/* INSERT LIKE INTO DB */
$time = time();
$qry = $connection->query("INSERT INTO posts_likes (id, from_user_id, target_user_id, unique_post_id, time) VALUES (NULL, '{$_SESSION['SESS_MEMBER_ID']}','{$id}','{$unique}', '{$time}')");
?>
However none of this works. I'm pretty sure that there's something wrong with the AJAX code. Any idea's how I can achieve this?
Just as a quick summary, what I need is:
CLICK --> TRIGGER AJAX CODE? --> LOAD PHP FILE WITH ADDITIONAL DATA ATTACHED (unique post id) --> PHP FILE INSERTS QUERY.
Hope I've been as clear as possible, thanks in advance :)
(If I seem nooby, my age might be a reason: 15)
You should open up your browser console and see what errors are being thrown.
Base off of what script I've read your data definition looks wrong, I believe it wants an object like
$.ajax({
data: { post : '23', id: '32' }
});
And you should prevent the default click from reloading your page by using no href attribute or href="#" or by using
$('element').click(function(e){
e.preventDefault();
}
I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.
This is a tough one to explain...
I'm developing a restaurant system where the user add the dishes available to sell, but the user has to have an option to edit/delete AFTER the dish was registered.
So what i thought was: k, gonna make a table fetching the data from the DB and in the last column put some options like edit/delete... Here is the code for better understanding:
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img src="img/icons/16/delete.png" alt="delete" height="16" width="16">'.'</td>';
echo '</tr>';
}
Like you've saw the delete option has already there (with no function/action yet) Here is the thing... I could put a link to a file in href="delete.php? but when a user clicks on this link will lead them to the delete.php page, leaving the administration page... I would like that when the user clicks the delete img, worked as/similar AJAX. I don't want the user exit the page....
Sorry for bad english (not my mothertongue), if you guys want more details just ask.
Ps: New PHP Programmer
Thanks in advance.
use javascript or jQuery to do an ajax request to delete.php with the id of the row you want to delete. I often put the id in the <tr> like echo "<tr data-id='{$row['id']}'>" and my jQuery would look something like this
$(".delete").on('click', function() {
var id= $(this).parents('tr').data('id');
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function(data, textStatus, jqXHR) {
// do something with the data returned. I usually output "success" from my
// delete.php and then check for data.indexOf('success') != -1
$("tr[data-id="+id+"]").remove();
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Error: "+jqXHR+" "+textStatus+" "+errorThrown);
}
});
});
on my delete.php page i check that $_POST['id'] is not empty before continuing. If you use $_REQUEST['id'] it will also work with a direct link to delete.php?id=999
You can call Delete.php using AJAX, so the request is executed without leaving the page.
The advantage of making an actual link to the delete page, is that it also works without Ajax/Javascript. So you can start by building a plain delete page, and add the Ajax later.
First, you should also print a record_id because just deleting based on the name is a very bad idea where encoding will hunt you down.
Having said that, here is what I would do using jQuery:
//PHP
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img class="delete-btn" src="img/icons/16/delete.png" alt="delete" height="16" width="16" data-order-id="$row['id']">'.'</td>';
echo '</tr>';
}
//JQUERY
$(document).ready(function(){
$(".delete-btn").click(function(){
$.post("/delete.php", {order_id: $(this).attr("data-order-id")}, function(){
$(this).closest("tr").remove();
});
});
});
I have a question about jQuery UI Dialog boxes and showing dynamic content from a database.
So I got a webapplication where I also need to make a admin module to manage all users and other information. I created a page that shows all users in a list, in every row I also made an edit button. I wanted to make it so that when you press on a users' edit button, a dialog box opens and shows all the user information and stuff in the dialog box.
So my question is, what is the best way to do this? I was thinking about making a PHP page where I execute the MySQL Query and show that in the dialog box, but I am sure there are better ways..
EDIT: Here is the code for the page as it is right now. I added a small placeholder dialogbox that I used for testing purposes.
Javascript:
script type="text/javascript">
jQuery(document).ready( function(){
jQuery(".edit-button").click( showDialog );
//variable to reference window
$myWindow = jQuery('#myDiv');
//instantiate the dialog
$myWindow.dialog({ height: 600,
width: 800,
modal: true,
position: 'center',
autoOpen:false,
title:'Bewerk therapeut',
overlay: { opacity: 0.5, background: 'black'}
});
}
);
//function to show dialog
var showDialog = function() {
$myWindow.show();
//open the dialog
$myWindow.dialog("open");
}
var closeDialog = function() {
$myWindow.dialog("close");
}
PHP:
<?php
//LEFT OUTER JOIN Vragen ON Vragen.bsn_nummer = Gebruikers.bsn_nummer
include_once 'classes/class.mysql.php';
$db = new Mysql();
$dbUsers = new Mysql();
$db->Query("SELECT * FROM USERS_users ORDER BY username ASC");
$db->MoveFirst();
echo "<table>";
echo "<tr><th> </th><th> </th><th>BSN Nummer</th><th>Gebruikersnaam</th> <th>Voornaam</th><th>Achternaam</th></tr>";
while(! $db->EndOfSeek()) {
$row = $db->Row();
$dbUsers->Query("SELECT * FROM Gebruikers WHERE user_idnr = '{$row->user_idnr}'");
$rowUser = $dbUsers->Row();
echo "<tr><td><a class='del-button' href='#'><img src='afbeeldingen/edit-delete.png' /></a></td>
<td><a class='edit-button' href='#'><img src='afbeeldingen/edit.png' /></a> </td>
<td>".#$rowUser->bsn_nummer."</td>
<td>".#$row->username."</td>
<td>".#$rowUser->voornaam."</td>
<td>".#$rowUser->achternaam."</td></tr>";
}
echo "</table>";
?>
<div id="myDiv" style="display: none">
<p>Gebruiker bewerken</p>
</div>
Nope. Sounds like you've got it right.
placeholder for the popup ->
<div id="popup"></div>
jQuery ui dialog ->
$('#popup').dialog({
autoOpen: 'false',
modal: 'true',
minHeight: '300px',
minWidth: '300px',
buttons: {
'Save Changes': function(){
$.ajax({
url: 'path/to/my/page.ext',
type: 'POST',
data: $(this).find('form').serialize(),
success: function(data){
//some logic to show that the data was updated
//then close the window
$(this).dialog('close');
}
});
},
'Discard & Exit' : function(){
$(this).dialog('close');
}
}
});
Now that the default settings have been created, send a ajax request for the data from the php file, and update the content in the 'popup' div.
$('.edit').click(function(e){
e.preventDefault();
$.ajax({
url: 'path/to/my/page.ext',
type: 'GET',
data: //send some unique piece of data like the ID to retrieve the corresponding user information
success: function(data){
//construct the data however, update the HTML of the popup div
$('#popup').html(data);
$('#popup').dialog('open');
}
});
});
in the PHP page, construct a form to be sent back ->
<?php
if(isset($_GET['id'])){
//build the query, do your mysql stuff
$query = mysql_query(sprintf("SELECT * FROM sometable WHERE id = %d", $_GET['id']));
//construct constant objects outside of the array
?>
<form>
<?php
while($row = mysql_fetch_array($query)){
?>
<tr>
<td>
<input type="text" name="<?php echo $row['id']?>" value="<?php echo $row['name'] ?>" />
</td>
</tr>
<?php
}
?>
</form>
<?php
}
?>
I am sure there are better ways..
No, that's about it.
You'll need a PHP script to give you the user's current details, and a second in which you should combine adding a new user, or updating an existing user.
Use AJAX to obtain the list of users, and likewise have the "current detail" page send back an JSON blob containing the information.
Use the client side Javascript to populate the dialog itself.
The hardest part is making sure that only authorised users can talk to the backend scripts.
Here's what I would do:
when creating the list of users, I know the id (unique) for each user. Then attach an event handler for the edit button that will make an ajax request to a server side script with that user id, the server side script will send you user details in JSON format.
have a template, for example a div, that has all the fields you need for updating user details (with classes attached or ids so you will know how to find them with selectors). when you receive data from the server you set the value of the fields in your template to the data in the response of the server then open the dialog (which is pre populated now with the data you need).
updating user details can also be done by ajax, to keep things simple. (grabbing the values in the inputs, and send a request to the server, sending also the id of the user you want to change details.
So... good luck!
The simplest way would be to get the information in the database using PHP, and populate the UI tables like that. The major downside would be loading time. If you find that the page is taking too long to load, then you may want to look into jQuery's .ajax()
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');
});