Triggering function from jQueryMobile "slide panel", "list view" - php

In my jQueryMobile app I'm using slider for search part of application. When slider is opened and user writes "word to search" into search panel, list view of found results is printed out in format:
<li><a id='$id'>***search result***</a></li>
its loaded from php search file. On click of this li part of list view I need to trigger onClick function redirecting into another page and create variable. But this onClick trigger is not being picked.
This is pannel with search init:
<div data-role="panel" data-theme="b" id="mypanel" data-position="right" data-position-fixed="true" data-display="overlay">
<input type="search" name="search-mini" id="search-mini" value="" data-mini="true" />
<div id="search_results">
<ul data-role="listview" data-divider-theme="b" data-inset="true" id="sub_cont"></ul>
</div>
</div>
Php which sends search result:
if($uname == $check_uname){
echo "<li id='search_r'>" . "<a href='#'>" . $uname . " : " . " " . $fname . " " . $sname . "</a>" . "</li>";
}else{
echo "<li id='search_r'>" . "<a href='#' id='$id' class='s_result'>" . $uname . " : " . " " . $fname . " " . $sname . "</a>" . "</li>";
}
and jQuery:
$("#cc_page").live('pageshow', function(){
$("#search_r").click(function(){
var search_r = $('.s_result').attr('id');
window.location.href = "http://imes.jzpersonal.com/app/userpanel.html#sfpp_page";
});
});
but still click function is not being triggered. Anyone same experience? Anyone found a correct working way?
Solution:
$("#cc_page").ready(function(){
$("#search_r").live('click', function(){
search_r = $(this).attr('id');
window.location.href = "http://imes.jzpersonal.com/app/userpanel.html#sfpp_page";
});
});

This is not going to work. From what you have explained when you enter "word to search" listview is dynamically populated with li items, same li items that should have a click event on them.
Here's a problem. You are binding a click event in the wrong moment. In your case click event is bind at a pageshow event, and at this point listview is not populated with search results and because of how javascript works future li elements are not going to have a click event on them. Event can not be bind retroactively.
What you should do is to bind a click event only after elements have been appended to a listview.

Related

Stop page refresh on button click

I'm currently developing a system for internal use within my company to allow our service desk team to unlock user accounts/reset passwords.
I've completed the PHP/POST functions for this and have included them with the .load function on the dashboard of my system. This works and the function in question is LDAP account unlocks. The button is clicked, the post form is submitted and it all works fine. However it refreshes the entire page when submitted even though its been loaded via jQuery. I'm struggling to understand why this would happen, and how I can avoid it so I can give the end user successful or unsuccessful messages on button clicks. This is the main aim and is why I have started using JS load functions as I believed this would allow me to do so.
I'm entirely new to jQuery/JSON/JS and if this question is slightly in-descriptive or has an obvious answer apologies.
EDIT:
The way I have included the form is as such:
<div id="lockedout"></div>
<script>
$(document).ready(function(){
$("#lockedout").load('/modules/active-directory/includes/lockedout.php');
});
</script>
And the included form is:
<?php
set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
include ('/core/system/global.ldap.php');
$attributes = array("displayname", "mail", "samaccountname", "lockoutTime");
$filter = "(&(objectClass=User)(lockoutTime>=1)(title=*))";
$search = ldap_search($ldap_conn, $ldap_dn, $filter, $attributes) or die (ldap_error($ldap_conn));
$info = ldap_get_entries($ldap_conn, $search);
?>
<h4><i class="fa fa-lock"></i> Currently Locked Out (<?php echo $info["count"]; ?>)</h4>
<br>
<table class="table table-bordered">
<tbody><tr>
<th>Username</th>
<th>Unlock</th>
</tr>
<?php
for ($i=0; $i<$info["count"]; $i++) {
echo "<tr>";
echo "<td>" . $info[$i]["displayname"][0] . " (" . $info[$i]["samaccountname"][0] . ")</td>";
echo "</form><form method='post' action='/active-directory/' id='" . $info[$i]["samaccountname"][0] . "'></form>";
echo '<input type="hidden" name="dn" value="'. $info[$i]["dn"] .'" form="' . $info[$i]["samaccountname"][0] . '">';
echo "<td><center><button type='submit' id='unlock' name='unlock' class='btn btn-success btn-flat' form='" . $info[$i]["samaccountname"][0] . "'>Unlock </button></center></td>";
echo "</tr>";
}
?> </tbody></table>
This code is attached above the dashboard where i'm doing the JSON import.
<?php
if(isset($_POST['unlock']))
{
$attr["lockoutTime"] = "0";
$userdn = $_POST['dn'];
$result = ldap_modify($ldap_conn, $userdn, $attr);
echo '<script>
$(document).ready(function(){
$("#lockedout").load("/modules/active-directory/includes/lockedout.php");
});
</script>';
}
?>
if you want to submit content to backpage or verify users but not reload the entire page use AJAX.
if you want to simply show some alerts or validate form when you click the button use javascript or its derivatives

