I want to run PHP code and change image when clicked - php

I've got some HTML with this image and this data-id.
<img id="test" src="image1.png" data-id="12345" />
I would like to change image1.png for image2.png, or change image2.png for image1.png when the image is clicked.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$("#test").click(function () { var $id = $(this).attr('data-id') });
$.ajax({
url:"test.php",
type: "POST",
data: { id = $id },
success:function(){ }
});
});
</script>
And here is my test.php script.
<?php echo $dataid; ?>
I meet some difficulties with Ajax and JQuery because I'm not used to it...

store the image in a div. whenever click on image retrieve the id and pass to test.php via ajax and echo the response inside the div
mainpage
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#toggle").on('click', '#test', function()
{
var $id = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "test.php",
data: { id: $id },
success: function(theResponse) {
$('#toggle').html(theResponse);
}
});
});
});
</script>
<div id="toggle">
<img id="test" src="image1.png" data-id="12345" />
</div>
test.php
<?php
# Get Id here
$id = isset($_POST['id']) ? $_POST['id'] : '';
# for testing; remove this
echo $id;
# change here date-id and src; if it is dynamic do the database select and display image
echo '<img id="test" src="image2.png" data-id="54321" />';
?>

Related

change span width style using jquery data response

I want to change the width of span depends on load data from jquery respnse. Thanks.
<div class="star-rating">
<span style="width:
<script type='text/javascript'>
var auto_refresh = setInterval(function(){
$('#load_rating_average').load('get_average_rating.php?b_id=<?php echo $row['b_id']; ?>');
},2000);
</script>
<span id=''></span>
</span>
</div>
You can use jQuery css for this, just get the value in javascript and assign it using jQuery
$("#spanId").css("width", "<?php echo $dynamicWidth ?>%"); // give id to span
or
$("#spanId").width("<?php echo $dynamicWidth ?>%");// give id to span
EDIT
you can use ajax request as well,
setInterval(function(){
$.ajax({
url: 'get_average_rating.php',
type: 'GET',
data: { 'b_id' : <?php echo $b_id ?> },
success: function(width){ // assumed width = 75 (numeric o/p)
// apply width to spanId
$("#spanId").css("width",width + "%");
}
})
},2000);
This one Worked thanks for sharing.
var auto_refresh = setInterval(
function()
{
var dt;
$.get("get_average_rating.php?b_id=<?php echo $row['b_id']; ?>", function(data){
dt=data;
$("#load_rating_avg").css("width", dt +"%");
});
}, 2000);

How to create load more data in blog in jQuery AJAX and PHP from database

I need help with a button for loading more data from the database. I've found examples, but too bad ones. Here is what I have so far:
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.tutorial_list').append(html);
}
});
});
});
You can follow below technique to load more data with just replacing morebox html.
blog.php
<div class="tutorial_list">
<!-- LOAD YOUR PHP BLOG DATA -->
<div class="loading"><img src="fb-load.gif"/></div>
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
</div>
<script>
$(document).on('click', '.show_more', function() {
{
var ID = $(this).attr("id");
if (ID) {
$('.morebox').hide();
$('.loding').show();
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastpost=" + ID,
cache: false,
success: function(html) {
$('.loading').hide();
$('.tutorial_list').append(html);
$("#show_more" + ID).remove(); // removing old more button
}
});
} else {
$(".morebox").html('The End'); // no results
}
return false;
});
</script>
ajax_more.php
<!-- LOAD YOUR PHP BLOG DATA WITH lastpost ID and remember to add below code for load more -->
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>

ajax a href onclick get php variable and execute php file

