jQuery AJAX document trigger? - php

My jQuery code:
$('.Img').click(function() {
alert('Test');
});
$().ready(function() {
$.ajax( {
type : 'POST',
url : 'Post.php',
success : function(Response) {
$('#Response').html(Response);
}
}
});
My HTML code:
<div id="Response"></div>
<img class="Img" src="blank.gif" /> [Click Trigger]
My PHP code:
echo '<img class="Img" src="blank.gif" />'; [Ajax from response]
why this image does not trigger from AJAX response?

You need to use .live() here, like this:
$('.Img').live('click', function(){
alert('Test');
});
It doesn't work currently because $('.Img') doesn't find the <img> to attach a click handler to...it didn't exist then, not until the ajax call loaded it, .live() will listen for the click appropriately, even if the element is added later.

Related

How can I send the value of the id through ajax and PHP

I want to pass value of the id of the product to cart.php by using AJAX and display it in a div.cart in index.php but I have no idea how. please help.
Product
Product Description
Add to Cart
$('a').on('click', function(e){
$.ajax({
url:
data:
})
e.preventDefault();
});
Of course you can :) !
So first, let's get things straight. You're showing a list of products as <div class="thumbnail"> form, right ? So your PHP/HTML should look a bit like this in reality :
<?php
foreach($database_recordset as $row) {
echo '
<div class="thumbnail>
<img src="'.$row['img_src'].'" alt="'.$row['img_alt'].'" />
<div class="caption">
<h4>'.$row['product_name'].'</h4>
<p>'.$row['product_description'].'</p>
<a id="p-'.$row['id'].'" onclick="addCart(this)">Add to Cart</a>
</div> <!-- You were missing a /div here if I guessed right the structure -->
</div>';
}
?>
so I simply labelled the link p-#ID where #ID is the id of the product from the database and added an onclick event with this as the argument. Now you need a function addCart that will contain the AJAX request.
<script type="text/javacscript">
function addCart(elm) {
// First we need the clean ID of the product
var id = elm.id.split('-')[1]; // We split with '-' as separator and take the second element of the resulting array
$.ajax({
url: "cart.php",
type: "POST", // or GET whatever but POST is usually better
data: { id: id },
success: function(response) {
if (response.status == 'OK') { // You should always test the response of an ajax request
// show a message, update the cart icon or whatever
}
}
});
}
</script>
you need to modify you code something like this. Href need to be removed else it will redirect you on that page. Give below is a sample of your code
<div class="thumbnail>
<img src="" alt="" />
<div class="caption">
<h4>Product</h4>
<p>Product Description</p>
<a id="id=(id from table products)">Add to Cart</a>
</div>
$('a').on('click', function(e){
$.ajax({
url: cart.php
data:{id:$(this).attr("id")}
})
e.preventDefault();
});
You need to stop the browser following the link, then make an ajax request and insert the response into the target div.
You can use jquerys load method to acheive that in a single call:
$('a.clickme').click(function(ev){
ev.preventDefault();
$('div.cart').load($(this).attr('href'));
});
Note i added a class to the link, else your code would capture all link clicks including site navigation etc
Add to Cart

jQuery: Change an element value after Ajax Call

