Delete clicked item in jQuery and PHP? - php

I just have a quick question how do I delete the item I just clicked? I don't have a great way of tracking it and I'm at my last resort way right now (which is what I'm posting) which deletes everything in the list.
PHP/HTML/jQuery:
<div class="image-list">
<?php
$count = 1;
if ($hotelId) {
foreach(glob($hotelDir) as $filename=>$hotelvalue){
echo '<li id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" id="del'.$count.'" value="Delete"><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>";
$count++;
}
}else{}
?>
</div>
</div>
<script>
$('div.image-list li a.image-list').live('click', function() {
bootbox.confirm("Are you sure you want to delete this image?", "Cancel", "Confirm", function(result) {
if (result) {
$('ul.image-list li a.image-list').closest('li').fadeOut();
$.post('assets/php/deletefile.php');
}
});
});
</script>
Here is the delete information (right now it is static PHP that only deletes the first file I don't have another way of doing this yet):
<?php
session_start();
$files = glob("upload/" . $_SESSION['curHotelId'] . "/" . '*.*');
if(is_file($files[0]))
#unlink($files[0]);
?>
UPDATE:
Thanks to Karl's answer I got a better idea of what I'm doing, but I still cannot get these to remove. I don't know why. They stay blank and act as if they don't even exist or the button does not work.
Here is my updated PHP/HTML/jQuery:
<div class="image-list">
<?php
$count = 1;
if ($hotelId) {
foreach(glob($hotelDir) as $filename=>$hotelvalue){
echo '<li data-filename="' . basename($hotelvalue) . '" id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" data-filename="' . basename($hotelvalue) . '" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a data-filename="' . basename($hotelvalue) . '" class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" id="del'.$count.'" value="Delete"><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>";
$count++;
}
}else{}
?>
</div>
</div>
<script>
$('li.image-list a.image-list').click( function () {
var filename = $(this).attr('data-filename');
$(this).remove();
$.get('assets/php/deletefile.php?filename=' + filename).done( function() {
// it succeeded
}).fail( function (){
// it failed
});
});
});
</script>
And the PHP was updated too:
<?php
session_start();
$filename = $_get['filename'];
$files = glob("upload/" . $_SESSION['curHotelId'] . "/" . $filename);
if(is_file($files))
#unlink($files);
?>
HOPEFULLY FINAL UPDATE:
I'm so close, I just wanna throw everything I love out a window. So here is where I'm having an issue. It isn't deleting the images when the code executes so here is PHP:
ALL OF THIS CODE WORKS. C: Thank you everyone that helped!
<?php
session_start();
$file = $_POST['filename'];
$selHotelId = $_SESSION['curHotelId'];
$files = "upload/" . $selHotelId . "/" . $file;
unlink($files);
?>
jQuery:
$(document).ready(function(){
$("#imageClick").live("click", "li.image-list a.image-list", function () {
var _clicked = $(this);
var _filename = _clicked.attr('data-filename');
_clicked.parents("li.image-list").fadeOut(function(){
$(this).empty().remove();
});
$.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) {
bootbox.alert('File has been deleted!');
}).fail( function (error){
bootbox.alert('There has been an error. Contact admin.');
});
});
});