Before I ask this question, I have already referred to the example of this question. However, it seems doesn't work. Without using ajax, I can get my post deleted but after implement ajax, the deleteAtc.php seems to be not working.
My delete page code (delete.php)
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> Delete<br />
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = <?php echo $article['article_id']; ?>;
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id"+id+,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
<div id="success"></div><br />
<?php } ?>
While my deleteAtc.php code:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
echo "Article deleted";
}
}
?>
What I'm trying to do here is to delete the record without redirect to deleteAtc.php, it will remove out the record and replace Article Deleted
May I know where did I go wrong in ajax side?
Please refer below for updated question
Based on the answer below, here is my updated code:
delete.php
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
deleteAtc.php
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
Somehow, if I delete two record at a time, only the first record echo the result, the second result deleted doesn't echo out the result.
Am wondering, possible to add jquery animation to .show the success message and .hide the record deleted?
First of all IDs are not meant to be duplicated, use class selector instead. Also you could make use of custom data attributes to store the id of the article.
Try
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
Script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
And in server side
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
The above script won't work you have to change like below. You are repeating the same identifier function again and again. Keep the jquery script out of foreach loop. You have to add the class property with the article id.
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> <a href="#" id="link" class='<?php echo $article['article_id']; ?>' >Delete</a><br />
<div id="success"></div><br />
<?php } ?>
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = $(this).prop('class');
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+id,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
You create several links with id="link". ID must be unique.
You have to write
id="link<? echo $article['article_id']; ?>"
as well as
$('#link<? echo $article["article_id"]; ?>').click(function() {...})
<script language="javascript">
$(document).ready(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this record? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "products/delete_record.php",
data: info,
cache: false,
success: function(){
setTimeout(function() {
location.reload('');
}, 1000);
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
//location.reload();
});
});
</script>

Loading a facebox modal window after an ajax request

this is what i have in the head tags of my html page to load the facebox plugin:
<!-- This is for the facebox plugin to work -->
<link href="<?php echo base_url();?>styles/facebox/src/facebox.css" media="screen" rel="stylesheet" type="text/css" />
<script src="<?php echo base_url();?>styles/facebox/lib/jquery.js" type="text/javascript"> </script>
<script src="<?php echo base_url();?>styles/facebox/src/facebox.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox({
loadingImage : "<?php echo base_url();?>styles/facebox/src/loading.gif",
closeImage : "<?php echo base_url();?>styles/facebox/src/closelabel.png"
})
})
</script>
this is the code for my div
<?php if(isset($$j)) : foreach($$j as $row) : ?>
<div class="single-result" id="single-result">
<div class="name"><?php echo $row->Name; ?></div>
<div class="description"><?php echo $row->Description; ?></div>
</div>
<?php endforeach; ?>
<?php else : ?>
error here
<?php endif; ?>
what i am wanting, is some ajax code that calls a function when the user clicks on the div id="single-result" so that it makes an ajax call to a php controller that gets the data from the database and then loads the view into a facebox modal window.
The part i am unsure about is how to make it load into a facebox modal window, l know how to use ajax calls to make it send data to a file and then load a view into a certain div on the page, l just want it to load it into the modal window instead of a certain div on the page.
Is this possible at all? (also i am using codeigniter for the php framework)
here is my ajax code which would load the ajax request results into the content-right div when the user clicks on div.
<script type="text/javascript">
$("#single-result").click(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#content-right').html(msg);
}
});
return false;
});
</script>
<!-- END -->
how do i modify this code above to make it work with going into a facebox modal window? I know facebox provides this code below, but i have no idea what to do with it?
jQuery.facebox(function() {
jQuery.get('code.js', function(data) {
jQuery.facebox('<textarea>' + data + '</textarea>')
})
})
It's not really clear what you're after...
If what you want is to have the data returned from the ajax POST to be populated into a facebox, simply call facebox on the success callback of the ajax post:
$("#single-result").click(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
jQuery.facebox(msg);
})
});
alternatively, it looks like if you want the facebox loading graphics while the post is processed, you can wrap the ajax POST in facebox function:
$("#single-result").click(function() {
jQuery.facebox(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
jQuery.facebox(msg);
})
});
})
})

Deleting a list item <li> with jquery?

