Running PHP function when PHP echoed HTML Button is clicked - php

I am Working on the project with my school but I have no idea how to call a PHP function when HTML button is clicked
<?php
function sqlUpdateTheScore($idMinusOneString){
$idminusOneVal=(int)$idMinusOneVal;
$MsgQuery=mysqli_query($conn,"UPDATE Point SET Point=".returnCurrentPoint($idMinusOneVal)."WHERE id=".($idMinusOneVal+1).";");
}
for($i=0;$i<$tot;$i++){
print "<tr>" ;
print "<td align='center'>" .$tot_result[$i][0]."</td>";
print "<td align='center'>" .$tot_result[$i][1]."</td>";
print "<td align='center'>" .$tot_result[$i][2]."</td>";
print "<td align='center'><button id='dec_".$i."' onclick='decreaseByOne(".$i.");'>-1</button><div id='pointOfStudent".$i."'>" .$tot_result[$i][3]."</div><button id='inc_".$i."' onclick='increaseByOne($i);'>+1</button></td>";
print "<td align='center'><button onclick='sqlUpdateTheScore($i);'>SAVE</button></td>";
print "</tr>" ;
}
?>
it's the sqlUpdateTheScore(); function at the top

You can't directly call php functions from html. (I also find this annoying)
There are two workarounds you can use. The easiest is a form:
<form action="thePage.php" method="POST">
<input type="text" name="newValue" id="newValue" hidden />
<button onclick="changeValue()">Change Value</button>
<input type="submit" value="SAVE" name="submit" />
</form>
JavaScript:
function changeValue() {
document.getElementById("newValue").innerText = "Some new value";
}
PHP:
if (isset($_POST["submit"])) {
$newValue = $_POST["newValue"]; // You can then run functions off this value
}
The other way is to use AJAX. Here is a good turorial.