There were still a few issues in your updated code. I've made some changes, and pasted in the code below. I've changed the method to $.post(), so your PHP file will need to access the parameter as $_POST['filename'].
A couple issues I noticed, you had more than one element with the same id attribute. I removed the redundant data-filename attributes from elements that didn't need them. I placed your jQuery inside a $(document).ready() in order to make sure that nothing was called until all DOM elements had been loaded. I also used the .on method for binding the event...just in case you ever dynamically add more li elements with the a.image-list element. This way you are binding the event to an element that will always be there, and catching it on the a.image-list. (I might be explaining that incorrectly...it's late).
Hope this helps.
<ul class="image-list">
<?php
$count = 1;
if ($hotelId) {
foreach(glob($hotelDir) as $filename=>$hotelvalue){
echo '<li id="del'.$count.'" class="image-list"><a class="enlargeUser" href="'.$hotelvalue.'"><img class="imageListMain" src="'.$hotelvalue.'" width="50px" height="50px"/><p class="filename">' . basename($hotelvalue) . '</p></a> <a class="btn btn-mini btn-primary image-list" style="width: 18px;margin-top: -35px;position: relative\9;top: -25px\9;border-radius: 100%;-moz-border-radius: 100%;-o-border-radius: 100%;-webkit-border-radius: 100%;margin-left:330px;" title="Delete" data-filename="' . basename($hotelvalue) . '" ><i class="icon-remove-circle icon-2" style="margin-left:-3px;"></i></a></li>' . "\n" . "<br>";
$count++;
}
}
?>
</ul>
<script>
$(document).ready(function(){
$("ul.image-list").on("click", "li.image-list a.image-list", function () {
var _clicked = $(this);
var _filename = _clicked.attr('data-filename');
_clicked.parents("li.image-list").fadeOut(function(){
$(this).empty().remove();
});
$.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) {
// it succeeded
}).fail( function (error){
// it failed
});
});
})
</script>
UPDATE: I had a typo in my code...not sure you caught it.
var _filename = clicked.attr('data-filename');
SHOULD BE...
var _filename = _clicked.attr('data-filename');
My apologies.
To see if you are hitting your PHP file, you can do something simple like this...
<?php
$data["response"] = $_POST['filename'];
echo json_encode($data);
?>
And then modify your .done method to look like this...
$.post('assets/php/deletefile.php', {filename: _filename}).done( function(data) {
// it succeeded
console.log(data);
}).fail( function (error){
// it failed
});

You can delete or remove a DOM element with jQuery using a syntax similar to this and pull the value passed in your item:
$('div.image-list li a.image-list').click( function () {
var filename = $(this).attr('data-filename');
$(this).parents('li').remove();
});
You will have pass the data to the PHP file like you are doing but with the filename in the url:
$.get('assets/php/deletefile.php?filename=' + filename).done( function() {
// it succeeded
}).fail( function (){
// it failed
});
When you load the page you will have to load in the data-filename="filename.jpg" into the element you clicked.
In your deletefile.php, you can use $_GET['filename'] to get the filename.

Related

Echo not printing anything (It was before)

