AJAX change comment on table row click - php

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.

Related

Ajax success function location.reload for individual php file

I have a feed page on my website (very similar to facebook) that enables me to like and comment on posts. I'm using ajax to update the posts, however, after a like, rather than each individual post reloading, the whole feed does (not the whole page itself, it just returns to the top of the feed).
I believe this is because each post is using a file named feedLikes.php that are all being reloaded rather than just that one specific post. I'm not sure how to only make that one post reload. below is my code.
From feed.php below, you can see i am searching for all the posts within the database. Each one of these posts is given a feedID like so:
$findShouts = $pdo->prepare('SELECT * FROM feed WHERE name IN (SELECT scoutingUsername FROM scout WHERE scoutedUsername =? OR scoutingUsername =?) ORDER BY timestamp DESC');
//execute query and variables
$findShouts->execute([$username, $username]);
if ($findShouts->rowCount() > 0)
{
//get the shouts for each scout
while($row = $findShouts->fetch(PDO::FETCH_ASSOC)){
$shoutID[] = $row['id'];
$shoutUsername[] = $row["username"];
$shoutName[] = $row["name"];
$shoutText[] = $row["text"];
$shoutTimestamp[] = $row["timestamp"];
}
$shoutCount = count($shoutUsername);
for($indexShout=0; $indexShout < $shoutCount; $indexShout++) {
print'
<div class=feedNewShout>
<div class=shoutInformation>
<div class=shoutName>
<p>'. $shoutName[$indexShout] .'</p>
</div>
<div class=shoutTimestamp>
<p>'. timeElapsed("$shoutTimestamp[$indexShout]", 2) .'</p>
</div>
<div class=shoutText>
<p>'. $shoutText[$indexShout] .'</p>
</div>
<input type="hidden" name="feedID" class="feedID" value="'. $shoutID[$indexShout] .'">
<div class=likesAndComments>
<div class=likesAjax data-id="'.$shoutID[$indexShout] .'">
</div>
<div class=commentsAjax data-id="'.$shoutID[$indexShout] .'">
</div>
<div class=deleteShoutAjax data-id="'.$shoutID[$indexShout] .'">
</div>
</div>
</div>
</div>';
}
unset($shoutID);
unset($shoutUsername);
unset($shoutName);
unset($shoutText);
unset($shoutTimestamp);
}
From this i use a jquery Ajax call in feedLikesAjax.js to find each individual feedID needed:
$(document).ready(function()
{
$(".likesAjax").each(function() {
var feedID = $(this).attr("data-id");
$.ajax({
url: "feedLikes.php",
cache: false,
type: "POST",
data: {feedID: feedID},
dataType: "html",
success: function(html){
$(".likesAjax[data-id='"+ feedID +"']").empty();
$(".likesAjax[data-id='"+ feedID +"']").append(html);
}
});
});
});
I use this information and pass it to feedLikes.php:
if (isset($_POST['feedID']))
{
$feedID = ($_POST['feedID']);
$findHasUserLiked = $pdo->prepare('SELECT username FROM feedLikes WHERE feedID =? and username=?');
//execute query and variables
$findHasUserLiked->execute([$feedID, $username]);
if ($findHasUserLiked->rowCount() > 0)
{
$hasUserLiked = $findHasUserLiked->fetchColumn();
echo<<<_END
<form action="feedLikes.php" id="unlikePostForm$feedID" method="post">
<button type="submit" class="unLikeButton"></button>
<input type="hidden" name="feedIDForUnlike" class="feedIDForUnlike$feedID" value="$feedID">
</form>
_END;
?>
<script type="text/javascript">
$(document).ready(function()
{
$('#unlikePostForm<?php echo $feedID ?>').on('submit', function (e) {
e.preventDefault();
var feedIDUnlike = $(".feedIDForUnlike<?php echo $feedID ?>").val();
$.ajax({
url: "feedLikesClicked.php",
cache: false,
type: "POST",
data: {feedIDUnlike: feedIDUnlike},
dataType: "html",
success: function(html){
location.reload();
}
});
});
});
</script>
<?php
}
else
{
echo<<<_END
<form action="feedLikes.php" id="likePostForm$feedID" method="post">
<button type="submit" class="likeButton"></button>
<input type="hidden" name="feedIDForLike" class="feedIDForLike$feedID" value="$feedID">
</form>
_END;
?>
<script type="text/javascript">
$(document).ready(function()
{
$('#likePostForm<?php echo $feedID ?>').on('submit', function (e) {
e.preventDefault();
var feedIDLike = $(".feedIDForLike<?php echo $feedID ?>").val();
$.ajax({
url: "feedLikesClicked.php",
cache: false,
type: "POST",
data: {feedIDLike: feedIDLike},
dataType: "html",
success: function(html){
location.reload();
}
});
});
});
</script>
<?php
}
$likesNumber = $pdo->prepare('SELECT count(*) FROM feedLikes WHERE feedID =?');
//execute query and variables
$likesNumber->execute([$feedID]);
$numberOfLikes = $likesNumber->fetchColumn();
print'
<div class=numberOfLikes data-id="'.$feedID .'">
<p>'. $numberOfLikes .'</p>
</div>';
}
?>
Like i said it all works perfectly apart from the reloading. Now i know the location.reload that is used on success is actually reloading every feedLikes.php for every post. But i'm really stuck on how to just reload the current feedLikes.php post that is needed for that specific post. I thought this would be really simple, and it maybe, but i cant find it anywhere.
Really grateful for any help. Thank you
There are lots of ways to do this. To achieve what you are actually asking you need to modify your jQuery success function to target only the div element for the post you are interested in. Either by adding a unique ID to the HTML, or using a selector based on the class and data-id attributes to identify that specific post.
Then yout PHP needs to only return the HTML which you want to modify and you have your jQuery success function insert that into the div for the relevant post.
Having said that, for what you are trying to do is there really any need to reload the post? You could have your PHP script just return the new number of likes and whether or not current user has liked the post and then update those values in your success call.
You could optimise your code a lot, the feedLikesAjax.js script is calling feedLikes.php once the page is loaded, creating a new ajax request for each post. You could combine the code from feedLikes.php into feed.php and have the server output the page with all the data immediately, and get rid of feedLikesAjax.js altogether. You could replace the likes and unlikes forms with a single button for each post and right now you are setting an event handler for each form individually, if you give them all a common class you can just use a single event handler.
EDIT
To answer your comment:
You don't need another query in your while statement. You can expand your first query using a left join to have it also include data from the feedLikes table in the returned results or you can use another subquery to your original query to add another column to your returned results. Something along the lines of this should give you a userLiked row with a value of 1 or 0 for liked/not liked. You might have to edit it a bit to get it working for you, I'm not an SQL guru by any means.
SELECT *, (SELECT COUNT(L.username) FROM feedLikes L WHERE L.feedID = F.id AND L.username = F.username) AS userLiked
FROM feed F
WHERE name IN (SELECT scoutingUsername FROM scout WHERE scoutedUsername =? OR scoutingUsername =?)
ORDER BY timestamp DESC