Try this
PHP:
Change your SAVE button part to
<button class="save_button" value=$i>SAVE</button>
Add
if (isset($_POST['idMinusOneString'])) {
sqlUpdateTheScore($_POST['idMinusOneString']);
}
JS:
add AJAX (with jQuery)
$('.save_button').click(function() {
$.ajax({
type: "POST",
url: "this.php",
data: { idMinusOneString: $(this).val() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});

Related

Prevent Javascript form use back data on Back click

I create table using ajax. When i click on button it will read the row and create a form using ajax.
Everything is fine here. But when i click back button on browser, the data is somehow posted/display back as FORM. How to delete/prevent this when click on back.
Thing i have read:
1) Clear input for form. But where is reading input because form is created using function submitRowAsForm when button is clicked
2) Disable autocomplete. But this doesnt seem relevant and not work.
$(document).ready(function update(){
$.ajax({
url: 'getSchedule.php',
success: function(data,status)
{
createTableByForLoop(data);
},
async: true,
dataType: 'json'
}).then(function() { // on completion, restart
setTimeout(update, 30000); // function refers to itself
});;
});
function createTableByForLoop(data)
{
var table = "\
<div class='table-scrollable'>\
<table class=\"table table-responsive\">\
<thead >\
<tr>\
<th class=\"d-none\">ID</th>\
<th class=d-none>SHOWSCHEDULE_ID ID</th>\
<th>TITLE</th>\
<th>TIME</th>\
<th>ACTION</th>\
</tr>\
</thead>\
<tbody>"
for(var i=0; i<data.length;i++)
{
table += "<tr id=\""+i+"\">";
table += "<td class=d-none><input type=text class=\"form-control transparent-input\" name=SHOWSCHEDULE_ID value=\""+data[i]['SHOWSCHEDULE_ID']+"\" readonly></td>";
table += "<td><input type=text class=\"form-control transparent-input\" name=SHOWSCHEDULE_SHOWTITLE value=\""+data[i]['SHOWSCHEDULE_SHOWTITLE']+"\" readonly></td>";
table += "<td><input type=text class=\"form-control transparent-input\" name=SHOWBEGINTIME value=\""+data[i]['SHOWBEGINTIME']+"\" readonly> - <input type=text class=\"form-control transparent-input\" name=\""+data[i]['SHOWENDTIME']+"\" value=\""+data[i]['SHOWENDTIME']+"\" readonly></td>";
table += "<td><button onclick=submitRowAsForm("+i+") id=btnRoom class=\"btn btn-outline-success\" >Room</button>\
<button onclick=submitRowAsForm("+i+") id=btnBook class=\"btn btn-outline-warning\" >Book</button></td>";
table += "</tr>";
}
table +="</tbody></table></div>";
$('#idShowSchedule').html(table);
}
function submitRowAsForm(id) {
form=document.createElement('form');
form.method='POST';
form.action='OrderTicket.php';
$("#"+id).children().each(function() {
$(this).children().each(function(){
$(this).clone().appendTo(form);
});
});
document.body.appendChild(form);
form.submit();
}
To protect against the back button I would set a dirty flag on your page. That way when it's set you know you have done this before. So
Check to see if your dirty flag is set
If not set your dirty flag
Load data because this is a fresh loading of the page.
Make sure that you do this after the DOM Content has Loaded otherwise this will fail in some browsers.
Here is an example of how I didn't this in one of my old projects
document.addEventListener("DOMContentLoaded", function (event) {
var dirty = 0;
var dirtyEl = document.getElementById('page_is_dirty')
if (!dirty && dirtyEl && (dirtyEl.value != "0" && dirtyEl.value != "")) {
dirty = 1;
}
else if (dirtyEl) {
dirtyEl.value = '1';
}
var el = document.getElementById('ClickApp');
if (el && !dirty)
el.innerHTML = "<div id='ClickApp' ng-view='' click-main><br /><br /><center><h2>Loading Calendar</h2><br /><span id='ErrorInstructions'></span><br /><div class='ui-progress-bar ui-container' id='progress_bar' style='width: 350px'><div id='progressBar' class='ui-progress' style='width: 0%; float: left'></div></div><br /><br /><small><span id='LastError'></span></small></center></div>";
else {
var dirtyMEl = document.getElementById('page_is_dirty_message');
var dirtyMSG = dirtyMEl ? dirtyMEl.value : "You arrived here by hitting the back button. Please start over.";
el.innerHTML = "<div><br /><br /><center><h2>" + dirtyMSG + "</h2><br /><span id='ErrorInstructions'></span><br /><div class='ui-progress-bar ui-container' id='progress_bar' style='width: 350px'><div id='progressBar' class='ui-progress' style='width: 0%; float: left'></div></div><br /><br /><small><span id='LastError'></span></small></center></div>";
}
if (!dirty) {
//Do your data loading. Page transformaions, whatever
...
}});

Getting the value of a dynamically created input

I have following jquery script which load a form into a div "blankform"
jQuery('#metentry').submit(function(e){
e.preventDefault();
// getting data from form to variables
var date = jQuery('#stddate').val();
var kgsunit = jQuery('#unit').val();
var kgsshift = jQuery('#shift').val();
//sending data to script
jQuery.post("get_blank_form.php", {
"date": jQuery('#stddate').val(),
'unit': kgsunit,
'shift': kgsshift,
}, function(data) {
//loading a form to the div blankform
jQuery('#blankform').html(data);
});
get_blank_form.php contains following code
<?php
echo'<form id="shiftentry" name="shiftentry" >';
echo "Date:<input id=shiftdate value='".$date."'/>";
echo "Unit:<input id=shiftdate value='".$unit."'/>";
echo "Shift:<input id=shiftdate value='".$shift."'/><br/>";
echo "<table><tr><th>No</th><th>Ele</th><th>Location</th><th>Dose Rate (mGy/h)</th><th> Tritium (DAC)</th> <th>Part (DAC)</th> <th>Iodine (DAC)</th><th> Surface Cont. (Bq/cm2) </th></tr>";
while($row2 = mysql_fetch_array($result_sec))
{
echo "<tr>";
echo "<td>".++$rc."</td>";
echo "<td><input size='5' id='".$row2['elevation']."' value='".$row2['elevation']."' /></td>";
echo "<td><input id='".$row2['loc_id']."' value='".$row2['location']."' /></td>";
echo "<td><input size='5' id='dose".$rc."' value='".$row2['radn_level']."'/></td>";
echo "<td><input size='5' id='h3".$rc."' value='0' /></td>";
echo "<td><input size='5' id='part".$rc."' value='0' /></td>";
echo "<td><input size='5' id='iod".$rc."' value='0' /></td>";
echo "<td><input size='5' id='cont".$rc."' value='0' /></td>";
echo "</tr>";
}
echo " </table>";
echo '<div align="center">';
echo '<input type="submit" id="submit" name="submit" value="Submit" width="30" />';
echo '</div>';
?>
this will create a form which will have input like id1, id2 ... id25, dose1, dose2 ... dose25 and so on.
I want to read the values of these input boxes. Normal method like var loc1 = $("#id1").val(); is not working since these elements are dynamically created.
Even the submit button clicking even is also not triggered.
the script below do not produce any output.
jQuery('#shiftentry').submit(function(e) {
e.preventDefault();
alert("Submitted");
Any suggestions please?
Since the Form DOM is dynamically created after Ajax Call, You can use .on ?
like:
$(document).on('submit' , '#shiftentry' , function(e) {
e.preventDefault();
alert("Submitted");
});
You will need to use on() method for event handling as the form is created using ajax call and added later.
As it's added later, it will not be bound to submit event handler that you had specified. To bind it with the handler you need to use on() from jQuery.
$(document).on('submit', '#shiftentry', function() {
//Your code
});
As for the submit button, you can trigger it using
$('#submit_id').on('click', function(){
$('#shiftentry').send(function(e) {
e.preventDefault();
alert("Submitted");
);
})
as for getting the values using.
$('#id1').val()
this should just work just fine but remember that some characters are not permitted in id field such as [, ], . etc.. if you cant avoid this special characters in your id field you can use.
$('input[name="value"]').val();
to get the value of your fields.

Passing a value through Button to Php function

I am beginner in php and I am currently working on admin panel (you can see my admin panel page). The thing is that I want to pass serial number through these two buttons to perform further. But I can't find how to send $value to edit and delete a particular line.
<div id="headin2"><strong> <h3>Admin page </h3></strong></div>
<?php
echo "<table width=\"100%\" border=\"0\" id=\"tab\">";
echo "<tr>";
echo "<th id=\"td1\">Serial No</th><th id=\"td2\">Account Title</th>
<th id=\"td3\">Email</th><th id=\"td4\">Gender</th><th id=\"td5\">city</th>
<th id=\"td6\">Course</th><th id=\"td7\">status</th><th id=\"td8\" colspan=\"3\">Action</th>";
echo "</tr>";
while ( $row = mysql_fetch_array($query))
{
$SN = $row['SN'];
$actitle = $row['ac_title'];
$email = $row['email'];
$gender = $row['sex'];
$cite = $row['city'];
$course = $row['CRS'];
$status = $row['status'];
echo "<tr>";
echo "<td>".$SN."</td><td>".$actitle."</td><td>".$email."</td>
<td>".$gender."</td><td>".$cite."</td><td>".$course."</td><td>".$status."</td>
<td>"."<input type=\"button\" name=\"edit\" value=\"Edit\"/>
<input type=\"button\" value=\"Delete\" name=\"delete\" >"."</td>";
echo "</tr>";
}
?>
</table>
You need both the action (edit/delete) and the row id. Unfortunately, without some JS the button will only post one value.
You can create a new form for each row, add in a hidden element. For example:
<?php while ($row = mysql_fetch_array($query)) : ?>
<tr>
<!-- other cells -->
<td>
<form method="post" action="">
<input type="submit" name="action" value="Edit"/>
<input type="submit" name="action" value="Update"/>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>"/>
</form>
</td>
</tr>
<?php endwhile; ?>
Then after posting it you can just check for the action and id
if ($_POST['action'] && $_POST['id']) {
if ($_POST['action'] == 'Edit') {
// edit the post with $_POST['id']
}
}
You can do it one of two ways.
jQuery and AJAX
For each <tr>, everywhere there is a delete button,
Delete
Script at the bottom:
//Include jQuery here
<script language="javascript">
$('.delete-row').click(function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
url: "url/to/delete",
method: "POST",
cache: false,
data: { id: id },
success: function (html) {
$(this).parent().parent().remove();
});
});
});
</script>
This puts the ID of the row into the <a href> itself using data and uses jQuery to send out an AJAX call to delete the record. If the delete is successful, it removes the row from the table.
Old-School Button
For each <tr>, everywhere there is a Delete button,
<form method="POST" action="url/to/delete">
<input type="hidden" name="id" value="<?php echo $value; ?>" />
<input type="submit" value="Delete" />
</form>
This is the old-school way to do it, where the hidden field is how the backend knows which row to delete.
On the backend, you still use $_POST['id']; to get the ID of the record to remove. In the above examples, $value is the ID for each row, and is most likely something like $row['id'] when it is coming from a foreach().
Use a hidden input (e.g.<input type="hidden" value="your_value_here">)
when you click Edit it open a page with corresponding record. You can do it by a Edit link or a image or a button.
<?php echo "<a href='".BASE_URL."admin/edit.php?id=$id' target='_blank'> <img src=".BASE_URL."/images/edit.png width=16 height=16 alt=Edit /> </a>";?>
for delete you can use jquery. here is a example
echo "<a href='#' onclick='deletePrescription($id)' ><img src=images/document_delete.png width=16 height=16 title='Delete Prescription' alt=Delete /> </a>";
<script type="text/javascript">
function deletePrescription(checkup_id) {
//alert(checkup_id);
var agree=confirm("Do you really want to delete the prescription?");
if (agree)
{
$.ajax
({
type: "POST",
url: "delete_prescription_admin.php",
data: "checkup_id="+checkup_id,
success: function(msg)
{
//
//alert( "array Updated: " + msg );
location.reload(true);
}
});
}
else
{
return false ;
}
}
</script>
PHP is on the server side, so you need to send parameters, parse it and have your php act.
i.e.
The edit button will make POST or GET request with parameter: id=123&action=edit
and your PHP will parse the Query String:
$strID = $_GET['id'];
$strAction = $_GET['action'];
then act on it..
if ($strAction=='edit'){
// do something...
}
Your buttons should be wrappen in a form like:
<form action="yourFile.php?id=<?=$SN ?>&action=edit" method="GET" id="formEdit<?=$SN ?>">
<button type="submit" value="Edit">
</form>
<a href=register_course.php?id=$roll&code=".$row['course_code']."&name=".$row['course_name']."><input type=submit value=Register>
*here register_course.php is the file where you are sending some variable having some data it will be delivered when button is clicked whose value is register //course code is the variable you want to send ... im assigning its value as $ code... and assigning id $roll as id and assigning course_name as $name....
the other file will get the variables having some data

How to make a html table appear using ajax and jquery?

Ive been trying to make my html table appear when i click the submit button but all it does is inserts data into the database and the html table doesnt appear.
here is my index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("table.php");
});
});
</script>
</head>
<body>
<form action = "insert.php" method="post">
Firstname: <input type="text" name="firstname"></br>
Lastname: <input type="text" name="lastname"></br>
Middlename: <input type="text" name="middlename"></br>
<button type="submit">submit</button>
</form>
<div id="div1">
</div>
</body>
</html>
here is my table.php
<?php
$con = mysqli_connect("localhost","root","","study");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to mysql" . mysqli_connect_error();
}
echo '<table border = 1>';
echo '<tr>';
echo ' <th>FIRSTNAME</th>';
echo '<th>LASTNAME</th>';
echo ' <th>MIDDLENAME</th>';
echo ' <th>DELETE</th>';
echo ' </tr>';
$result = mysqli_query($con,"SELECT * FROM sample_employers");
while($row=mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['middlename'] . "</td>";
echo "<td> <input type='button' value='Delete' </td>";
echo "</tr>";
}
mysqli_close($con);
echo '</table>';
?>
I did some editing in my index.php. I put the submit button outside the form tag and the html table appears but the problem now is there is no data inserted to the database.So how am i going to make the html table appear and at the same time insert data to the database when i click the submit button.??
// example 1 GET
$(document).ready(function(){
$("#submitButt").click(function(e){ // u should give a id to the button.
e.preventDefault(); // this is to prevent the form submit by it self
// using ajax to submit
$("#div1").load("insert.php",
$(this.form).serialize(); // this will use GET to submit data
);
});
});
// example 2 POST
$(document).ready(function(){
$("#submitButt").click(function(e){ // u should give a id to the button.
e.preventDefault(); // this is to prevent the form submit by it self
// using ajax to submit
$("#div1").load("insert.php",
$(this.form).serializeArray(); // this will use POST to submit data
);
});
});
http://jsfiddle.net/9kcek/
use Tamper Data to check the request when u click the submit button.
If you press submit, then you will be redirected to insert.php. Hence, your click event will never be executed. You must prevent the redirect first in order for you to load your data.
Furthermore, you will need to switch the way in which your data is posted. As you want to directly insert the table on the current page, you should switch to an ajax approach. Your data will be sent to your insert.php in the background via $.ajax and then you can load your #div1 on success with the content of table.php.
<script>
$(document).ready(function () {
var $form = $('form');
$form.submit(function (event) {
event.preventDefault();
var formData = $form.serialize(),
url = $form.attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function () {
$("#div1").load("table.php");
}
});
});
});
</script>