Updating Database and Page Content at the Same Time

This is a tough one for me. a total of five documents involved in this process. I can't help but feel that I am over complicating this issue. I asked about this previously and THOUGHT I understood the issue, but then I tried to add a simple "loading" modal to the equation, and it broke. What's worse I can't get it working anymore. I have changed too much. Yes I know I should have backed it up, let's get past that. The one language I cannot change at all in this whole element is my DB language, which is MySql.
What I Want to Happen
Page loads all non-archived submissions. The data is structured so that some but not all data is displayed for each row. At least not until the user clicks the "more info" button. NOTE: THIS IS NOT THE PROBLEM BUT ONLY HERE BECAUSE I HAVEN'T BUILT THIS YET, I WILL FOCUS ON THIS LATER.
After the user has finished using the data from one row, I would like the user to be able to archive the data into the database by changing the "archived" field from 0 to 1. After that is accomplished, I would like the row to disappear. If there is a lag and more than a second or two is needed to accomplish this, then a loading modal should appear that will indicate that the page has received the request and prevents the user from pressing the "archive" button multiple times.
What is Happening Now
When the page loads, all non-archived data is displayed in rows that show some but not all information for each record in a table. When the user clicks the "more info" button nothing happens. Note: Again I am not focusing on this issue I know how to fix this. When the user clicks on the "archive" button, it does nothing, but if they click if multiple times it eventually will bring up the "loading" modal and then refresh the page. The row that should have disappeared is still there, and the record still shows a "0" instead of a "1" as it should.
Final Comments Before Code Is Given
I am open to using other languages as I am a fast learner, I just don't know how to integrate them. But if you do respond with that, please also explain why my way is inferior and what I would have to do to make this work. I am still learning AJAX (very much beginner) and PHP (intermediate . . . I think).
The Code
index.php - abridged without head
<div class="container">
<h1><span class="hidden">Locate My Pet</span></h1>
<h2>Administration</h2>
<p class="lead alert alert-info">Hello There! You can review and archive submitted requests here.</p>
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="text-center">Submissions</h2>
</div><!--/.panel-heading-->
<div id="results"></div><!--To be populated by script-->
</div><!--/.panel .panel-default-->
</div><!-- /.container -->
<footer class="footer">
<div class="container">
<p class="text-muted text-center">© 2016 TL Web Development and Design</p>
</div><!--/.container-->
</footer><!--/.footer-->
<div class="modal fade" id="archiveMessage" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Archiving Submission</h4>
</div><!--/.modal-header-->
<div class="modal-body">
<p>Please wait . . .</p>
</div><!--/.modal-body-->
</div><!--/.modal-content-->
</div><!--/.modal-dialog-->
</div><!--/.modal-->
submission.php
<table class="table table-responsive table-striped">
<tr>
<th>Customer Name</th>
<th>Address</th>
<th>Contact</th>
<th>Pet Info</th>
<th>Tools</th>
</tr>
<?php
require "../_php/connect.php";
$get_all = "SELECT request_id, fName, lName, address, city, state, zip, pPhone, cPhone, email, pName, gender, spayedNeutered, howLost, comments, timeEntered, archived FROM requests";
$result = $conn->query($get_all);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if (!$row['archived']) {
echo "<tr id='" . $row['request_id'] . "' class='fade in'>
<td>
" . $row['fName'] . " " . $row['lName'] . "</br>
<strong>Sent: </strong>" . $row['timeEntered'] . "
</td>
<td>" . $row['address'] . "</br>" . $row['city'] . " " . $row['state'] . ", " . $row['zip'] ."</td>
<td>
<strong>Primary Phone:</strong> <a href='tel:" . $row['pPhone'] . "'>" . $row['pPhone'] ."</a></br>
<strong>Cell Phone:</strong> <a href='tel:" . $row['cPhone'] . "'> " . $row['cPhone'] . "</a></br>
<strong>Email:</strong> <a href='mailto:" . $row['email'] . "'>" . $row['email'] . "</a></td>
<td>
<strong>Pet Name:</strong> " . $row['pName'] . "</br>
<strong>Gender:</strong> " . $row['gender'] . "</br>
<strong>Spayed or Neutered?:</strong> ";
if ($row['spayedNeutered'] = 0) {
echo "No</td>";
} else {
echo "Yes</td>";
}
echo "<td>
<button class='btn btn-info'>More info</button></br>
<form action='../_php/archive.php' method='get'><input type='hidden' value='" . $row['request_id'] . "' id='row_id'><button type='submit' class='btn btn-warning archive'>Archive</button></form>
</td>
</tr>";
}
}
} else if ($conn->connect_error != NULL) {
echo "<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>";
} else {
echo "<tr><td colspan='5'><div class='alert alert-info' role='alert'>No Records were found.</div></td></tr>";
}
?>
<script type="text/javascript" src="../_js/query.js"></script>
</table>
connect.php - some content no included for security reasons
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("<tr><td colspan='5'><div class='alert alert-danger' role='alert'>Error: " . $conn->error . "</div></td></tr>)");
}
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$(".archive").click(function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
});
});
});
functions.php
<?php
require "connect.php"; // Connect to database
function archive($id) {
require "connect.php";
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['callArchive'])) {
archive($_POST['callArchive']);
} else {
archive(1);
}
?>
Since archive button is dynamically loaded, its the best choice to use .on('click') rather than .click() that does not fires on a dynamically loaded element. Try to read the question and answeres here, specially the selected correct answer.
query.js
$(document).ready(function() {
"use strict";
$('#results').load('../_php/submission.php');
$("#results .archive").on("click",function() {
$('#archiveMessage').modal('show');
var id = $(this).parent().parent().attr('id');
$.ajax({
type: 'POST',
url: '../_php/functions.php',
data: {'archive': id},
//If you dont want to change your functions.php file use the commented line below instead of the above code
//data: {'callArchive':id},
});
});
});
When the user clicks on the "archive" button, it does nothing, but if
they click if multiple times it eventually will bring up the "loading"
modal and then refresh the page. The row that should have disappeared
is still there, and the record still shows a "0" instead of a "1" as
it should.
Since your ajax call data contains post 'archive' in which the value is id and you want to update some data of your request table but you are checking the wrong index of the POST data(if (isset($_POST['callArchive'])) ) rather change it to if (isset($_POST['callArchive']))
<?php
function archive($id) {
require "connect.php";// Connect to database
$archive = "UPDATE requests SET archived='1' WHERE request_id='$id'";
if ($conn->query($archive) === TRUE) {
echo "Record " . $id . " has been archived.";
} else {
echo "Error: " . $conn->error;
}
}
if (isset($_POST['archive'])) {
archive($_POST['archive']);
} else {
archive(1);
}
?>
Hope that helps :D

