I'm still searching solution for getting values from dynamic created object.
Follwing code generates dynamic object from zip2.php
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var q = $("#k").val();
$.ajax({
type: "POST",
url: "zips.php",
data: "q="+ q,
dataType: "html",
success: function(res) {
$("#result").html(res); $('#result').trigger('create');
},
});
});
});
<div data-role="content">
<div id="result"></div>
</div>
It created object like this format.(contents of zips.php)
<? echo " <div><ul id='zips' data-role='listview' data-inset='true' data-theme='c'>";
while($row = mysql_fetch_array($result)) {
$out .= "
<li>
<a name='submit_button' href='#mainPage'><span class='zip1'>$zip1</span>-
<span class='zip2'>$zip2</span><br />
<span class='address'>$row[zp_sido] $row[zp_gugun] $row[zp_dong] $row[zp_bunji] </span></a>
</li> \n";
}
echo $out."</ul>";
?>
And this script get the text() value from dynamic object and insert it to form.
<script>
$(document).ready(function() {
$('a[name=submit_button]').click(function(){
var inputVal1 = $('.zip1, this).text();
var inputVal2 = $('.zip2', this).text();
var inputVal3 = $('.address', this).text();
$('div input[name=zip_code1]').val(inputVal1);
$('div input[name=zip_code2]').val(inputVal2);
$('div input[name=address1]').val(inputVal3);
</script>
<div>
<form>
<input type="text" id='zip_code1' name="zip_code1" > - <input type="text" id='zip_code2 name="zip_code2"><br />
<input type="text" id='address1' name="address1">
</form
</div>
The problem is that "var inputVal1 = $('.zip1, this).text();" gets null from dynamic objects class name "zip1".
Instead of
$('a[name=submit_button]').click(function(){..
use this:
$('#result').on('click', 'a[name=submit_button]', function(){..
As you a[name=submit_button] append to DOM after page load, dynamically via ajax request, so you need delegate event handler to that, ordinary event binding will not work here.
Read more about .on()
Note
For general binding syntax of .on() is like:
$(target).on(eventName, handlerFunction)
but for delegate event systax is
$(container).on(eventName, target, handlerFunction)
Here container is the Static-element that belongs to DOM at page load and contains target and both container and target are valid jQuery selector.
Related
This is my HTML PAGE
I want to send some values with ajax then I want to get them with ajax response but I can't see any character in my div which called with id=result . Where is the problem?
<html>
<head>
<!-- JQuery v1.8.2 -->
<script src="theme/scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div class="row-fluid">
<div class="span4">
<input type="text" id="title"/><br>
<textarea rows="10" cols="50" id="content"></textarea><br>
<input type="submit" id="gonderBtn" name="gonderBtn" />
<div id="result"></div>
</div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#gonderBtn").click(function(){
var title = $("title").val();
var content = $("content").val();
$.ajax({
url: "deneme_action.php",
dataType: "html",
type: 'POST',
data: {
title: title,
content: content
},
success: function(data){
$("result").html(data);
}
});
});
});
</script>
</body>
</html>
deneme_action.php
<?php
if(isset($_POST["gonderBtn"])){
$result = "Sonuc:".$_POST["title"];
echo "Selam:".$result;
}
else{
echo "no post";
}
?>
Because you don't have a tag with class="result" but you have a tag with id="result".
Either change the jQuery selector to:
$("#result").html(data);
Or the div tag to:
<div class="result"></div>
and selector to:
$(".result").html(data);
And you are not sending gonderBtn with the POST - fix it too:
$("#gonderBtn").click(function(){
var title = $("#title").val();
var content = $("#content").val();
var gonderBtn = $(this).val();
$.ajax({
url: "deneme_action.php",
dataType: "html",
type: 'POST',
data: {
title: title,
content: content,
gonderBtn: gonderBtn,
},
I've also fixed the selectors for input and textarea too.
Check this line:
echo "Selam:"+$result;
Here the plus operator is an error so the php script is not returning anything.
Check this link that documents the use of + operator in php.
var title = $("title").val();
var content = $("content").val();
should be
var title = $("#title").val();
var content = $("#content").val();
You will also need to change:
$("result").html(data);
to
$("#result").html(data);
You should also wrap your inputs in a form.
Edit:
You might want to give your button input a value.
<input type="submit" id="gonderBtn" name="gonderBtn" value="go!" />
Edit 2:
You will also need to give your html elements a name.
<input type="text" id="title" name="title"/><br>
<textarea rows="10" cols="50" id="content" name="content"></textarea><br>
You're not selecting your #result div properly, add a # before
$("#result").html(data);
the same goes for all your selectors
var title = $("#title").val();
var content = $("#content").val();
Since your ajaxing your form you'll have to manually pass your button parameter, although an ajax parameter would be more appropriate.
data: {
title: title,
content: content,
gonderBtn: 'gonderBtn'
},
echo "Selam:"+$result;
In php use "." to concatenate strings.
echo "Selam:".$result;
I have code like this :
<?php
$username = 'johndoe';
?>
<head>
<script>
...
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});
...
</script>
</head>
<body>
...
<li><input type="hidden" value="001" class="block-hidden-input" />
<a href="#" id="manage-1" class="manage-content-link">
<img src="images/web-block/web-block1.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
<li><input type="hidden" value="002" class="block-hidden-input" />
<a href="#" id="manage-2" class="manage-content-link">
<img src="images/web-block/web-block2.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
...
</body>
as you can see there, every time user click "manage-content-link" class, either manage-1, manage-2, ... or even manage-X (multiple li tags) jQuery will load "file-XXX.php". which XXX is actually value of hidden input in li tag.
but that "file-XXX.php" requires $username from PHP tags and ID itself, that is "manage-X". how to pass this 2 variables needed by "file-XXX.php", one from PHP and other from ID's?
Use jQuery's .ajax() instead of .load(): http://api.jquery.com/jQuery.ajax/
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val(),
this_id = self.attr('id');
$.ajax({
url: "file-" + file + ".php",
data: { username: "<?php echo $username;?>", id: this_id },
context: this,
success: function(data) {
$(this).next(".manage-content-wrap").find(".manage-content").html(data);
}
});
e.preventDefault();
});
If you want to keep the script external, you couldn't rely on php to echo the $username inside the script. So, you could add the username a few ways. You can make a hidden input somewhere in the page with the value equal to the username; you could attach the username to an element (like the body) as a data-username attribute; or you could just have a script block in the header that purely defined the username. For example:
<input type="hidden" name="username" value="<?php echo $username;?>>
Or:
<body data-username="<?php echo $username;?>">
Or:
<head>
<script>
var username = "<?php echo $username;?>";
</script>
</head>
In your <body> you can add a hidden field
<input type="hidden" value="<?=$username?>" id="username" />
and in your jquery,
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
var username = $("username").val(); //use this variable where ever you want
var ids = $(this).attr('id'); // this is the id
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php?id="+ids+"&username="+username); //and in php file usee $_GET
e.preventDefault();
});
$('a.manage-content-link').click(function (e) {
var self = $(this);
file = self.prev('.block-hidden-input').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});
Instead of passing username from script, i would suggest you store username in a session and get that value inside php using $_SESSION['username'] otherwise it will cause you security issue in the future.
DEMO
I have buttons and divs and in each part I have them with the same ID I want to get the ID of button and use it for refreshing the div html.how should I write the * section?
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
*********I HAVE PROBLEM HERE**************
$('how to get the id of the div from var id of button above?').html(html);
}
});
});
});
Div:
Downloaded:<div id="<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
Button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
If I get class It will update the whole divs I want to update just the div realted to the button
You cannot have the same id on both the button and the div, id values must be unique in a document.
What I'd probably do is put the div's id on the button as a data-divid attribute (all attributes with the prefix data- are valid on all elements as of HTML5, and harmless in earlier versions of HTML), like this:
<input type="button" value="Download" class="button" data-divid="<?php echo $id; ?>" name="dl">
Then change
var id=$(this).attr('id');
to
var id=$(this).attr('data-divid');
...and then use that id var in your success callback (as the callback is a closure created within the context where id is defined, and so the callback has access to id).
Here's a simple example: Live copy | source
HTML:
<div id="div1">This is div1</div>
<div id="div2">This is div2</div>
<div>
<input type="button" data-divid="div1" value="Update div1">
<input type="button" data-divid="div2" value="Update div2">
</div>
JavaScript:
jQuery(function($) {
$("input[type=button]").click(function() {
var id = $(this).attr("data-divid");
// I'll use setTimeout to emulate doing an ajax call
setTimeout(function() {
// This is your 'success' function
$("#" + id).html("Updated at " + new Date());
}, 10);
return false;
});
});
Use the id but prefix them then build the name up...
<div id="div_<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
Then in you're code you have the id used in the buttons already (and also it will be div_), so you can then in you're 'success' just do:
$("#div_"+id).html(html);
change your html to this:
Downloaded:<div id="<?php echo $id; ?>" class="downloaded" ><?php echo $downloadcount;?></div>
then do something like:
var element_id = $(".downloaded").prop("id");
if(element_id = this.id){
$("#"+element_id).html(/* ... */);
}
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$('.count-' + id).html(html); // for class
}
});
});
});
<div class="count-<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
First of all avoid using same IDS.
Then you can use CSS selectors:
$('div.class') //div
$('input[type="button"].youridclass')
You cannot use the id attribute for that purpose, the id cannot be a number (valid html) and thereby id's needs to be unique. Use the data attrib instead.
Try something like:
$('.button').attr('id');
to get the id of the button, then to change it:
$('.button').attr('id',''); //delete previous id if existing
$('.button').attr('id','yourNewId'); //set new id
then to use the new id:
$("#yourNewId").doSomething();
First and foremost, ids should be unique, you'll run into problems, particularly when using jQuery, if you have elements with the same id.
Without seeing your markup it's hard to give you a working example. But you can get the id of the div which corresponds to the clicked button by traversing the DOM.
Example markup:
<div id="example-div">
<input type="button" value="Example" />
</div>
jquery
$('input[type="button"]').click(function() {
console.log($(this).parent('div').prop('id'));
});
// outputs 'example-div'
for your reference check the below link for the various ways that you can use to select the dom elements given the parent element.
jsperf.com/jquery-selectors-context/2
I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});
Here is my jQuery using delegate and ajax:
$(".tweets").delegate("#fav #submit", "click", function(){
var favid = $("#fav input#favid").val();
var favsave = 'favid=' + favid;
alert(favsave);
$.ajax({
type: "POST",
url: "fav.php",
data: favsave,
success: function() {
$('#fav').fadeOut(100);
}
});
return false;
});
The HTML:
<div class='tweets'>
<ul class='entries'>
<li>
<form id='fav' method='post' class='favo' action=''>
<input style='display: none;' type='text' name='fav' id='fav' value='".$row["tweetid"]."' />
<input type='submit' value='Add to Favorites' name='submit' id='submit' />
</form>"
</li>
</ul>
</div>
There is another set of Ajax on the page that is constantly adding to the .entries list, these records that get appended pickup the click function, so that when I click on them the Alerts are shown but the Ajax part of the function doesnt work.
Any ideas? Would .live be better?
"doesn't work" is not the best of all descriptions.
Anyway, it makes no sense to use "absolute" selectors within an delegated event.
By querying $("#fav input#favid").val(); you would get results from all elements with that id
you would only get the first match (since ids are assumed to be unique) (which would be unfortunate just because of multiple id tags)
You should grab the target property from the event object to identify the elements which should get involved.
Example:
$(".tweets").delegate("#submit", "click", function(event){
var $self = $(event.target);
var favid = $self.siblings('#fav');
var favsave = 'favid=' + favid;
$.ajax({
type: "POST",
url: "fav.php",
data: favsave,
success: function() {
$self.closests('#fav').fadeOut(100);
}
});
return false;
});
It's probably not a good idea to have IDs for elements which are created dynamically.
As mentioned, it's no valid HTML markup to have multiple ID tags. Should be classes I guess.