how to run php code on submit button without refreshing/ reloading the page

I want to execute some php code on submit button click without refreshing/reloading my page. Is it possible? also i have javascript function on page load that's why i don't want to refresh my page.
thanks in advance.
<?php
if(isset($_POST["search"]))
{
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
$add_to_textbox = "<input type='button' name='btn' value='add' />";
#****results in Grid****
echo "<table width='360px' border='1' cellpadding='2'>";
$rowID=1;
while($row = mysql_fetch_array($rs))
{
echo "<tr>";
echo "<td width='130px' id='name.$rowID.'>$row[Name]</td>";
echo "<td width='230px' id='link.$rowID.'><a href = '$row[Link]'>$row[Link]</a></td>";
echo "<td width='130px' onclick='Display($rowID);'>$add_to_textbox</td>";
echo "</tr>";
$rowID++;
}
echo "</table>";
#**********************
mysql_free_result($rs);
}
?>
<script type="text/javascript">
function Display(rowID){
var linkVal = document.getElementById('link'+rowID+'').innerHTML.replace(/<\/?[^>]+(>|$)/g, "\n");
document.getElementById("name").value = document.getElementById('name'+rowID+'').innerHTML;
document.getElementById("link").value = linkVal;
}
</script>
here is my code
Well, you need to use the javascript / ajax.
Example: on your submit link (a href for exaple), add call-in-to js function submitMe and pass on whatever variables you need
function submitMe() {
jQuery(function($) {
$.ajax( {
url : "some_php_page.php?action=getsession",
type : "GET",
success : function(data) {
alert ("works!"); //or use data string to show something else
}
});
});
}
IF you want to change some content dynamically, it is easy- you just need to create tags, and assign ID to them : <div id="Dynamic"> </div>
Then you load ANYTHING between those two tags using
document.getElementById("Dynamic").innerHTML = "<b>BOOM!</b>";
Meaning that you calling area between two tags and loading something into them. The same way you GET data from that place:
alert(document.getElementById("Dynamic").innerHTML);
Please read this:
http://www.tizag.com/javascriptT/javascript-getelementbyid.php
In addition, play and experiment with DOM elements and learn how they interact. It is not hard, just takes some time to grasp all concepts.
Whenever you send request ajax (with plain js anyway) from a html form, make sure you add the return false statement to prevent redirection:
something like:
<form method="post" ... onsubmit="ajax_post(); return false;">
You have to use ajax, but you can do it in plain javascript (without jquery). Jquery makes it easier.
plain javascript example: This function will trigger an ajax, via get, without parameter: you can tweak it so it run in POST and be able to send some parameter: file represent the php file to request and html represent the container whre the data will be displayed:
function plain_ajax(file,html){
if (window.XMLHttpRequest){
r=new XMLHttpRequest(); //For Most BRowser
} else{
r=new ActiveXObject("Microsoft.XMLHTTP"); //for Explorer
}
//When the state change
r.onreadystatechange=function(){
//ReadyState 4 = Loaded see: http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
//status 200 = ok see: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if(r.readyState==4 && r.status==200){
//Replace the content with the response, Using creatDocumentFragment is more efficient
//at the cost of a few more lines But it would alos allow you to append the data
//instead of replacing it using innerHTML;
document.getElementById(html).innerHTML = r.responseText;
}
}
//Opening the connection and sending the request.
r.open("GET",file,true);
r.send();
}
Your HTML or PHP form
<form action="submit.php" method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone Number: <input name="phone" id="phone" type="text" /><br />
<input type="button" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>
Your JavaScript
<script>
function SubmitForm() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
$.post("submit.php", { name: name, email: email, phone: phone },
function(data) {
alert("Data Loaded: " + data);
});
}
</script>
Your PHP page to do some activity
<?php
echo $_POST['name']."<br />";
echo $_POST['email']."<br />";
echo $_POST['phone']."<br />";
echo "All Data Submitted Sucessfully!"
?>

Categories