Using Ajax and Dialog Widget - javascript

I'm using a Dialog Widget for generate a popup with this code in my index.php:
<button class="btn btn btn-info openObs">Deixar observação</button>
<div id="dialog" title="Dialog Title">I'm a dialog</div>
and
$("#dialog").dialog({ autoOpen: false });
$(".openObs").click(function() {
$("#dialog").dialog("open");
});
so far no problem, but i have a ajax code that generate for me this buttons in a table in other archive and echoes the result back in my index.php in a result div:
$return .= "$tabela";
while($row = mysqli_fetch_assoc($query)){
$data = str_replace('-', '/', $row['consulta_data']);
$data = date('d/m/Y', strtotime($data));
$return .= "<tr>";
$return .= "<td>" .$row['consulta_idConsulta']."</td>";
$id = $row['documento_id'];
$return .= "<td>" .$data. "</td>";
$return .= "<td>" .$row['consulta_hora']. "</td>";
$return .= "<td>" .$row['consulta_desc']. "</td>";
$return .= "<td>" .$row['profissional_nome']. "</td>";
$return .= "<td>" . "<button class=\"btn btn btn-info openObs\">Deixar observação</button></td>";
$return .= "</tr>";
}
echo $return .=" </tbody>
</table>";
The problem is, when i click on the button generated by ajax nothing happens but if I put a button manually like up there works normal.

The issue is that the button is generated. To avoid this, you need to use on()
http://api.jquery.com/on/
$(body).on('click', '.openObs', function(){
});
Here is the js.fiddle for you. You can test it by enabling and disable individual function.
Make sure that the $(body) is not an element that is appended on later. So it can be $('.container'), as long as it is not javascript generated.

The problem in your case is that when you are binding the click function for dialog, the button you are creating with ajax is not present in the DOM yet , hence no binding will be done on the buttons created by ajax after your binding. To achieve this functionality, a simple way is to bind the same function again after you created the button with ajax. This will solve the issue.

Related

How can i display data from selected row in textarea

I'm trying to learn php with html and I decided to create a project.
Right now, I'm stuck at this point where I want to display data on a textarea.
I created a database named 'company' with the table 'login' and the columns 'id','password' and 'username'.
When I select an option in the select option menu, the data from the column 'id','password' and 'username' is displayed in a table. What I want to achieve is when I click on a row, that the data from the column "problem" is displayed on the textarea which describes the situation with explanation.
I don't know how to write this but the syntax should be something like: Select 'problem' from login WHERE id='selected row id' I created on my php a select case witch works fine. The only problem that I have is I don't know how to select the id when I click on a specific row to display the data on the textarea.
Here's my code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Formulaire</title>
<link rel="stylesheet" type="text/css" href="formulaire.css"/>
<!--<script type="text/javascript" src="select1.js"></script>-->
<!--<script src="http://code.jquery.com/jquery-latest.js"></script>-->
<style>
table tr:not(:first-child){
cursor: pointer;transition: all .25s ease-in-out;
}
table tr:not(:first-child):hover{background-color: #ddd;}
</style>
</head>
<body>
<div id="form">
<form action="#" method="post">
<label>Veuillez choisir une option :</label>
<select id="choix" name="choixtest">
<option value="tous">tous</option>
<option value="id">id</option>
<option value="username">username</option>
<option value="password">password</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
<table id="table">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "company");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM login";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>username</th>";
echo "<th>password</th>";
echo "</tr>";
if(isset($_POST['submit'])){
$selected_val = $_POST['choixtest']; // Storing Selected Value In Variable
while($row = mysqli_fetch_array($result)){
switch($_POST['choixtest']){
case 'tous':
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
break;
case 'id':
echo "<tr>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'username':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'password':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "</tr>";
break;
default:
// Something went wrong or form has been tampered.
}
}
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</table>
<textarea id="erreur" rows="20" cols="100"></textarea>
</form>
</div>
</body>
</html>
For a table with <table id="myTable">to get the first column value into a textbox which is defined as
<input type="text" placeholder="Customer Name" id="cus_name">
You can add the following js code.
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
document.getElementById("cus_name").value = this.cells[0].innerHTML;
};
}
</script>
Here the cus_name is the id of the text field while in the this.cells[0], the value 0 represents the first column. You can change it accordingly and also can add more columns with the code document.getElementById("cus_name").value = this.cells[0].innerHTML; by only changing the cell value and the textbox id.
Every row in your html table must correspond to an id in the login table.
you have to place somewhere in the row the id corresponding to that row. You can achieve this in many ways.
one way to do it is using a data-something attribute to put the id, for instance
<tr data-id="<?php echo $current_row['id']; ?>">
<td>column1</td>
<td>column2</td>
<td>etcetera</td>
</tr>
Once you have the data-id atttribute set you can access it via Javascript everytime a user clicks on the row. For this you need to capture the click event on the row. I'll show you an example using jQuery:
$('.myTable tr').click(function(){
let id = $('this').data('id');
console.log('id of selected row: ' + id);
});
Now the 'id' variable contains the id of the row the user selected (check console output to make sure the id is the one you expect). The next step would be to use that id to make a request to the server, via Ajax or via regular http request. If this works successfully i suggest you to research, or make another post to find out how to reload the page with the content with the data you want. Since the more specific a question is the higher is the chance that it will be answered

