This script displaying the dynamic content for once thereafter its not working
Here is the code:
$(document).ready(function(){
$('.getmore').on('click',function(){
var last_id = $(this).attr('id');
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/getmore.php',
data: 'last_id='+last_id,
beforeSend: function(){
$('.getmore').html('<img src="../images/loader.gif" alt="Loading..." />');
},
success: function(data){
$('.getmore').remove();
$('#comments').append(data);
}
});
});
});
Here is the complete php code:
<?php
mysql_connect('localhost','root','') or die('Error... Couldnt connect..');
mysql_select_db('mydb') or die('Error... Couldnt select the Db..');
$records = mysql_query(' SELECT * FROM `compare_post_comments` WHERE `post_id`=37 limit 5 ');
if(mysql_num_rows($records)){
echo '<div id="ajax_comment">';
echo '<ul id="comments">';
while($data = #mysql_fetch_array($records) ){
echo '<li>'.$data['comments'].'</li>';
$last_record = $data['sno'];
}
echo '<li class="getmore" id="'.$last_record.'">Get More</li>';
echo '</ul>';
echo "<span id='cmmnts'></span>";
echo '</div>';
}
?>
getmore.php code
<?php
if( ( isset($_POST['last_id'])!=null ) && $_POST['last_id']!="" ){
$last_id = $_POST['last_id'];
//echo "::".$last_id;
$qry = " SELECT * FROM `compare_post_comments` WHERE `post_id`=37 and sno > ".$last_id." limit 5 ";
//echo "::".$qry;
$comments = mysql_query($qry) or die('Error..');
if( mysql_num_rows($comments) ){
while( $data = mysql_fetch_array($comments) ){
echo "<li>".$data['comments']."</li>";
$last_id=$data['sno'];
}
echo "<li class='getmore' id='".$last_id."'>Get More</li>";
}else{
echo "<li class='nomore'>No More</li>";
}
}else{
echo "<li class='nomore'>No More</li>";
}
?>
ajax call working for once, thereafter its not clickable.
I dont have much knowledge about ajax and javascript, explanation is appreciated.
Try the deferred syntax of on instead:
$(document).on('click', '.getmore', function...
This will survive DOM changes. This answer presumes that your loaded data contains an object with class="getmore", as you are removing it from the DOM on success. If not you need to remove the remove as suggested by NewInTheBusiness, but probably replace it with empty() instead to remove the loading progress.
Note I have recently found problems with the version of on that only takes the event and function. In jQuery 1.10.3 it seems to not be firing when it should.
It's because you remove the getmore class after success.
Remove this line of code:
$('.getmore').remove();
Check your firebug console for any error
Remove this line $('.getmore').remove();
Delegate the click event to the element's static parent or to the document.
Try,
$(document).on("click",'.getmore', function( event ) {
});
Just try live or bind in-place of "on" :
$('.getmore').live('click',function(){
}
or
$('.getmore').bind('click',function(){
}
Related
Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.
Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>
So I got a list of names which are dragable. I have a list of checkboxes with help them I can filter that names. After checking checkbox I make an ajax call. Here is how my list is look like(it is an accordion):
<div id="myAccordion">
<?php
echo "<h3>Names</h3>";
echo '<ul class="source">';
echo '<div id="getData"></div>';
echo '<div id="hideData">';
$sql = "SELECT * FROM user ORDER BY `username` ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$name = $row["username"];
$user_type = $row["user_type"];
echo"<li class='item'><span class='closer'>x</span>".$name."</li>";
}
}
else
{
echo "0 results";
}
echo '</div>';
echo '</ul>';
?>
</div>
So after calling ajax i call filter.php and print that:
<?php
require_once('inc/database_connection.php');
include 'model/model.project.php';
if($_POST['user_type'])
{
//unserialize to jquery serialize variable value
$type=array();
parse_str($_POST['user_type'],$type); //changing string into array
//split 1st array elements
foreach($type as $ids)
{
$ids;
}
$types=implode("','",$ids); //change into comma separated value to sub array
echo "<br>";
$result = getUserTypeChecked($types);
?>
<div id="getData">
<?php
while($rows=mysqli_fetch_array($result))
{
//echo $rows['username']."<br>";
$name = $rows["username"];
echo '<ul id="source">';
echo"<li class='item'><span class='closer'>x</span>".$name."<div class='green'></div></li>";
echo '</ul>';
}
?>
</div>
<?php
}
?>
So the problem is name stops being draggable after ajax call. How can I achieve this?
EDIT
Ok, so here is my js for accordion:
<script>
$("#myAccordion").accordion({heightStyle:"content", collapsible:true});
$("#myAccordion li ").draggable({
appendTo: "body",
helper: "clone",
refreshPositions: true,
start: function (event, ui) {
sourceElement = $(this);
},
});
</script>
And ajax call:
<script>
$(document).ready(function(){
//$('#getData').hide();
$('.ids').on('change',function(){ //on checkboxes check
//sending checkbox value into serialize form
var hi=$('.ids:checked').serialize();
if(hi){
$.ajax({
type: "POST",
cache: false,
url: "filter.php",
data:{user_type:hi},
success: function(response){
//$('#getData').show();
document.getElementById('getData').style.display = "block";
document.getElementById("getData").innerHTML = response;
$('#hideData').hide();
}
});
}
else
{
document.getElementById('getData').style.display = "none";
$('#hideData').show();
}
});
});
</script>
JS works with loaded DOM on page. This means when ever you call sort function, HTML elements must be present on the page.
Let's try to understand what's going on here?
All html elements loaded first.
JS trigger and all dragging functionality to loaded DOM.
Ajax call to fetch new data and replace old DOMs.
Now drag functionality stops working.
why? because JS drag function run on old DOM and currently it has been removed.
need to call the drag function again on new loaded DOM.
NOTE: make sure elements or HTML must be loaded before calling JS drag function.
reinitialize you plugins after appending the new html in the success function:
document.getElementById("getData").innerHTML = response;
$('#hideData').hide();
$("#myAccordion").accordion({heightStyle:"content", collapsible:true});
$("#myAccordion li ").draggable({
appendTo: "body",
helper: "clone",
refreshPositions: true,
start: function (event, ui) {
sourceElement = $(this);
},
});
i need to know how on earth to get my checkbox value from PHP that is in a loop and also might be in DOM. I have to put that checkbox inside the loop to make it being shown on each row of databases. I tried to call it back using different method but none success. The last part is javascript but i don't have any clue how to do that.
My code for javascript index.php.
function ajaxSearchUpdater(p){
$("#result").show();
var x = $("#search").val();
var y = $("#edulevel").val();
var pagelim = $("#pagefpe").val();
var pagenumber = p;
var checkb = $(".sBorrow").val()
$.ajax({
type:'POST',
url:'userres.php',
data:'q='+x+'&e='+y+'&pagelim='+pagelim+'&pageno='+pagenumber+'&checkb='+checkb,
cache:false,
success:function(data){
$("#result").html(data)
}
});
}
$(document).ready(function(e) {
ajaxSearchUpdater(1); // fires on document.ready
$("#search").keyup(function() {
ajaxSearchUpdater(1); // your function call
});
$("#edulevel").click(function() {
ajaxSearchUpdater(1); // your function call
});
$("#pagefpe").click(function() {
ajaxSearchUpdater(1); // your function call
});
$('.sBorrow').on('change', function(){
var checkBorrow = $(event.target);
var isChecked = $(checkBorrow).is(':checked');
alert("test");
alert(isChecked);
alert('checkbox'+checkborrow.attr('id')+'is checked:'+isChecked);
});
});
$(document).ready(function() {
$('.sBorrow').on('change', function(event) {
var checkbox = $(event.target);
var isChecked = $(checkbox).is(':checked');
alert('checkbox ' + checkbox.attr('id') + ' is checked: ' + isChecked);
});
});
My code for the checkbox in PHP userres.php
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-blackice' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr>";
echo "<th>No.</th>";
echo "<th>No.Matric</th>";
echo "<th>Name</th>";
echo "<th>Programme</th>";
echo "<th>Title</th>";
echo "<th>Thesis Level</th>";
echo "<th>Serial Number</th>";
echo "<th>Availability</th>";
echo "<th>Select book (Max 3)</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($r as $row){
$sBorrow = $_SESSION['sBorrow'];
echo "<tr align='center'><td>". ($startrow+1) ."</td><td>". $row['matricno'] ."</td><td>". $row['studentname'] ."</td><td>". $row['programme'] ."</td><td>". $row['title'] ."</td><td>". $row['thesis_level'] ."</td><td>". $row['serialno'] ."</td><td>". $row['bavailable'] ."</td><td>
<form method='post'>
<input type='checkbox' name='sBorrow' id='sBorrow' class='sBorrow' value='". $row['serialno'] ."'>
</form></td></tr>";
$startrow++;
//echo $row['education_level'];
}
echo "</tbody>";
echo "</table>";
I don't know what to do since i'm calling that page from ajax and uhh how should i explain this.
You know index.php -> userres.php -> index.php using ajax.
for javascript on the bottom part is what i have done and i dont think its right. I tried to create one other document ready for this checkbox but still even alert not showing up. I'm confused. please help T_T
I try to make a query from database to get the list of users based on their country using php/mysql and jquery.
I have a mysql query that extracts the countries form database in a select options field. After this, i put a jquery code to automatically get the table with users based on the selected country. This is how jquery code looks like:
<script>
$( "#tara" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += "<table class='table table-bordered table-striped'>" +
"<thead><tr><th><p><?php echo _('Tara');?></p></th></tr></thead>" +
"<tbody>" +
"<?php
$variabilatara = 182;
$test = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") ?>" +
"<?php while($row=mysql_fetch_object($test))
{
echo "<tr>";
echo "<td><p>$row->nume</p></td>";
echo "</tr>";
}
?>" + $( this ).val() + " ";
});
$( "#testare" ).html( str );
})
.change();
</script>
My question is: How to put the $( this ).val() into php instead of $variabilatara, so it will looks something like: $variabilatara = $( this ).val(); and the sql query will modify on change of selected country. Thank you!
What you are trying to do is called AJAX. Sounds complicated, but it really isn't. See these examples for a simplistic explanation. Do not just look at them -- copy/paste to your server and make them work. Change the values. See how it works - really very simple.
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Your code is a bit difficult for me to follow, but should be refactored something like this. (I am unsure where strTara figures in the code, but I'm sure you will be able to figure it out from here).
javascript/jQuery:
var strTara = <?php echo _('Tara');?>
$( "#tara" ).change(function () {
selVal = $(this).val();
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'variabilatara=' + selVal,
success: function(data){
var tblHead = "
<table class='table table-bordered table-striped'>
<thead><tr><th><p>strTara</p></th></tr></thead><tbody>
";
$( "#testare" ).html( tblHead + data );
}
});
});
another_php_file.php: (your PHP AJAX processor file)
<?php
$var = $_POST['variabilatara'];
$out = '';
$result = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") or die(mysql_error());
while($row=mysql_fetch_object($result)){
$out .= "<tr>";
$out .= "<td><p>" .$row->nume. "</p></td>"; //<== fixed
$out .= "</tr>";
}
$out .= '</tbody></table>'; //<== fixed
echo $out;
?>
I want to make one javascript function, but I cannot call my function name right when i click on it(show_more_in_month_0/1/2).
this is my code
$i = 0;
foreach ($data as $row){
echo '<td><span class="glyphicon-plus show_more_in_mont_'.$i.'"></span><span class="glyphicon-minus_'.$i.'"></span></td>';
echo '<td>';
echo $row[0];
echo '</td><td>;
echo $row[1];
echo '</td><td>';
echo $row[2];
echo '</td><tr>';
$i ++;
}
And this is my script, i just want alert my class name after i call right function name
$(document).ready(function() {
$(".show_more_in_mont_'.$i.'.").click(function(){
alert(show_more_in_mont_'.$i.');
});
});
You are doing it wrong -- $i i suppose its your PHP variable ? well you shouldnt have those in your JS..
Just add as javascript one global class such "show-more-container" and use it to show whatever you want to show
$( document ).ready(function() {
$(".show-more-container").click( function() {
var elementId = $(this).data('id');
alert ('show_more_in_mont_'+elementId);
});
});
Now your html should look like
<div data-id="<?= $i ?>" class="show-more-container">
</div>
Hope this make sense to you :)
EDIT:
If you want to go far -- and call that as a function then do as follow:
window['my_fn_name_as_string'+appendId]()
for this to work the function should be on a Global scope -- on Body or Head and not inside Jquery! if you want to add it to jQuery then make sure you use:
$.function() {
window.my_fn_name_as_string_div = function() { }
}
EXAMPLE:
http://jsfiddle.net/7d23y99b/1/