I have a page full of images that end with _off.jpg. I have an onclick event that when an image is clicked, it will change the image to the _on.jpg version of the image(an image that is grayed out). That part works fine. I also want it to call an update.php page where I'll update the database using variables passed in for that image that was clicked.
The problem is that I'm having trouble getting the variable for the image clicked to pass through to the update.php page.
here is the jquery function to swap each image with the ajax call to update.php
jQuery(function(){
$(".img-swap").live('click', function() {
if ($(this).attr("class") == "img-swap") {
this.src = this.src.replace("_off","_on")
$.ajax({
type: "get",
url: "updatelist.php"
});
} else {
this.src = this.src.replace("_on","_off");
}
$(this).toggleClass("on");
});
});
And here is the part that is calling the images from the directory
$files = glob("movieposters/*_off.*");
for ($i=0; $i<count($files); $i++)
{ $num = $files[$i];
echo '<img src="'.$num.'" border="3" style="border-color:#ffffff" class="img-swap">';
I think this will do what you want...
Display images
<?php
// Load list
$_fileList = glob( "movieposters/*_off.*" );
foreach ( $_fileList as $_file )
echo '<img src="' . $_file . '" border="3" style="border-color:#ffffff" class="img-swap">';
?>
Swap them...
<script>
$(function(){
$('.img-swap').live('click', function() {
var _src = $(this).attr('src');
if (-1 == _src.indexOf('_on')) {
$(this).attr('src',_src.replace('_on','_off')).removeClass('on');
} else {
$(this).attr('src',_src.replace('_off','_on')).addClass('on');
}
// Update server
$.get( 'updatelist.php?image='+escape(_src));
});
});
</script>
Then your server script (updatelist.php):
<?php
$_clickedFile = $_GET['image'];
...
?>
Here's a quick example of an AJAX request:
$.ajax({
type: "GET",
url: "file.php",
data: "foo=three&bar=asdfg",
success: function(data) {
alert('Response was: ' + data);
}
});
The part that sets the variables to be sent is right here, "foo=three&bar=asdfg", so if you want to send the src= of the image, this sort of request might work:
$.ajax({
type: "GET",
url: "file.php",
data: "name=" + encode($(this).attr('src')),
success: function(data) {
alert('Response was: ' + data);
}
});
Note that I used encode(). You need to encode your requests.
Related
I have this little piece of code and I would like to pass the value to PHP.
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
Is there a way to do this? (new at jQuery)
Many thanks!
check this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
$.ajax({
type: "POST",
url: 'edit.php',
data: "window_size=" + size,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
alert(result)
}
});
</script>
then create edit.php
<?php
print_r($_REQUEST);
?>
if you want to save this value then use this code
<?php
session_start();
echo $_SESSION['php_value'];
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
$.ajax({
type: "POST",
url: 'edit.php',
data: "window_size=" + size,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
alert(result);
//window.location.reload();
}
});
</script>
and update edit.php as like
<?php
session_start();
$_SESSION['php_value'] = $_REQUEST['window_size'];
echo $_SESSION['php_value'];
?>
you want to see this value or use then refresh this page
if you want to use this variable in other page then use this
//first page first set it
$_SESSION['php_value'] = $_REQUEST['window_size'];
//second page or other page and use it
$var_value = $_SESSION['php_value'];
No you cannot. JQuery plays on client and php on backend.
If you want to pass some values from Client (Jquery/Js) to Backend (PHP), you need to either submit a form or make an AJax call to server.
You should research about jQuery ajax. This can be your solution for sending data to server from client.
Yes. Use the code below to send the value of size to your php script:
var ajax_call = $.ajax({url: '/your_php_script.php', data: 'size='+size, success: function(data) {
}});
My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}
First i echo images for which i set ID with php function. Now im tyring to get the ID value with jQuery click function and pass it to another php function, but unfortunately i always get the undefined index error. Can the reason be in xampp config or something else? Becasuse the code seems to be "right".
jQuery
$(function postImgId() {
$('img').click(function() {
var imgId = $(this).attr('id');
$.post('functions.php', {postId:imgId},
function(data) {
$('#content').html(data);
console.log(imgId);
});
});
});
php
function showPlayer() {
$number ='';
$number = $_POST['postId'];
if(isset($_POST['postId'])) {
echo "<h2>";
echo $_POST['postId'];
echo "</h2>";
}
}
Try:
Put this in your click function:
var imgId = $(this).attr('id');
$.ajax({
type: "GET",
url: "functions.php",
data: 'playerId=' + imgId,
success: function(data){
$('#content').html(data);
}
});
now check with isset($_GET['playerId']) and so on in your php:
if(isset($_GET['playerId'])) {
echo "<h2>";
echo $_GET['playerId'];
echo "</h2>";
}
This playerId should not be something important in your database like the unique AI id.
Whole thing also works with POST see: http://api.jquery.com/jquery.post/
I used ajax loader to uplaods files to server.It works fine but now i want to set delete option with each image and can delete that image before saving.My current images look like :
I am using this file uploader script for file uploading.Link
My Code for files upload is :
jQuery("#fileuploader").uploadFile({
url:"<?php echo $this->getUrl('pmembers/priority/productimages/') ?>",
multiple:true,
fileName:"myfile",
onSuccess: function (files, response, xhr,pd) {
var dir = '<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA)."mkd/uploads/".Mage::getSingleton("customer/session")->getId()."/"; ?>';
jQuery('#files').append('<li style="width:60px; float:left;margin-left:5px; margin-right:5px;"><img width="60" height="60" src="'+dir+files+'" /></li><img src="cross.png" />');
},
});
});
Try:
Event when click remove button will send a request to server unlink (path: "dir+files"), after complete server will return client a notify.
jQuery:
var removeButton = $("li > img:last");
removeButton.click(function(){
if (removeButton.attr('handling') != "true") {
removeButton.attr('handling', 'true');
var path = removeButton.prev('img[src]').attr('src');
$.ajax({
type: "POST",
dataType: "json",
url: (url),
data: {'path': path},
error: function () {
//. Action when error.
},
success: function (data) {
//. Action when success.
}
}).done(function(){
removeButton.attr('handling', 'false');
});
}
});
PHP:
$path = $_POST['path'];
$unlink = unlink($path);
if (!$unlink) {
print json_encode(array("return" => false)); exit();
}else {
print json_encode(array("return" => true)); exit();
}
I am using AJAX to load content from mysql database when I CLICK on LINKS.
once I load the content successfully, I refresh the container every 5 seconds so the new content will be displayed.
the content gets loaded fine and the refresh part works fine too.
but the issue that I have is that when the refresh happens, the loaded content gets lost.
by "it gets lost" i mean that it will display the LAST result from the mysql database.
so, to help you understand the situation I will explain it further:
Lets say I have 3 results stored in mysql database.
I create <a></a> from each result in mysql using PHP. i am doing this without any issue.
I click on the link 2. (works fine)
the content of the link 2 will load on the page using AJAX. (works fine)
The container of content will refresh every 5 seconds. (works fine)
(THIS IS WHERE THE PROBLEM STARTS) once the refresh happens, the content of link 3 will be displayed even though I haven't clicked on the link 3!
so basically, for some strange reason, the content of the last Link or last mysql result will be displayed at all time which is un-wanted. I need to load the content of the CLICKED link and make it stay until another Link is clicked.
I hope I haven't confused you. :)
here is my html code:
<div id="chattercontent" style="width:90%; height:150px; resize:none; border:solid 1px #ccc; background:#F2EDF0; overflow:scroll; text-align:left;"></div>
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
}
load();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".list-group-item").click(function(e) {
e.preventDefault();
$("#chattercontent").load(this.href);
return false;
});
});
</script>
and PHP code for the links:
while (mysqli_stmt_fetch($stmt)) {
$product_list .= "<a id='listc' class='list-group-item' href='file.php?u_id=".$u_id."' >".$u_id." ".$date_added." <img src='light-red-flash.gif' width='20' /></a>";
}
}
any help would be appreciated.
Thanks
edit:
this is the code for file.php
<?php
session_start();
if (isset($_GET['u_id'])) {
$u_id = $_GET['u_id'];
$sql = "SELECT * FROM chat WHERE u_id='$u_id' ";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$user_message = $row["user_message"];
}
} else {
echo "Sorry, there was an error.";
exit();
}
echo $user_message;
}
?>
as I mentioned before, the file.php returns the result properly according to the link that have been clicked on but then it will JUMP on the last result after each refresh!
You need to keep track of the current url the user has selected:
$(document).ready(function () {
//set url 1st time
var currentUrl = "file.php?u_id=<?php echo $u_id; ?>";
//variable to reference the timeout
var timer;
function load(url) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: url,
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
timer = setTimeout(function(){
load(currentUrl);
}, 5000);
}
});
}
load(currentUrl);
$(".list-group-item").click(function(e) {
e.preventDefault();
//update url on click
currentUrl = this.href;
//cancel existing timer
clearTimeout(timer);
load(currentUrl);
});
});
You aren't loading your dynamic content with the javascript function. Check out the following, hope it will fix your problem.
function load(href) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(function() {
load(href);
}, 5000)
}
});
}
var _currentUrl;
function load(href) {
if (!href) {
href = _currentUrl;
}
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
_currentUrl = href;
}
I am a bit confused. I would be glad if you would explain it a bit more with some examples.
Anyway from what I could get from your text is that, the previous result is being overwritten.
In order to stop that, as we do while making a chatbox, you need to add the response "after" the previous result as in -
<script type="text/javascript">
/* A variable to hold the last response */
var lastResponse = "";
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
/* Check if it is the same response or not */
if (lastResponse != response)
{
/* Save the last response */
lastResponse = response;
/* Add content after the previous */
$("#chattercontent").html($("#chattercontent").html()+response);
}
setTimeout(load, 5000)
}
});
}
load();
});
</script>