I am having a bit of a headache with a echo on my php code, the problem is that it isn't printing anything on screen, even though it was before, granted I added a function but when I used firebug to debug it it showed that it was getting the information out of a database correctly, just not printing it on-screen.
Where a list should be displayed there is nothing but empty space, staring into my soul.
I would appreciated if someone could point me out if I am missing something, as well why it is happening so I many not have to bother anyone anymore and if needed share my newly acquired knowledge.
PHP
function displayInfoLabs(){
if(isset($_POST['pId'])){
$id = $_POST['pId'];
$info = getSpecificLabs($id);
while($row = mysql_fetch_assoc($info)){
echo '<ul>' .
'<li>Laboratorio # ' . $row['codigolab'] . '</li>' .
'<li>Capacidad: ' . $row['capacidad'] . '</li>' .
'<li>Carrera: ' . $row['carrera'] . '</li>' .
'<li>Ubicación: ' . $row['ubicacion'] . '</li>' .
'</ul>';
}
}
}
function getSpecificLabs($pId){
$query = "SELECT bk.idlab , bk.codigolab , bk.capacidad, bk.carrera, bk.ubicacion FROM labs as bk WHERE bk.idlab = $pId";
$result = do_query($query);
return $result;
}
For reference I am also including the html and JS code of this function.
JS
$("#lnkInfo").click(function() {
var id = $('#txtId').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'displayInfoLabs',
'pId':id},
dataType: 'json',
success: function(response){
alert('exito')
}
});
});
HTML created via PHP, mind the lnkInfo which calls the JS that in turn calls the PHP
function displayList(){
$lista = getLabs();
while($row = mysql_fetch_assoc($lista)){
echo
'<div class="box" id="lab'.$row['idlab'].'">
<p id="labName">Lab #'.$row['codigolab'] . '</p>
<p class="info">Info</p>
<p class="info">Reservar</p>
<input type="hidden" name="txtId" id="txtId" value="'.$row['idlab'].'">
</div>';
}
}
Thanks a lot in advance.
EDIT:
Changing the success function made the list appear but it overrode the div's style including the buttons it had and all. This is the div's code.
div class="popUp1 hide" id="popUpCorrecto1">
<div class="estiloPopUp">
<span>Información de laboratorio</span>
<span value="Cerrar" id="btnCerrar">x</span>
</div>
<input type = "button" value = "Eliminar" id = "btnEliminar" onclick="eliminar()" />
<input type = "button" value = "Modificar" id = "btnModificar" onclick="window.location='modificarLab.html';" />
</div>
As you said in the comments, your data is being captured, but you aren't appending it to the document. you are simply doing:
alert('exito');
What you want to do is append the response to an element that is present in your page.
For examples sake, we can put a <div> with the id of mydata like so:
<div id="mydata"></div>
Now in your jQuery.ajax function, you could do something like the following:
$("#lnkInfo").click(function() {
var id = $('#txtId').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'displayInfoLabs',
'pId':id},
dataType: 'text/html',
success: function(response){
$('#mydata').html(response);
}
});
});
As you can see in the above, we modified your success function to include
$('#mydata').html(response);
provided all your data is printed and supplied correctly, it should display on the page.
EDIT:
it seems in your PHP query
$query = "SELECT bk.idlab , bk.codigolab , bk.capacidad, bk.carrera, bk.ubicacion FROM labs as bk WHERE bk.idlab = $pId";
You are selecting the columns prefixed with bk.* yet trying to print out the values without the prefix as seen below:
echo '<ul>' .
'<li>Laboratorio # ' . $row['codigolab'] . '</li>' .
'<li>Capacidad: ' . $row['capacidad'] . '</li>' .
'<li>Carrera: ' . $row['carrera'] . '</li>' .
'<li>Ubicación: ' . $row['ubicacion'] . '</li>' .
'</ul>';
Try changing the above to something like:
echo '<ul>' .
'<li>Laboratorio # ' . $row['bk.codigolab'] . '</li>' .
'<li>Capacidad: ' . $row['bk.capacidad'] . '</li>' .
'<li>Carrera: ' . $row['bk.carrera'] . '</li>' .
'<li>Ubicación: ' . $row['bk.ubicacion'] . '</li>' .
'</ul>';
If i understood it correctly.
Edit: ignore above php examples.
Change the success function from:
$('#mydata').html(response);
to
$('#mydata').append(response);
As .html() replaces all content within the specified element with the supplied content.
EDIT #2:
From the comments, you're ajax request is run every time that #LnkInfo is triggered which seems like it happens a lot as it loads the PopUp?
What you want to do is add in some logic, either in your jQuery function that checks if you've already appended the list to the popup and to stop it appending.
That could be done simply by adding a boolean variable somewhere in there.
Alternatively, you could just add a little div on that popup that you append it to.
Example:
This is your popup:
div class="popUp1 hide" id="popUpCorrecto1">
<div class="estiloPopUp">
<span>Información de laboratorio</span>
<span value="Cerrar" id="btnCerrar">x</span>
</div>
<!-- ADDED A NEW DIV HERE FOR LIST CONTENT -->
<div id="mylistcontent"></div>
<input type = "button" value = "Eliminar" id = "btnEliminar" onclick="eliminar()" />
<input type = "button" value = "Modificar" id = "btnModificar" onclick="window.location='modificarLab.html';" />
</div>
As you can see above, I've added the following:
<!-- ADDED A NEW DIV HERE FOR LIST CONTENT -->
<div id="mylistcontent"></div>
Now in your jQuery success function, you could append to that #mylistcontent div instead of the popup div :)

Refresh one variable every second

