How to pass php values to javascript then to ajax? - php

I am echoing data into a table with values from my database. It looks like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point
echo "<tr><td>".$somedata."</td></tr>";
?>
So the value of this table row will be displayed based on how much data is in the database. I want to asynchronously update the page, for example the user wants to delete this from the DB. How can I pass this value to javascript with an onClick function? Or is there another way? If I have a link to delete in the table like:
<td><a onClick="delete(ThisValueOfThisTableRow)">Delete</a></td>
And in javascript or jQuery I want to find this value and set it to a variable, then pass it as:
var some_value = //get this value
.ajax{
url: "somephpfile.php"
data:{some_value:value}
}
I think this would be helpful to anyone if they a responsive member page. Please help out!

maybe something like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array) {
?>
<tr>
<td><?=$somedata;?></td>
<td><a href='#' class='delete-btn' id='row-<?=$someID;?>'>Delete</a></td>
</tr>
<?
}//end while
?>
and then for the js event
$('.delete-btn').click(function() {
var id = $(this).attr("id");
id = id.split("-");
data = { "id" : id[1] }
//your ajax here, pass in your data obj
});
best of luck-

PHP
while ( $row = mysql_fetch_array( $result ) ) {
echo '<tr><td><a onclick="delete_row(' . $row['id'] . ')">delete row</a></td></tr>';
}
Javascript
function delete_row( id ) {
alert( id ); //To show you are getting the id remove this for production
//ajax goes here
}

Related

Delete Current Row in Php

How can i delete the current row from Mysql using php ?
I want to search from my Mysql database, every individual row has a Delete button on right side.
When i click on Delete button, that current row should be deleted from database.
I've tried to create a function in php that contains the Query to delete from database. But its not working when i call it in my Search block.
I've created two functions, one in PHP (named as "hello") that contains the Delete Query and one in JavaScript (named as "DeleteRecord") that is calling php function "hello".
Now i called JS function in my Search block.
JS function is working fine, but when JS call a php function, it also works if i just use echo, but within php function if i un comment the Delete Query, it doesn't work !
Anyone to help me out
Thanks !
function viewRecord($Para)
{
echo "<table border=1>
<thead>
<th>Book_Number</th>
<th>Name</th>
<th>Auther</th>
<th>Quantity</th>
<th>Shelf</th>
</thead>";
while($row=mysql_fetch_array($Para))
{
echo "<tr>";
echo "<td>".$row['Book_Number']."</td>";
global $DeleteRecordNumber;
$DeleteRecordNumber = $row['Book_Number'];
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Auther']."</td>";
echo "<td>".$row['Quantity']."</td>";
echo "<td>".$row['Shelf']."</td>";
echo "<td>"."<input type=button value=Delete onclick=DeleteRecord()>"."</td>";
echo "</tr>";
}
echo "</table>";
}
function hello()
{
global $DeleteRecordNumber;
$asd = $DeleteRecordNumber;
echo $asd;
// $Del = "DELETE FROM books WHERE Book_Number='$asd'";
// mysql_query($Del);
}
mysql_close($Connection);
?>
<script type=text/javascript>
function DeleteRecord()
{
document.write (<?php hello(); ?>);
}
</script>
Wait a minute, i think you are mixing apples with oranges! You cannot execute a PHP function on the client side using a button unless you submit the form. The more i look at your post the more errors i Find.
However, assuming you ARE submitting the command (you are not showing what DeleteRecord() does, so i will assume you have a form submision there), You should have a unique field in your table, for example 'id" which would be of type NOT NULL, AUTO_INCREMENT, PRIMARY.
When dislpaying your rows, have each row to hold this unique id. Then when the button is pressed simply do:
$result = MySQL_Query("DELETE QUICK FROM books WHERE id='idtodelete'");
Update the query with your table name and a unique id, That should do it.
converting it to function should go like:
function delete_record($id)
{
return MySQL_Query("DELETE QUICK FROM books WHERE id=$id");
}
If you dont want to use a unique field, use anything that is unique, like an email or something that is not present in another record in the same table, like your field 'Book_Number', but it is more standard the field 'id'.
Column names are case-sensitive, so, if your query is not working as it should, check the character case of everything.
Are you trying to delete a record without refreshing the page?
If so you can remove the element via javascript/jquery and on the delete function you would make an ajax post call to the server with the book id and the operation to perform.
In jQuery it would look like (assuming you put an id in your book_number<td> as book_number):
<script>
var data = {
book_id: $("#book_number"),
operation:"delete"
}
var jqxhr = $.post( "example.php", data, function() {
alert( "Record deleted" );
//delete the row from the table
})
.done(function() {
alert( "Alternative to the above" );
})
.fail(function() {
alert( "error deleting record" );
})
.always(function() {
alert( "Operation completed" );
});
</script>
On the php side, in example.php you would need to adapt your code to include some processing if the $_SERVER['REQUEST_METHOD'] is equal to "POST" and if so, in your query string you would place:
"DELETE FROM books WHERE Book_Number='{$_POST['book_id']}'";
Keep in mind that although this might work, it is not safe from SQL injection, you would need to use some form of escaping to safeguard your queries from SQL Injection.
Another way to do it would be to have the delete button serve as a submit button for a form with the book_number being passed around and do the same above but this time around without the Javascript part. This would force a page reload.