I am trying to change the value of a span after using jQuery.ajax.
JavaScript
$(document).on('click', '.kssico', function(event) {
var for_uid = $(this).parents("li").attr('data'),
for_name = $(this).parents("li").attr('unme'),
dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300") {
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else {
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});
HTML
<li class="mispan main-span" >
<div class="thumbnail">
<h3 class="miheader">Dewashree Singh</h3>
<a >
<div class="miprofile-pic-cnt" ></div>
</a>
<div class="caption">
<p>
<a href="#" class="btn kssico miclickks">
<img src="/lisps.png"><span class="mi-val">0</span>
</a>
<a href="#" class="btn bdico miclickbd">
<img src="/besd.png"><span class="mi-val">1</span>
</a>
</p>
</div>
</div>
</li>
When I click on a.miclickks it should complete the Ajax call and return a value too be placed inside the span on the button anchor. However, nothing is being changed!
jsFiddle
I don't know what your whole code looks like, but you should be able to modify this to do what you are trying to:
$('#id').on('click', function() {
var that = this;
$.ajax({
url: 'wherever.php',
success: function(html) {
$(that).find("li span.mi-val").html(html);
}
});
It looks like you have two problems. The first is that as #Barmar posted above, mi-val is a child of micclickks, not a parent. The second is that your ajax complete function is asynchronous, so $(this) isn't what you expect it will be. Both of these are solvable though.
Your code is a bit messy and your html is missing the proper attributes, but this is I think roughly what you want:
$('.kssico').on('click', function(event) {
var for_uid = $(this).parents("li").attr('data'); //the li element in your html doesn't have a data attribute
var for_name = $(this).parents("li").attr('unme'); //the li element in your html doesn't have a 'unme' attribute
var dataString = "for_uid=" + for_uid + "&for_name=" + for_name;
$.ajax({
type: "POST",
context: this,
url: "include/ajax.php",
data: dataString,
success: function (html) {
if(html=="300")
{
$('#myModal .modal-body p').html("Error Please Try Again.");
$('#myModal').modal('show');
}
else
{
$(this).parents("li span.mi-val").html(html);
$('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
$('#myModal').modal('show');
}
}
});
});

ZF ajax general how to

I have some trouble with zend framework and ajax.
In a view I have a div with tabs. When I click on the UnitTab "#tabUnits" the Unit view is displayed with a list of items. There is also a link to add new Units, so the add view is loaded into the tab.
The link to add an unit is:
<a id="addUnit" href="idBuilding/<?= $this->idBuilding ?>" href="#"><img width="16" height="16" src="/images/icons/fugue/plus-circle-blue.png"></a>
and the ajax call is :
$(document).ready(function(){
var url = '/unit/add/'+$("#addUnit").attr('href');
// ADD
$("#addUnit").click(function(event){
event.preventDefault(); // link is not executed
$.ajax({
url: url,
type: 'GET',
success: function(data) {
$("#tabUnits").html(data);
},
error: function(){
alert('An error occurred, please check before continue...');
}
});
});
});
When no error occurred the units are added and the list is displayed again.
How can I now do the same when I want to edit an Unit, knowing that the id is changing?
It has not much in common with ZF, it's more just jQuery. If you want to use the same AJAX call for more elements, just change url variable. Something like (not tested):
<a class="link" data-url="add" id="addUnit" href="idBuilding/<?= $this->idBuilding ?>" href="#"><img width="16" height="16" src="/images/icons/fugue/plus-circle-blue.png"></a>
<a class="link" data-url="edit" id=editUnit" href="idBuilding/<?= $this->idBuilding ?>" href="#"><img width="16" height="16" src="/images/icons/fugue/plus-circle-blue.png"></a>
$(document).ready(function() {
var url;
// ADD
$(".link").click(function(event){
event.preventDefault(); // link is not executed
url = '/unit/' + $(this).data('url') + '/' + $(this).attr('href');
$.ajax({
url: url,
type: 'GET',
success: function(data) {
$("#tabUnits").html(data);
},
error: function(){
alert('An error occurred, please check before continue...');
}
});
});
});
More about data parameters: http://api.jquery.com/data/#data-html5

Clone a draggable div

This script to clone a draggable has a weird effect. I create a clone of a draggable div and then remove the original. When I drag the clone and drop it on a second container, two draggables appear: the original and the clone appended to the body. Neither is draggable after that. What could be the problem?
Here is the code where the element is created and made draggable. It is echoed from a php script when the page is loaded.
// Add link with tools
echo ' <div id="'.$url['ID'].'" class="link"> <img class="link_handle" src="http://www.google.com/s2/favicons?domain='.$urlico.'" align="middle" /> <a title="Delete" class="link_button_delete" href="#" onClick="delete_link(\''.$url['ID'].'\', \''.$node['ID'].'\');"> </a> </div>';
// Make link draggable
echo "<script type='text/javascript'>\n";
echo ' $("#'.$url['ID'].'.link").draggable({
handle: ".link_handle",
helper: function() {
$copy = $(this).clone();
$(this).remove();
return $copy;
},
appendTo: "#page" ,
scroll: false,
revert: true,
});';
echo "</script>\n";
Here is the HTML where the script is called.
<div id="page"> <!-- Begin page div -->
<script type="text/javascript">
$(document).ready(function() {
// Make ajax call to recreate linkcards from XML data
$.ajax({
url: "get_nodes.php",
type: "POST",
data: { },
cache: false,
success: function (response) {
if (response != '')
{
$("#page").append(response);
alert(response);
}
}
});
});
</script>
</div> <!-- End page div -->
I don't have this accessible, it is only on my local pc.
Found out that if I don't remove the original the code works. Ideally, I'd prefer the behavior where the original is visually dragged from the first container to the second. This can only be done if the container does not have overflow: hidden. With cloning the original cannot be delete. This is not ideal but works. Here is the code that worked without the line $(this).remove();.
// Make link draggable
echo "<script type='text/javascript'>\n";
echo ' $("#'.$url['ID'].'.link").draggable({
handle: ".link_handle",
helper: function() {
$copy = $(this).clone();
return $copy;
},
appendTo: "#page" ,
scroll: false,
revert: true,
});';
echo "</script>\n";

Request after request ajax and jquery using $.ajax

I am very new to Jquery and ajax so please be kind.
i am making a request to the server using jquery $.ajax, the ajax pulls the image from the image id stored on the server/database when the user clicks on a thumbnail of which there are loads. All works fine except with the following code i can only click on any of the thumbnails once to load the big picture from the database, after that no other thumbnail works.
Can anyone help?
<script type="text/javascript" src="jquery-1.5.2.min.js"></script>
<script type="text/javascript">
function getimage(data){
var img = new Image();
$(img).load(function(){
$(img).hide();
$.ajax({
type: "GET",
url: "name.php?",
data: "name=" + data,
success: function(){
$("#loader").removeClass("loading").append(img);
$(img).fadeIn("slow");
}
});
}).attr("src", data +".jpg");
}
</script>
</head>
<body>
<h1>Image Loading</h1>
<div id="loader" class="loading">
</div>
<a href="name.php?name=image1" id="image1" onclick="getimage('image1'); return false;"/><img src="image1_th.jpg" /></a>
<a href="name.php?name=image2" id="image2" onclick="getimage('image2'); return false;" /><img src="image2_th.jpg" /></a>
<a href="name.php?name=image3" id="image3" onclick="getimage('image3'); return false;"/><img src="image3_th.jpg" /></a>
try this:
function getimage(data){
var img = new Image();
$(img).load(function(){
$(img).hide();
$.ajax({
type: "GET",
url: "name.php?",
data: "name=" + data,
success: function(){
$("#loader").html(''); // you need to remove the old image
$("#loader").removeClass("loading").append(img);
$(img).fadeIn("slow");
}
});
}).attr("src", data +".jpg");

Categories