I've spent the last couple of days wrestling with a .hover script that posts data to a php script then retrieves related data from a database.
Posting id data to the details.inc.php page is working fine. An alert in the script retrieves and show's the data correctly.
The problem arises when i try to include the data in a div, nothing seems to happen. Firefox show's the script to be executing and retrieving the correct id info as it should.
I don't know where from here. I've tried all i can, but my understanding of java is limited
Thanks for any help in advance.
A mouse over function executes and retrieves the id from an image
<img src="#" class="latest" id="id_retrieved_from_DB">
id is then passed through jquery and ajax which retrieves data linked to id from details.inc.php, the data retrieved should then be included in the "details" div
<script type="text/javascript">
//Mouse over
$(function(){
$('.latest').hover(function() {
id = $(this).attr('id');
$.ajax({
cache: false,
url: "details.inc.php",
data: 'hovered_id='+id,
success:function(data){
alert(data);//showing data correctly
//not working here
$("#details").load('details.inc.php', data);
}
});
return false;
}
});
</script>
details.inc.php
<?php require_once('../../Connections/userauthentication_conn.php'); ?>
<?php
require_once('../../includes/session_remap.inc');
require_once('../../includes/tNG_functions.inc.php');
?>
<?php
$KTColParam1_rsDetails = "0";
if (isset($_GET["hovered_id"])) {
$KTColParam1_rsDetails = (get_magic_quotes_gpc()) ? $_GET["hovered_id"] : addslashes($_GET["hovered_id"]);
}
mysql_select_db($database_userauthentication_conn, $userauthentication_conn);
$query_rsDetails = sprintf("SELECT tbl_entries.id_ent, tbl_entries.country_ent, tbl_entries.date_ent, tbl_entries.title_ent, tbl_entries.subject_ent, tbl_entries.description_ent, tbl_entries.image_ent, tbl_entries.url_ent FROM tbl_entries WHERE (tbl_entries.id_ent=%s) ORDER BY tbl_entries.date_ent DESC ", $KTColParam1_rsDetails);
$rsDetails = mysql_query($query_rsDetails, $userauthentication_conn) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = mysql_num_rows($rsDetails);
?>
<!-- Details -->
<a href="<?php echo $row_rsDetails['url_ent']; ?>" title="Go to <?php echo $row_rsDetails['title_ent']; ?>">
<?php
//show if file exists
if (file_exists("../../images/entries/" . $row_rsDetails['id_ent'] . "__img.jpg")) {
?>
<img src="../../images/entries/<?php echo $row_rsDetails['id_ent']; ?>__img.jpg" width="70" height="70">
<?php
}
//end show if file exists
?>
<p class="seriesName"><?php echo $row_rsDetails['subject_ent']; ?></p>
<h4 class="programTitle"><?php echo $row_rsDetails['title_ent']; ?></h4>
</a>
<!-- End -->
<?php
mysql_free_result($rsDetails);
?>
Why are you doing a second ajax call?
If you already have the data available in javascript, you can replace:
$("#details").load('details.inc.php', data);
with:
$("#details").html(data);
if $("#details") is in the script page and that's the div you wish to display the result, you could use only load:
//Mouse over
var id = $(this).attr('id');
$("#details").load('details.inc.php', 'hovered_id='+id, function(data){alert(data);});
Or you could use $.get()
Jquery manual
The POST method is used if data is provided as an object; otherwise, GET is assumed.
And your PHP script uses get.
Related
I'm currently developing a web app that demonstrates how to "sign" different words in ASL. There's a list of terms on the left, and a video and comment section on the right.
See screenshot here: http://i917.photobucket.com/albums/ad19/brycematheson/Screen%20Shot%202015-06-16%20at%2010.05.36%20PM.png
I'm struggling to get the comments to change using AJAX whenever a new term is clicked. Currently, the comments stay the same as new terms are selected. How would I go about using AJAX to change the comment section to update when a new term is selected?
My comment section looks like so. Updating the $id_post=3 section in PHP will change the comment to match the comments with that ID in the database, so that's not an issue, I just need it to do it on the fly.
Here is my comment code in my index.php page:
<?php
// Connect to the database
require_once('models/db-settings.php');
$id_post = '$_POST['rowID']; //the post or the page id
?>
<div class="cmt-container">
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM comments WHERE id_post = '$id_post' ORDER BY id ASC") or die(mysqli_error($mysqli));
while($affcom = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
$id = $affcom['id'];
$name = $affcom['name'];
$email = $affcom['email'];
$comment = $affcom['comment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ucfirst($name); ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
<div style="float:right;"><span class="action">X</span></div>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clearfix"></div>
</div>
And my Javascript:
$('#matrix tr').click(function (event) {
var rowID = ($(this).attr('id')); //trying to alert id of the clicked row
$(function(){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'index.php',
data: rowID,
success: function(msg) {
}
});
});
});
What am I doing wrong? Am I missing something?
Thanks in advance.
You aren't actually doing anything with the page once it's returned to you
success: function(msg) {
}
When the ajax completes successfully the code inside this function will execute, whatever was returned by the page will be inside the msg param.
success: function(msg) {
$('#comments-container').html(msg);
}
This will entirely replace the contents of the element(s) that have id="comments-container" with whatever the ajax request returned.
You might properly read the jQuery AJAX documentation page and study some of the examples. http://api.jquery.com/jquery.ajax/
Once you've fixed that you'll run into a problem where it still won't change, this is because you're not sending properly formatted POST data.
data: rowID,
In order to access the POST data like you are trying to (with $_POST[key]) the POST data also needs to be in key-value pairs.
data: "rowID=" + rowID,
Read the comments on the PHP manual page for the $_POST superglobal for a better understanding of this. http://php.net/manual/en/reserved.variables.post.php
EDIT: Oh and if you're planning on releasing this website to the public you might want to look at SQL Injection and how to harden your websites against it. As it stands this would be pretty easily broken into and your database compromised.
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 am really stuck and was wondering if someone could lend a hand please,
i know how to get a query string, thats not a problem,
however,
I have links that use jquery to fade out the content and load the new content via links,
usage example below - class="link2" is a reference for the jquery to do what it does lol
click here
in the href i have to have the # first to stop the page from loading if you get what i mean,
now when i try and get the query string id=2 it says none as there is a # first, there is probably a simple fix for this but i must just be missing it,
i have searched and searched but still cant find the answer
----------------------edit------------------------------
this is what i am trying to do,
enter page,
sql query runs to display all the reports
click a report and the jquery hides "contmain" and shows "contreports" now a new sql query runs to display the report based on the "id"
now usually i can just get this information from the url and clean it up, hovever as i have jquery running i need to have the "#" for the href so the page does not reload and the jquery can run, but now this is stopping me from being able to retrieve the url query,
Interstellar_Coder
he seems to have the right idea, passing it in the background
Although i don't fully understand what you're doing, i'm guessing it would be better to store your querystring as a data attribute.
click here
Then in your jQuery function.
$('.link2').click(function(e){
var queryString = $(this).data('id');
e.preventDefault(); // prevent the default action
});
because of the code i thought it best to post here
i think i am getting close,
#Interstellar_Coder - this is what i have so far but it only ever retrieves the first id,
$query1 = mysql_query("SELECT * FROM `".TBL_CATCH_REPORTS."` order by id DESC");
$query2 = mysql_num_rows($query1);
if(mysql_num_rows($query1) != 0) {?>
<table width="880" style="margin:0 auto">
<?PHP while ($output = mysql_fetch_assoc($query1)) { ?>
<tr class="row">
<td width="190px"><input type="button" class="c_report"value="<?PHP echo $output['id']; ?>" />
View Report <img src="images/icons/arrow_right.png" width="16" height="16" /></a></td>
<td width="210px">Submited by <?PHP echo $output['submitby']; ?></td>
<td width="160px"><?PHP echo $output['date']; ?></td>
<td><?PHP echo $output['title']; ?></td>
</tr>
<?PHP } ?>
</table>
<?PHP }else{ echo '.Sorry there are no catch reports yet'; }?>
<div id="contreport"> content here </div>
<script type="text/javascript">
$(document).ready(function(){
$(".c_report").click(function () {
$("#contreport").html('Getting Catch Report......');
$.ajax({
type: "POST",
data: "data=" + $(".c_report").val(),
url: "reportdata.php",
success: function(msg){
$("#contreport").html(msg)
}
});
});
});
</script>
my other page "reportdata.php just gets the value and is then used in a sql statement
$getreport = '';
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$getreport = trim($_POST['data']);
}
i am assuming i need some kind of loop going on in the jquery but i am just lost, been stuck on this all day today again lol
this is all i need
id 1 - link
id 2 - link
id 3 - link
id 4 - link
id 5 - link
click on any and the id will be sent to reportdata.php where the id will be used in a sql statement, then the data returned and displayed,
its truly sending me mad lol
I'v built a application using codeigniter and I have a message system that displays the users messages, this is done with a foreach statement. I have some JS in the background that once a user clicks on 'delete' of a specific message that message hides from view while the JS posts the message ID to my controller and marks that message as deleted. What is happening though is that once a user clicks on delete only the first message hides (only the first foreach value) but all other messages have separate ids but are not responding to the delete click. I should also note that if I click on 'delete' of any message the first message hides and not the message I clicked on.
heres some code:
View
<?php foreach ($rows as $r) : ?>
<li id="notification_<?php echo $r['MID']; ?>"><?php echo anchor("$r[MID]", 'X', array('class'=>'delete', 'rel'=>"$r[MID]")); ?>
<p>
<?php echo anchor("headless/view_msg/$r[MID]", $r['head'], array('rel'=>'notifications')); ?>
<?php if(strlen($r['body'] >= 74)) : ?>
<?php echo $r['body']; ?>
<?php else : ?>
<?php echo substr($r['body'], 0, 74) . "..."; ?>
<?php endif; ?>
</p>
</li>
<?php endforeach; ?>
JS:
$("a.delete").click(function(eve) {
eve.preventDefault();
var MID = $("a.delete").attr('rel');
$.post('headless/notification_read', {
MID: MID},
function(html){
if(parseFloat(html)){
$('#notification_' + MID).hide('slow')
console.log('success');
}else{
console.log('fail');
}
})
});
Im not to sure whats going on here but my guess would be that the javascript is only linking the first foreach and not the rest(if so how would i fix this)
Any help would be appreciated.
Thanks.
$("a.delete").click(function(eve) {
eve.preventDefault();
var MID = this.rel; // `this` would be the element being clicked on....
//var MID = $("a.delete").attr('rel'); this line is the problem....
$.post('headless/notification_read', {
MID: MID},
function(html){
if(parseFloat(html)){
$('#notification_' + MID).hide('slow')
console.log('success');
}else{
console.log('fail');
}
})
});
demo with comments
it seems you have a collection of anchor links that share the "delete" class, so I think this piece of code would always delete the very first one. You may want to specify the specific index of the anchor, something like
$("a.delete")[x].attr('rel')
where x is the index in this collection.
God I already forget how to program in jQuery after half a year! Sorry no other details could be given.
Edit:
Maybe a better way is to retrieve the unique id user is clicking on and pass its rel to your code.
I want to show a certain amount of results (say, 5) and make a:
<a href="" onclick="<?php ShowNextResult(); ?>">
And use onlick to show the next 5 results.
EDIT ::
HTML
<div id="results">
<div class="result"></div>
<div class="result"></div>
<div class="result"></div>
</div>
<a href="#" id="showMore" />Show more</a>
JAVASCRIPT
Use Jquery as below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#showMore').click(function(event) {
event.preventDefault();
$number = $('.result').size();
$.ajax({
type: "POST",
url: "getNext.php",
data: "count=$number",
success: function(results){
$('#results').append(results);
}
});
});
});
</script>
PHP
you should make a new php page (getNext.php ) that will get query results
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons LIMIT {$_POST['count']},5");
while($row = mysql_fetch_array($result))
{
echo "<div class='result'>".$row['FirstName'] . " " . $row['LastName']."</div>";
}
mysql_close($con);
?>
HELP
you can use SQL something like
SELECT x,xx,xxx FROM XxXxXs Limit $_POST['count'],5
Since you specifically mention JavaScript I assume you don't want to reload the page or anything like that. Your onClick will have to trigger an AJAX call to a php page on your server that will handle the request and give you back the next five records (or the last 5, or random ones, etc...).
JQuery is really popular for doing this and have built in functionality to make this process easier.
http://api.jquery.com/jQuery.ajax/
Here are some tutorials: http://docs.jquery.com/Tutorials
Your best bet is to write this functionality w/o using JavaScript. Make the page accept arguments to show specific records. Once you have that code done, then put the AJAX on top of it, but that way you'll have the older stuff to fall back on if you need to for compatibility or things don't work the way you need them to.
These are pretty general answers, do you need specific help making the query to only show the next 5 records? Or the specific PHP code to tie it together? Or just the JS to do the AJAX stuff? Could you be more descriptive if you need more info.
change
data: "count=$number",
to
data: "count=" + $number,
because then it isn't work!
Here's my solution that showing quiz questions partially with next button means on each click at Next Button 5 more question will display.
<?php
$strSQL="SELECT * FROM `quizes` WHERE Q1 IS NOT NULL ORDER BY RAND()";
$result=mysql_query($strSQL);
while($row=mysql_fetch_array($result)){
$c=0;
$q[]= $row['Q1']; // This is database record that has all question stored as array
?>
<?php
for($inc=0; $inc < $ret; $inc++){ ?>
<table>
<tr id="<?php echo "i".$inc ?>">
<td id="qs"> <?php print_r($q[$inc]); ?></td>
</tr></table>
<!-- here in i am display all question with loop in this variable $q[$inc] -->
<?php } ?>
// Now we are going to display partial
instead of all so data will display partially with next button
Next/Show More
//this is anchor/button on which more questions will load and display when clicked
//CSS question are placing in tr (table row) so first hide all question
<style>
tr{
display:none
}
</style>
//jquery now we will show partial question 5-questions at each click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("[id=i0],[id=i1],[id=i2],[id=i3],[id=i4],[id=i5]").show();
//Display first 5-question on page load other question will
//show when use will click on next button
var i=0;
$("#more").click(function(){ // Next button click function
//questions tr id we set in above code is looping like this i1,i2,i3,i4,i5,i6...
i=i+5; //at each click increment of 5 question
var e=i+5;
//start after the last displayed question like if previous result was 1-5 question then next result should be 5-10 questions...
for(var c=i; c < e; c++ ){
$("[id=i"+c+"]").show();
}
});
});
</script>