Add onclick event to a dynamic created link (PHP)

I have many links which are dynamically created with PHP and now I want to add an onclick event.
while($row = mysqli_fetch_array($xyz)) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . "</a></td>";
echo "</tr>";}
but I want like this:
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . onclick="test()"</a></td>";
echo "</tr>";}
is this possible?
I am not sure if I understood what exactly you are asking but I try to answer you the same:
You can't record a normal JS variable in a page session and then to access to it after the loading of a page.
For this case you can use cookies (that are accessible via server-side too):
// put this code into methods that users suggested you.
document.cookie = "value_selected=something"
and once page is loaded:
var cookies = document.cookie.split(';');
var value_selected = JSON.parse(JSON.stringify(cookies[YOUR_COOKIE].split("=")[0]))
or server side:
echo "<td><a href=\"test.php?parameter=". $row['z'] ."\" data-something=htmlentities($_COOKIE['value_selected']) target=\_blank>" . $row['z'] . "</a></td>"; //(example)
Or more simply, pass the value selected through query
?value_selected=something //elaborate the new link in the method users suggested you
and
in server-side, use $['GET'] to obtain all values in query string.
IMHO I think the first choice is simpler than second.
I hope I helped you
Try Like this
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a class='myclick' href=\"test.php?parameter=". $row['z'] ."\" target=\_blank>" . $row['z'] . **onclick="test()"**</a></td>";
echo "</tr>";}
i have added a class to link as myclick
and in jquery
$(document).on('click','.myclick',function(e){
e.preventDefault();
alert('clicked');
});
You can try like this..just a simple way.
<script type="text/javascript">
function test(){
alert('test');
}
</script>
<?php
while($row = mysqli_fetch_array($xyz) {
echo "<tr>";
echo "<td><a href='your link' onclick='test()'></a></td>";
echo "</tr>";
}
?>

On table row click, alert box shows click value

i'm having problems where when i click the tablerow, nothing is being shown.
When I click lets say the row where customername= 'John', the name 'John' should appear on a alert box, but nothing happens.
This is my table click code.
$(document).ready(function(){
$("#parentElementIdHere").on("click", "#test tr", function(e) {
var name = $(this).find("td").first().text();
alert(name);
});
And, here is my generating of table code.
if(!empty($_GET['q'])){
$q = $_GET['q'];
$query="select * from customer where customername like '$q%'";
$result = mysqli_query($dbconn,$query);
echo "<div id='parentElementIdHere'>";
echo "<table id='test' border=3>
<tr>
<th>Customername</th>
<th>nric</th>
<th>email</th>
<th>mobileno</th>
<th>telephoneno</th>
<th>address</th>
<th>postalcode</th>
<th>datejoined</th>
<th>points</th>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['customername'] . "</td>";
echo "<td>" . $row['nric'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['mobileno'] . "</td>";
echo "<td>" . $row['telephoneno'] . "</td>";
echo "<td>" . $row['occupation'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['postalcode'] . "</td>";
echo "<td>" . $row['datejoined'] . "</td>";
echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
Could the problem be because my table generated is constantly changing because of ajax?
To get name value for click on any value of the row
$("tr").click(function() {
var str = this.innerText;
var i = str.split('').indexOf(" ");
alert(str.slice(0, i));
})
http://codepen.io/nagasai/pen/QENwgQ
to get table cell value on click
$("td").click(function(){
alert(this.innerText);
})
codepen URL for reference- http://codepen.io/nagasai/pen/jrqEBz
Hope this is helpful for you
There are two main problems with your code:
Your selector '#test tr #name' says to select all elements with id="name" that are descendants of tr elements, but it is actually your tr elements that all have that id. (And speaking of them all having that same id, duplicate ids is invalid HTML.)
Calling .click() binds a click handler to elements that exist at that moment. Which means that when your table changes due to an Ajax call your click handler would not work for the newly loaded/created elements even if you fixed the selector.
The solution to both problems is to use a delegated event handler, which you bind to the table element's parent (or to the nearest ancestor element that does not get overwritten by the Ajax call):
$(document).ready(function(){
$("#parentElementIdHere").on("click", "#test tr", function(e) {
var name = $(this).find("td").first().text();
alert(name);
});
});
When a click occurs on any descendant element of the parent element, jQuery will check if the specific clicked element matches the selector that is the second argument to the .on() method, and if so it will call your function with this set to the matching element. Because the matching element is a tr element, you would then use .find("td").first() to get that row's name td.
Demo: https://jsfiddle.net/269Lt9hm/
I managed to solve it. I tested with a non ajax generated sql table and did it. Then i brought over the javascript code over to this file and tried it out. This is the code i used.
$(document).ready(function(){
}).on('click','.test tr',function(){
var id = $(this).attr('value');
alert(id);
});
Thanks to all who helped me i appreciate it!

Using jQuery to get the data of a JSON Object

I am new to jQuery and JSON. I have the following PHP code (getData.php) performs query from the database:
<?php
header('Content-Type: application/json');
....
// some code here
....
$my_arr=array();
// fectching data into array
while($info = mysqli_fetch_array($result))
{
// convert to integer value if there is a bug after passing json_encode
$rev=intval($info['bIRevNum']);
$name=$info['bIName'];
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
$my_arr[]=array('br'=>$name,'rev'=>$rev);
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
}
// json encode
echo json_encode($my_arr);
?>
After use echo 'json_encode' here I can see the JSON object under this format
[{"br":"itemsb1","rev":37},{"br":"itemb2","rev":45}] on my page.
Now I want to access the integer of rev element of the object (37 and 45) for future usage by jQuery in a different PHP file, lets call it index.php and with the below script
<html>
.....
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value){
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
});
</script>
...
// test here
<!---jquery--->
<div id="div1"><h2>CHANGE >>>> ....!!!!</h2></div>
<button>Calling from different PHP file</button>
</html>
If it is correct, when I click on the button "Calling from different PHP file" it should appears the value of JSON object as 37, 45.
I have tried many ways, but it does not display anything on my page.
Please help me with this!
It appears your problem is that you are echo'ing the html as well as the JSON. try removing the 'echo' from these lines
echo "<tr>";
echo "<td>" . $info['bName'] . "</td>";
echo "<td>" . $info['bRevNum'] . "</td>";
echo "<td>" . $info['bIName'] . "</td>";
echo "<td>" . $info['bIRevNum'] . "</td>";
echo "<td>" . $info['pName'] . "</td>";
echo "<td>" . $info['pRevNum'] . "</td>";
echo "</tr>";
DO NOT delete this line:
$my_arr[]=array('br'=>$name,'rev'=>$rev);
Also make sure your javascript is syntax correct
$("button").click(function(){
$.getJSON("getData.php", function(obj) {
$.each(obj, function(key, value) {
$("#div1").append("<li>"+value.rev+"</li>");
});
});
});
Ensure that the only content coming back from getData.php is JSON-formatted; otherwise, it won't be parsed correctly. If you visit getData.php in your browser directly, you should only see JSON content, and nothing else (including errors, warnings, etc.). Your jQuery looks good; so the issue would have to be whatever content is coming back from the PHP script. I just whipped up a trivial test case using this PHP:
<?php
header('Content-type: application/json');
$my_arr[]=array('br'=>'something','rev'=>'2.0.5');
echo json_encode($my_arr);
?>
Using the exact HTML you provided, that works just as expected.

Dynamic way to get a list of ticked checkboxes on a php generated page

I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});​
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!

Categories

Resources