I want to refresh two variables named profittext and sumtext which will be refreshed and echoed in the following places every few seconds. I know AJAX is needed to do this but how do i actually make it work ? The only way i found out was to refresh the content of the whole file. is there any way to refresh specific variables? Any answers will be greatly appreciated . Thank you very very much.
<table>
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$sum+= $profitandloss;
//
echo "<tr><td>" . $row['trade_id'] .
"</td><td>" . $row['selection'] .
"</td><td>" . $row['date'] .
"</td><td>" . $row['type'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['bidprice'] .
"</td><td>" . $row['offerprice'] .
"</td><td>" . $row['stoploss'] .
"</td><td>" . $row['takeprofit'] .
"</td><td>" . $profitText .
"</td><td><a href ='delete.php?id=".
$row['trade_id']."'>X</a>
</td></tr>";
$profitandloss=0;
if($sum<$zero) {
$sumText = "<div style=\"color: red;\">$sum</div>";
} elseif ($sum>$zero) {
$sumText = "<div style=\"color: green;\">$sum</div>";
}
}
echo "</table><br>";
?>
<!DOCTYPE html>
<html>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">Profit/Loss</th>
</tr>
<tr>
<td style="border:1px solid black;"><?php echo $sumText ;?></td>
</tr>
</table>
</html>
I struggled with the concept of how to structure such code when I first started too. Although it's not specific to your particular variables, here's a quick example for how to update a var through AJAX with jQuery/PHP.
Prologue: If this is something you're going to be doing often, you'll want to learn jQuery, rather than using normal javascript alone. There are lots of great, free, resources on how to learn jQuery. Alternatively, if you're not satisfied with the free tutorials online, this is an excellent book. I'll write the example in jQuery.
Design: Okay, so the way it works is this:
Set a timer in javascript to execute a particular function every X seconds (you DO NOT want to do it every second).
That function makes an AJAX call (with jQuery) to a .PHP file on the server, sending it the data necessary so that the .PHP code knows what to send back.
The .PHP code grabs the data required (e.g., with MySQL) encodes it in a JSON format, and exits.
A promise on the AJAX call is fired and the data sent from PHP is received. Process it as you will.
Repeat from step 2.
If you have any questions about what the code is doing, please ask.
AJAX.PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$return_obj = array();
$request_obj = NULL;
// our AJAX call used "POST" as it's 'type', so we look in that
// variable.
if ( array_key_exists("func",$_POST) ) {
if ( $_POST['func'] === "get_update" ) {
if ( array_key_exists("which_var",$_POST) ) {
$which_var = $_POST['which_var'];
$which_var = $mysqli->real_escape_string($which_var); // should use prepared statements
// we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field
// with that value. this assumes that some other code, somewhere else,
// is regularly updating the table. it also assumes that there will only
// be a single row returned, which will hold the value.
$query = "SELECT '$which_var' FROM site_stats ";
if ( $result = $mysqli->query($query) ) {
if ( $row = $result->fetch_assoc() ) {
$request_obj[$which_var] = $row[$which_var];
}
}
}
}
}
$return_obj['request'] = $request_obj;
echo json_encode($return_obj);
die();
?>
MYCODE.JS
// this actually sends the AJAX request to the server.
function getUpdate() {
var jqXHR = $.ajax({
url : "ajax.php",
data : {
'func' : 'get_update',
'which_var' : 'num_people_logged_in'
},
dataType : 'json',
type : 'POST',
timeout : 10000
});
// attach 'promises' to the jqXHR object, which represents
// the AJAX call itself. 'promises' are, in this context,
// just events.
jqXHR.done(function(data,textStatus,jqXHR) {
// this executes if the AJAX call succeeded.
// the variable 'data' holds what the server
// sent us.
if ( ( data ) && ( data.request ) ) {
receiveUpdate(data.request);
}
});
jqXHR.fail(function(jqXHR,textStatus,errorThrown) {
// this executes if it failed
console.log("Fail: " + textStatus + " (" + errorThrown + ")");
});
jqXHR.always(function(a,textStatus,c){
// this executes either way, after .done or .fail
});
}
// this is called from jqXHR.done, on success
function receiveUpdate(request_obj) {
if ( request_obj.num_people_logged_in ) {
updateDOM(request_obj.num_people_logged_in);
}
}
function updateDOM(num_people_logged_in) {
if ( num_people_logged_in ) {
$("#mydiv > p.update").html("The updated value is: " + num_people_logged_in);
}
}
var timeoutID = null;
// setup our timer, to periodically make an
// AJAX call
function init() {
timeOutID = setInterval(function(){
getUpdate();
},5000);
}
// stop the timer
function cleanup() {
clearTimeout(timeoutID);
}
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AJAX practice</title>
<!-- <link href="mycss.css" rel='stylesheet'> if needed -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="mycode.js"></script>
<script>
$(document).ready(function() {
init();
$("#cleanup").on("click",function(){
cleanup();
});
}); // end ready
</script>
</head>
<body>
<div id='mydiv'>
<p>
How many people are online?
</p>
<p class='update'>
</p>
</div>
<button id='cleanup'>Stop updating!</button>
</div>
</body>
</html>
You will needd two PHP pages:
- one with HTML and JS, which periodicly makes ajax calls and puts the result to the HTML
- second with json (or even plain text) output of your dynamic data piece
Unfortunately, writing the full code in the answer is not someting that people do at stackoverflow, so just look at small example below, and try to figure out the missing parts.
http://jsfiddle.net/AMEqz/
var xhr = new XMLHttpRequest();
xhr.onload = function(r) {
// your render logic HERE
setTimeout(send, 1000);
}
function send() {
xhr.open("GET", "/", true);
xhr.send();
}
send();
p.s.: keep in mind that each ajax request will mean extra connection to your server, so make sure it can deal with the load ;)
Use a timer : https://developer.mozilla.org/en/docs/DOM/window.setInterval
setInterval(function(){
//update your var here
},1000);