loading an ajax call within a forEach loop

i have a feed page which loads posts (known as 'shouts' in my code) from a database based on who the user is following ('scouting' in my code). The basic information is displayed correctly. However, in each post i would like to load a separate file using ajax which will control the likes of the post. Below is my PHP for the feed page:
$findShouts = $pdo->prepare('SELECT * FROM feed WHERE name IN (SELECT scouting FROM scout WHERE scouted =? OR scouting =?) ORDER BY timestamp DESC');
//execute query and variables
$findShouts->execute([$username, $username]);
if ($findShouts->rowCount() > 0)
{
//get the shouts for each scout
while($row = $findShouts->fetch(PDO::FETCH_ASSOC)){
$shoutID[] = $row['id'];
$shoutUsername[] = $row["username"];
$shoutName[] = $row["name"];
$shoutText[] = $row["text"];
$shoutTimestamp[] = $row["timestamp"];
}
$shoutCount = count($shoutUsername);
for($indexShout=0; $indexShout < $shoutCount; $indexShout++) {
print'
<div class=feedNewShout>
<div class=shoutInformation>
<div class=shoutName>
<p>'. $shoutName[$indexShout] .'</p>
</div>
<div class=shoutTimestamp>
<p>'. timeElapsed("$shoutTimestamp[$indexShout]", 2) .'</p>
</div>
<div class=shoutText>
<p>'. $shoutText[$indexShout] .'</p>
</div>
<input type="hidden" name="feedID" class="feedID" value="'. $shoutID[$indexShout] .'">
<div class=likesAjax>
</div>
</div>
</div>';
}
unset($shoutID);
unset($shoutUsername);
unset($shoutName);
unset($shoutText);
unset($shoutTimestamp);
}
In each post the div class=likesAjax performs an ajax call which sends the hidden $feedID to feedlikes.php.
feedLikes.js
$(document).ready(function()
{
var feedID = $(".feedID").val();
$.ajax({
url: "feedLikes.php",
cache: false,
type: "POST",
data: {feedID: feedID},
dataType: "html",
success: function(html){
$(".likesAjax").empty();
$(".likesAjax").append(html);
}
});
});
feedLikes.php
if (isset($_POST['feedID']))
{
$feedID = ($_POST['feedID']);
echo "$feedID";
}
the problem i have is that i can see the ajax goes through every post and echos the feedID, however, every time a new call is made, all the feedID's change to the same thing. I know this is because my success call in my ajax updates every likesAjax class to the same thing. So whatever the feedID is of the last post, will be displayed for all of them.
My question is, how can i load feedLikes.php so that every post is shown with its own $feedID?
Note, feedLikes.php will eventually do something with the ID, the echo is just for test purposes.
Without changing your codes' logic, in PHP you can add an attribute to each ".likesAjax" box called data-id:
<div class="likesAjax" data-id="'.$shoutID[$indexShout] .'">
Now in jQuery in your ajax success function you can update your selector to look for this attribute as well in order to update the correct ".likesAjax" element:
$(".likesAjax[data-id='"+ feedID +"']").append(html);
To put these all together you would need to loop through your .likesAjax elements. To make your code a little cleaner you should make a function with the feedID as a parameter that will be executed for every step of the loop. This will look like the following:
$(".likesAjax").each(function() {
var feedID = $(this).attr("data-id");
loadFeedLikes(feedID);
});
function loadFeedLikes(feedID) {
$.ajax({
url: "feedLikes.php",
cache: false,
type: "POST",
data: {feedID: feedID},
dataType: "html",
success: function(html){
$(".likesAjax[data-id='"+ feedID +"']").html(html);
}
});
}
If you want to make this lighter you can create a new feedLikes.php that takes all the feedLikes you have and pushes them in an array. This array should contain the content you need and the feedId. Then you would only need one ajax call and with a for loop you could loop through the results and update all the $(".likesAjax") elements at once. This way you will have only one query to your db and only one ajax call to fetch your data.