I'm trying to delete a li item using jquery, but its not working. Here's my code:
the html file:
<li>
<img class="avatar" src="images/$picture" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>$username</strong> $auto
<div class="date">$rel</div>
$reply_info
<div class="date"></div>
<a class ="delbutton" href="#" id = $id> Delete </a>
</div>
<div class="clear"></div>
</li>
The jquery file:
$(function () {
$(".delbutton").click(function () {
var del_id = element.attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
the delete.php file:
<?php
include("includes/connect.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
There is no element in your HTML with a class of record. I would try something like this:
<li class="record">
<!-- a bunch of other stuff -->
<a class="delbutton" href="#">Delete</a>
</li>
then in the JS:
$(function ()
{
$(".delbutton").click(function ()
{
if (confirm("..."))
{
$.ajax({ /* ... */});
$(this).closest(".record").fadeOut();
}
return false;
});
});
If your div look like this:
<ul>
<li>One | <a href='#' class='delete'>Delete</a></li>
<li>Two | <a href='#' class='delete'>Delete</a></li>
<li>Three | <a href='#' class='delete'>Delete</a></li>
<li>Four | <a href='#' class='delete'>Delete</a></li>
</ul>
jQuery:
jQuery(document).ready(function(){
jQuery('.delete').live('click', function(event) {
$(this).parent().fadeOut()
});
});​
Check: http://jsfiddle.net/9ekyP/
EDIT:
You can remove your li after getting response in success function something like this:
jQuery(document).ready(function(){
jQuery('.delbutton').live('click', function(event) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
$(this).parent().parent().fadeOut();
}
});
});
});​
There are several issues with your code...
element.attr("id") references undeclared element but this should probably be $(this).attr("id")
The <li> block has no class ".record" either
EDIT: You only fade your <li> but do not actually remove it from the DOM (don't know if this was deliberate though)
The <a>'s ID is not quoted (and not escaped either... as are the other strings you insert in PHP (EDIT) and the ID you use in your delete script - this is very dangerous as it allows cross-site scripting / XSS and SQL injection as TokIk already pointed out)
PHP:
echo '<li class="record">
<img class="avatar" src="images/'.htmlentities($picture).'" width="48" height="48" alt="avatar" />
<div class="tweetTxt">
<strong>'.htmlentities($username).'</strong> '.htmlentities($auto).'
<div class="date">'.htmlentities($rel).'</div>'.htmlentities($reply_info).'<div class="date"></div> <a class="delbutton" href="#" id="'.htmlentities($id).'"> Delete </a>
</div>
<div class="clear"></div>
</li>';
JavaScript:
$(document).ready(function() {
$(".delbutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
EDIT: Delete script (note the additional error check that $_POST['id'] exists and the pseudo-function for quoting the ID):
<?php
include("includes/connect.php");
if( isset($_POST['id']) ) {
$id = quote($_POST['id']);
$sql = "delete from {$prefix}notes where id='$id'";
mysql_query( $sql);
}
?>
I am assuming that '.records' is the container.
You can pass through your ID value to make <li> unique, result being:
<li id='record_12'>
//CONTENT
</li>
<li id='record_13'>
//CONTENT
</li>
And change your SUCCESS script to the following:
$(".delbutton").click(function(){
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
//Getting the unique LI and fading it out
$('#record_' + del_id).fadeOut();
}
});
Your code works fine well.I was trying to code a form that has multiple textbox, then after each textbox threre will be link called add which POST call the other php called addnew.php.
In addnew.php data will we added to database(postgres). But I am geting problem while getting the post variable itself.
this is my code for form (I will chage for multiple textbox once it works fine)
script:
<script type='text/javascript'>
$(window).load(function() {
jQuery(document).ready(function() {
jQuery('.add').live('click', function(event) {
var da = $('form#myform').serialize();
alert(da);
$.ajax({
type: "POST",
url: "addnew.php",
data:da,
success: function(data) {
if (data === "ok") {
$(this).parent().fadeOut();
$('#results').html(data);
}
else {
alert(data);
}
}
});
});
});
});
Form
<form name='myform' id='myform'>
<input name='da' type='text' id='da' value='none'>
<a href='#' class='add'>Add</a>
</form>
addnew.php code here
<? php
if( isset($_POST['da']) )
{
echo (da);
}
?>

Categories