Load an html table from a mysql database when an onChange event is triggered from a select tag

So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});

Getting a record row in php using javascript

Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/

jquery and ajax page refreshing issue

I am fetching a problem though I know it's not a big issue, but something is different to me as I new. I have a page which has a list of records, fetching from a database. Now one button is there , after clicking the records, one pop up will be opened up along with some data. Inside that pop up one another link is there called "restore", whenever , that linked will be clicked out the database has been updated. Now up to this its okay for me. But whenever, I close the pop up, my list of records should automatically changed as some records have been restored. But I am not getting the result until and unless I do not refresh the page. so how can I do this, please help me ....
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "restore-request-process.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
//return false;
});
});
in the restore-request-process.php page I just update the database and echo the id.
After the database update, call a function to update the front end or simply reload page using location.reload()
you need to have declared global function in parent window
function Update(){
//global function in parent, update div
}
on popup window call function
window.opener.Update();
that will automatic reload your div, and not all page, If it's not necessary
Suppose this is your listing format
<table>
<?php
foreach($results as $result) { ?>
<tr id="my_div">
<td><?php echo $result->name?></td>
<td class="delete" id="<?php echo $result->id?>"><img src="delete.png"/></td>
</tr>
<?php } ?>
</table>
In restore-request-process.php write a query which fetch all the result from database and just echo the result like this
$result = mysql_query("SELECT * FROM my_table");
while($row = mysql_fetch_array($result))
{
echo '<td>'. echo $row["name"].'</td>
<td class="delete" id="'. echo $row["id"].'"><img src="delete.png"/></td>' ;
}
and onsuccess replaced all the content inside the my_div with response text
CODE IS NOT TESTED
for more references you can go through this link

Populate input with database data on select change

I'm an absolute beginner in the HTML/Php/JavaScript world. I'm trying to make this page:
dropdown list with titles of documents
when something is selected, populate input fields below with data from PostgreSQL to allow for update
submit button to update database with corrected values from user.
1 and 3 are ok (already tried this with an insert-only form).
My code looks like this (simplified, without dbconn):
echo "<select name='listedoc' size=1>";
while ($ligne = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo '<option value="'.$ligne['id_doc'].'">'.$ligne['doc_titre']. '</option>';
}
echo "</select>";
The input fields (simplified, there are 4 fields actually):
<p><form name="saisiedoc" method="post" action="docupdins.php"></p>
<table border=0>
<tr><td>Texte</td>
<?php
echo '<td> <textarea name="content" cols="100" rows="30"></textarea> </td>';
?>
</tr><tr>
<td colspan=2>
<input type=submit value="Valider la saisie" name="maj"> </td>
</tr>
</table>
</form>'
Then JQuery script :
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
});
});
</script>
The php to select fields (docsel.php):
<?php
include('../scripts/pgconnect.php');
$iddoc = $_POST['id'];
$sql="SELECT * FROM document where id_doc = $iddoc";
$result = pg_query($db, $sql);
if (!$result) {
echo "ERREUR<br>\n";
exit;}
$row = pg_fetch_row($result);
$doctyp = $row[1];
$doctitre = $row[2];
$docauteur = $row[3];
$doccontent =$row[4];
pg_free_result($result);
pg_close($db);
}
?>
Whatever I do, I can't get back values. I tried value="'.$doctitre'" in the input,
echo $doctitre, to no avail . Is my code logic correct ? Thank you for your help
you are close. the script docsel.php needs to return the data to the html-page.
you have it already setup to receive the data in the callback function
$.post("docsel.php", {id:id},function(data) {
$('textarea[name="content"]').text(data.content);
});
in order to have something in data.content, the php script sends json data:
$result = [];
$result['content'] = $doccontent;
echo json_encode($result);
maybe you need to read the docs on $.post and json_encode... good luck.
There are a couple of things you need to change here.
Firstly, and most importantly your docsel.php script has a gaping security hole. You should never ever ever place unsanitised input e.g. directly from a user, straight into a SQL query because it allows for SQL injection. Essentially, SQL injection allows a malicious user to end the programmers query and submit their own. To get round this you must sanitise any user input - so in this case pass the user input through the function pg_escape_literal() before putting it into your query.
Secondly, your docsel.php script must put out some kind of output for the AJAX request. You can do this by using echo and I would recommend you encode it into JSON. Code example:
$return_vals = array("doctype" => $doctyp, "doctitle" => $doctitre, "docauthor" => $docauteur, "doccontent" => $doccontent);
echo json_encode(array("document" => $return_vals));
Lastly, in your jQuery script, you aren't actually doing anything with the data that is returned from your AJAX post request. Inside the callback function, you need to then add the returned fields to your select dropdown. Code example:
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
//FILL THE DROPDOWN HERE
$(data).each(function(elem) {
$("#dropdown-id").append("<option value='" + elem.doctitle + "'>" + elem.doctitle + "</option>");
});
}, "json");
});
</script>
A mute and pedantic point, but when making requests for content then you should be using GET instead of POST.

Categories