How can I combine php documents to 1 document?

I'm making something like stock-price finder, there is data table made up of stock name, code, price.
what I want to do is if user input stock name on index.html, the result will shown at result.php , and If user click stock name, describe more information on view.php. anyway I made up this, the problem is... I think the pagination would be complicated with user, I want to combine pages to one page. not using result.php and view.php, but only index.html.
Like this...
There are some variable moving page to page, so I'm very afraid of how can I merge this pages. user input text, and the code. I don't know how I can control it.
index.html
<form action="./result.php" method="get">
<label>
Search
<input type="text" name="keywords">
<input type="submit" value="Search">
</label>
</form>
result.php
<?php
require_once './require/db.php';
if(isset($_GET['keywords'])){
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("SELECT name,code FROM data2 WHERE name LIKE '%{$keywords}%' ");
?>
<div class="result-count">
Found <?php echo $query->num_rows; ?> results.
</div>
<?php
}
if($query->num_rows) {
while($r = $query->fetch_object()) {
?>
<div class="result">
<a href="./result.php?code=<?php echo $r->code;?>">
<?php echo $r->name; ?></a>
</div>
<br />
<br />
<?php
}
}
?>
view.php
<?php
require_once("./require/file_get_contents_curl.php");
$code = $_GET['code'];
$source = file_get_contents("http://www.nasdaq.com/symbol/$code");
$dom = new DOMDocument();
#$dom->loadHTML();
$stacks = $dom->getElementsByTagName('dl')->item(0)->textContent;
?>
The above code I made up. but I want to merge it. How can I combine 3 documents to 1 document? because of user input 'keywords(index.html->result.php)' and '_GET variable(result.php->view.php)' It's very difficult to me. Please help me.
You can keep your separate files, but instead of displaying the information inside those actual files, you can call them via AJAX (asynchronous HTTP requests) instead. Here's the syntax using jQuery:
index.html
<input type="text" id="keywords">
<button id="search">Search</button>
<div id="result"></div> <!-- The div that will be filled with the result from the AJAX request -->
Javascript
$('#search').click(function(){
$.ajax({
url: "result.php",
method: "POST",
data: {keywords: $('#keywords').val()}
}).success(function(result) {
$('#result').html(result);
});
});
result.php
<?php
require_once './require/db.php';
if(isset($_POST['keywords'])){
$keywords = $db->escape_string($_POST['keywords']);
$query = $db->query("SELECT name,code FROM data2 WHERE name LIKE ' {$keywords}%' ");
echo "Found ".$query->num_rows." results.";
?>
So in the example I made up above you pass in the variable keywords as keywords. This means that inside result.php, you can access the variable keywords via $_POST['keywords'].
So basically, you do the exact same things in result.php and view.php you've done so far, but you return the data to the index.html file instead of just echoing it out in that file. If you want to read more about the AJAX function in jQuery, here's a link: jQuery.ajax().
Hope this helps, please let me know if you wonder something.
This is a very broad question.
So the answer will be very subjective.
If this is your first rodeo, I think its a good time to learn about AJAX.
The basic idea is that you let a javascript request information from the server, and add the response to the page.
AJAX is a complex set of methods, but with modern frameworks like jquery, it's become easy to implement.
See this documentation:
http://www.w3schools.com/jquery/jquery_get_started.asp
and
https://api.jquery.com/jquery.get/
when jquery is added to your page, try this:
$.get( "result.php", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
if you do not like ajax,
try adding iframes to the index.html, and set the src of the iframe to the php page you want to display.
This will cause them to load once. So you need to refresh them everytime the dropdown changes.
that could be a little tricky: How to refresh an IFrame using Javascript?

How to save and retrieve contenteditable data

I want to be able to change the text of some pages. Using contenteditable would be perfect for me.
Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work, but I just don't understand the programming languages used to store the data enough to make it work.
This is how I would like it to work:
Admin hits a button 'edit'
div becomes editable.
When the admin is ready editing, he hits a button 'save'
The data is saved to a file or database (don't really know what would be the best option).
The edited content shows up when the page is opened.
This is all I have for now:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.
My problem is that i really have no idea how to save the edited data.
I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.
Thanks for your help,
Samuël
EDIT:
#gibberish, thank you so much for your super-quick reply!
I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.
Here's my code:
over_ons.php:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
<input type="button" value="Send Data" id="mybutt">
<script type="text/javascript">
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'sent_data.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
</script>
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
$tekst=$_POST['myTxt'];
$query="UPDATE paginas SET inhoud='" .$tekst. "' WHERE id='1'";
mysql_query($query);
?>
Thanks again for your great help!
Can you also help me to make the div editable only when the user hits a button?
SOLUTION:
It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)
I would like to share how i did this if someone wants to do the same.
over_ons.php:
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper' id='editable'>
<?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show content
echo $inhoud;
?>
</div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
As this is a pretty long and complicated file, I tried to translate most of my comments to english.
If you want to translate something that in't already translated, the original language is Dutch.
javascript.js:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editable").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up witch page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.
Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.
Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:
jsFiddle Demo
$('.editable').prop('disabled',true);
$('.editbutt').click(function(){
var num = $(this).attr('id').split('-')[1];
$('#edit-'+num).prop('disabled',false).focus();
});
$('.editable').blur(function(){
var myTxt = $(this).val();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
PHP file: some_php_file.php
<?php
$myVar = $_POST['varname'];
$secondVar = $_POST['anothervar'];
//Now, do what you want with the data in the vars
Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the moreTxt variable -- I added that to show how you would add a second var of data to the ajax.
Here are some basic examples to bring you up to speed on ajax:
AJAX request callback using jQuery
There is no short path to learning jQuery or AJAX. Read the examples and experiment.
You can find some excellent, free jQuery tutorials here:
http://thenewboston.com
http://phpacademy.org
UPDATE EDIT:
To respond to your comment inquiry:
To send data from a DIV to a PHP file, first you need an event that triggers the code. As you mentioned, on an input field, this can be the blur() event, which triggers when you leave a field. On a <select>, it can be the change() event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user does, such as clicking a button.
So, the user clicks a button -- you can get the content of the DIV using the .html() command. (On input boxes and select controls, you would use .val(), but on DIVs and table cells you must use .html(). Code would look like this:
How to send DIV content after a button clicked:
HTML:
<div class='big_wrapper' contenteditable>
PAGE CONTENT
</div>
<input id="mybutt" type="button" value="Send Data" />
jQuery:
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
You could save the whole
page clientside with this:
<script>
function saveAs(filename, allHtml) {
allHtml = document.documentElement.outerHTML;
var blob = new Blob([allHtml], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
</script>
hth

$.ajax script not pulling php data into div

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.

Categories