.load() little part without toggle

I have a conversations flow who is refresh with .load() of jQuery every 3 seconds.
This system work, but in each conversation I have an answer button who slide a form (textarea and submit button) with .toggle().
To display the flow, I use a while with PHP.
My issue is, when the is loading by .load(), and answer button is clicked, the form hide again and text contain too.
<div id="the_river_loading">
<?php
$sql_the_river = 'SELECT u.nickname, u.firstname, u.lastname, u.main_photo, u.locality,
id_conversation, id_messages, owner, participants, text, date
FROM users AS u
INNER JOIN the_river
ON u.nickname = owner
WHERE answer = 0
ORDER BY date DESC';
$result_the_river = mysqli_query($mysqli, $sql_the_river);
$count = 0;
while ($data_the_river = mysqli_fetch_assoc($result_the_river))
{
$count++;
echo '<div class="message_container_news">'; // Start block conversation
echo '<a href="/profile/' . $nickname . '" class="name_links" style="vertical-align: top; font-size: 16px;">
<img src="' . $main_photo . '" title="' . $name . '" class="members_actu_photo" />' . $name . '</a>
<span style="vertical-align: top">, ' . $locality . '</span><span style="float: right; font-size: 12px;">Posté le Octobre 25, 2012</span>
<p style="margin-top: 5px;">' . $data_the_river['text'] . '</p>
<div class="btnAnswer_nb">' . $count_answer . '</div> Answers
See conversation
<div class="btnAnswer_news" id="btnAnswer_news_id_' . $count . '">Reply</div>
<form method="post" id="display_form_id_' . $count . '" action="" style="display: none;">
<br />
<textarea name="answer_text"></textarea><br />
<input type="submit" name="answer_valid_id_' . $count . '" value="Post" />
</form>
</div>'; // End block conversation
}
?>
</div>
<script type="text/javascript">
$(".btnAnswer_news").live("click", function(){
var num_show = this.id.replace(/\D/g, "");
$("#display_form_id_" + num_show).toggle("fast");
});
var auto_refresh = setInterval(
function() {
$("#the_river_loading").load("/home" + " .message_container_news");
}, 3000
);
</script>
In pleasure of read you.
This is because if you load the content again into the container, the styles applied per js will get removed (because they were applied through style="" and this gets refreshed). You should move the Form and the Button to another Div, wich is not in the loading Div.
If I understand your problem correctly (you've not be very descriptive), you just want to not hide the form when clicking again, for that use show() instead of toggle() , so replace your following line:
$("#display_form_id_" + num_show).toggle("fast");
for this one:
$("#display_form_id_" + num_show).show("fast");
If you want to keep the text of the textarea, you can like so:
var auto_refresh = setInterval(
function() {
tx = $("#the_river_loading textarea[name='answer_text']").val();
$("#the_river_loading").load("/home" + " .message_container_news", function(){
$("#the_river_loading textarea[name='answer_text']").val(tx);
});
}, 3000
);

jQuery UI picker with input box added using jQuery append

I am printing a form in a row on a page. The row contains a few columns which hold the form elements. Much like a table but in CSS.
When the user clicks on a link with the ID add_transaction_row then a little bit of jQuery is called which appends another row/div to the page. This row contains an identical set of div's and form elements as the row above.
I have named the elements date[], sub_cat_id[] etc so that I get an array of the updates to process on the next page.
I am using the jQuery datepicker for the date input box. I have a trigger on on class called .datepicker.
On the first row the jQuery date picker appears as expected. However when I click into any of the date input boxes on the rows below (the new rows/input box's added by jQuery append) then the datepicker does not work.
I was thinking that it might be something to do with me naming them all the same so I have given them all a unique ID. Still no luck.
I am now thinking its something to do with jQuery adding the .datepicker on page load and then when I click the bottom to add a new row this is adding the html to the source but after jQuery datepicker has loaded so it does not pick the new date/input box's up?
If anyone could shed any light on this I would appreciate it.
<?php
$my_new_split = '';
$my_new_split .= '<div class="split_transaction_box">';
$my_new_split .= '<div class="span-7">' . form_input('date[]', '', 'id="' . random_string('numeric', 8) . '" class="datepicker"') . '</div>';
$my_new_split .= '<div class="span-7">' . form_dropdown('sub_cat_id[]', $subcategories_options) . '</div>';
$my_new_split .= '<div class="span-5">' . form_input('reference[]') . '</div>';
$my_new_split .= '<div class="span-4 last">' . form_input('ammount[]') . '</div>';
$my_new_split .= '<div class="clearfix"></div></div><!-- /.split_transaction_box -->';
$my_new_split = trim($my_new_split);
$replace_this = array("\r\n", "\n", "\r");
$my_new_split = str_replace($replace_this, '', $my_new_split);
$my_new_split = str_replace('"', '\"', $my_new_split);
?>
<script>
$(document).ready(function() {
$('#add_transaction_row').click(function() {
$(".split_continer").append("<?=$my_new_split;?>");
return false;
});
});
</script>
<hr />
<div class="span-24 last">
<?=form_open('accounts/do_split')?>
<div class="split_continer">
<div class="split_transaction_box">
<div class="span-7"><?=form_input('date[]', '', 'id="' . random_string('numeric', 8) . '" class="datepicker"');?></div>
<div class="span-7"><?=form_dropdown('sub_cat_id[]', $subcategories_options);?></div>
<div class="span-5"><?=form_input('reference[]');?></div>
<div class="span-4 last"><?=form_input('ammount[]');?></div>
<div class="clearfix"></div>
</div><!-- /.split_transaction_box -->
</div><!-- /.split_container -->
<br />
Add new split
<input type="submit" class="button white" value="Save this split" />
<?=form_close()?>
Your exactly right, the datepicker does not work on new elements because you are adding those elements into the page after jquery has attached the datepicker. I've come across this issue myself. I came up with a few ways of doing it.
The first way was to bind a live click handler to the element, check if datepicker is applied, and if not apply it.
http://jsfiddle.net/uyx67/1/
But maybe a better way is to build the elements using jquery as objects and apply the datepicker that way
http://jsfiddle.net/4jmkw/3/
Both ways work, and do the job.
<script>
$(document).ready(function() {
$('#add_transaction_row').click(function() {
var new_row = jQuery("<?=$my_new_split;?>");
$(".split_continer").append(new_row);
$( ".datepicker" ).datepicker({
numberOfMonths: 2,
dateFormat: 'DD, d MM, yy'
});
return false;
});
});
</script>

Passing list item value during JQuery sortable() function

I'm trying to pass information from an unordered list, list item to an ajax request once the list item is placed in another list.
This is the JQuery that picks up the column #id the list item is dropped into, however the code for getting the $row['id'] picks up the first item in each list, not the specific item I'm sorting.
(I'm using php to iterate the list items in both lists - I've removed the unessential PHP code).
<script type="text/javascript">
$(document).ready(function(){
$(".sortable").sortable({
connectWith : ".sortable",
receive : function(){
var column = $(this).closest('div.box').attr('id');
var id = $(this).find('span').html();
$.ajax({
url: "update_column.php",
type:"POST",
data: "column="+column+"&id="+id
});
alert(column + id)
}
})
.disableSelection();
});
</script>
I'm using the alert() to give me some visual feedback. This is the HTML code:
<div id="one" class="box">
<ul class="sortable">
<li>
<div class="card">
<p>' . $row['customer'] . '</p>
<p>' . $row['ponumber'] . '</p>
<p class="hide"><b>ID:</b><span>' . $row['id'] . '</span></p>
<p class="hide">' . $row['misc'] . '</p>
</div>
</li>
</ul>
</div>
<div id="two" class="box">
<ul class="sortable">
<li>
<div class="card">
<p>' . $row['customer'] . '</p>
<p>' . $row['ponumber'] . '</p>
<p class="hide"><b>ID:</b><span id="id">' . $row['id'] . '</span></p>
<p class="hide">' . $row['misc'] . '</p>
</div>
</li>
</ul>
</div>
I'm a self taught programmer who has been programming for 3 months so I apologise for any novice mistakes.
I've updated your js, it works now. I have added comments where required.
$(document).ready(function(){
$(".sortable").sortable({
connectWith : ".sortable",
receive : function(event, ui){
//changed this to be use parent()
var column = $(this).parent().attr('id');
//get the current dragged item - as per http://jqueryui.com/demos/sortable/#event-receive
var index = ui.item.index() + 1 ;
//get the id from the span using the column we got in the first step and index we got above
var id = $("#"+column+" li:nth-child("+index+") span").html();
$.ajax({
url: "update_column.php",
type:"POST",
data: "column="+column+"&id="+id
});
}
}).disableSelection();
});

Categories