Download-Page with JQuery request

I have a download page. Members are free to click on their bought songs and the download starts. I wish now that in the same time an Ajax request takes place, which adjusts the count of downloads in the database. The page should then be reloaded to the counter from the database is updated again. If the counter is zero, there is no longer downloading.
Obviously my script does not work. The download happens, but the JQuery-Script will not work. Does someone have a solution?
This is the link to the download-page:
<a href="get-download-files.php?file=xyz.zip"><img class="a_0" src="images/download.png" width="30" height="30" />XYZ-Song/a>
And this is the Java-Script on the same page:
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$.get("zaehler.php?dl_id=1", function(data){
$("#ausgabe").html(data);
});
});
});
</script>
And this is the request-file:
<?php
require_once 'includes/db_login.php';
$dl_id = $_REQUEST['dl_id'];
// counter updaten
$sql = 'UPDATE ' . $tbl_prefix . 'downloads
SET zaehler = zaehler - 1
WHERE dl_id = ' .$dl_id;
mysql_query($sql);
$abfrage = 'SELECT zaehler FROM ' . $tbl_prefix . 'downloads WHERE dl_id=' . $dl_id;
$ergebnis = mysql_query($abfrage);
while ($datensatz = mysql_fetch_array($ergebnis, MYSQL_ASSOC))
{
echo '<h3 style="color:#333;">Dein Download-Stand</h2>';
echo '<br /><br />Du hast noch ' . $datensatz['zaehler'] . ' Downloads zugut.';
}
?>
Im thanking you. Best regards,
Heinz
You don't need Ajax for this. In the script get-download-files.php, update the database before delivering the file to the browser.
Have you tried this?
<script>
$(document).ready(function(){
$(".a_0").click(function(){
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>
You can check if your code is executed by adding a alert() inside your function. If the alert fires, the function is executed.
<script>
$(document).ready(function(){
$(".a_0").click(function(){
alert('Function is fired!'); // Debug
$("#ausgabe").load("zaehler.php?dl_id=1");
});
});
</script>

Unable to get animations to work correctly in jQuery

I just recently started learning jQuery. To help me learn, I started redesigning this website. The problems I have at the moment are:
Once a thumb image is clicked and the main post loads; after closing the main post and when hovering over the thumbs again, the title and post information no longer fade in above and beside the thumbs.
When hovering over a thumb image for the first time, you should notice that it hides everything (including itself) and then shows itself again, this gives the illusion that it flickers. How can I stop this?
Here is the .js file containing the jQuery code:
$(".post").hover(
function () {
$(this).children(".post_title, .post_info").stop(true).fadeIn();
$(this).children(".link-to-post").stop().show();
$(".post").stop().fadeTo(0,0.2);
$(this).fadeTo(300,1);
},
function () {
$(this).parent().find(".post_title, .post_info").stop(true).hide();
$(this).parent().find(".link-to-post").stop().hide();
$(".post").stop().fadeTo(300,1);
});
$(".cover-img").click(function(){
$("#main-post").fadeIn(1000);
$.post("inc/fullpost.php", {postid: $(this).data('postid')},
function(output){
$("#gotpostid").html(output).show();
}).fail(function(x,y,z){
$("#gotpostid").html(x + "<br />" + y + "<br />" + z)
});
$('.post').fadeTo(0,0);
});
$('input[name=close]').click(function(){
$(this).closest('#main-post').hide();
Each thumbnail is within its own class:
// Retrieve all active posts order by lastest first
$resultarray = retrieve_active_posts();
echo '<div id="content-wrap">';
foreach($resultarray AS $value){
$filename = substr($value['img_file_name'],9);
$cat_id = $value['cat_id'];
echo '<article class="post">';
echo '<div class="post_title">' . stripslashes(stripslashes($value['post_title'])) . '</div>';
echo '<div class="post_info">' .
'Category: ' . $cat_name = get_cat_name($cat_id) .'<br />'.
'Year: ' . $value['post_year'] .'<br />'.
stripslashes($value['post_desc']) .'<br />'.
'</div>';
echo '<div class="link-to-post">Click to view</div>';
echo '<img class="post-thumb" src="img/thumb_/'.$filename.'" alt="MJbox Michael Jackson memorabilia thumbnail" data-postid="'.$value['post_id'].'"/>';
echo '<img class="cover-img" src="img/post-bg-1.png" alt="test" data-postid="'.$value['post_id'].'"/>';
echo '</article>';
}
echo '</div>';
I'll have another go :-)
I've looked on the Google Developer Tools and it looks like this is the problem...
$('.post').fadeTo(0,0);
It is leaving the opacity attribute as 0. When I override this in developer tools, the popups show again. Try changing it to:
$('.post').fadeOut;
or even
$('.post').hide();
Should do the trick.
I'm pretty sure I have the answer to the other problem:
You have two animations. You are fading all of the .post items out and then fading $(this) back in again. You need this solution:
$(".post").hover(
function () {
$(this).children(".post_title, .post_info").stop(true).fadeIn();
$(this).children(".link-to-post").stop().show();
$(this).siblings.().stop().fadeTo(0,0.2);
},
This will fade out only the other ones so you don't have to fade $(this) back in again!
Fingers crossed!
I have tested this. It fixes both problems and also stops the browser going to the top of the page when you click one of the thumbs.
Here is the complete jQuery code
$(document).ready(function(){
$(".fancybox").fancybox();
$("#login").click(function(){
$("#searchform").hide();
$("#loginform").fadeIn('3000','swing');
});
$("#search").click(function(){
$("#loginform").hide();
$("#searchform").fadeIn('3000','swing');
});
$(".post").hover(
function () {
$(this).children(".post_title, .post_info").stop(true).fadeIn();
$(this).children(".link-to-post").stop().show();
$(this).siblings().stop().fadeTo(0,0.2);
},
function () {
$(this).parent().find(".post_title, .post_info").stop(true).hide();
$(this).parent().find(".link-to-post").stop().hide();
$(".post").stop().fadeTo(300,1);
});
$(".cover-img").click(function(e){
e.preventDefault();
$("#main-post").fadeIn(1000);
$.post("inc/fullpost.php", {postid: $(this).data('postid')},
function(output){
$("#gotpostid").html(output).show();
}).fail(function(x,y,z){
$("#gotpostid").html(x + "<br />" + y + "<br />" + z)
});
$('.post').fadeOut();
});
$('input[name=close]').click(function(){
$(this).closest('#main-post').hide();
});
});
Just cut and paste this in place of your code.
Chris
This is for your first problem.
Try doing ...
$(".cover-img").click(function(e){
e.preventDefault();
.... rest of your code
This prevents the default behaviour of the browser to follow the link. This may solve your first problem but should be in there anyway with click events.

Pass a php var to jQuery Function

How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.

Categories