I'm a newbie in php and I need help with this. The query runs every time on page load and not when I click my button.
<input type="button" name="button" onclick="<?php
$temp_id = $row_RecStudent['stu_id'];
mysql_query("UPDATE tbl_studentdetail SET stu_queue = 0 WHERE stu_id = $temp_id"); ?>" value="Unqueue" />
This is so frustrated because I run this button in a loop but every time the button loads it automatically run the mysql_query inside not when I click it.
SOLVED! Check on AnthonyB's answer.
The query runs every time on page load and not when I click my button.
Which is because onclick events are usually executed in the browser with client side scripting, which invariably means javascript. What you really need to have is
<input type="button" name="button" onclick="js_function()" value="Unqueue" />
Where js_function is a javascript that will make an ajax request to the page or simply cause the form to be submitted. What you are doing is making onclick equal to the result of the PHP code fragment, which obviously happens at the server side and has absolutely nothing at all to do with the user clicking on the button.
You should use an AJAX request, because there is no redirection nor reloading.
To use the exemple below, you must include jQuery
<!-- data-id is the id you got before -->
<input type="button" data-id="<?php echo $row_RecStudent['stu_id']; ?>" name="button" class="button-on-click" value="Unqueue" />
<script type="text/javascript">
$(function() {
//On click on this kind of button
$(".button-on-click").on('click', function() {
var id = $(this).attr('data-id');
//Send AJAX request on page youraction.php?id=X where X is data-id attribute's value
//the ID used in mysql query
$.ajax({
url: "youraction.php",
method: "GET",
data: {
id: id
}
}).done(function() {
//Once it is done
console.log("OK!");
});
});
});
</script>
On youraction.php
<?php
//Cast $_GET['id'] to integer to prevent SQL injection.
//If there is no id given, stop
if (empty($_GET['id'])) {
exit();
}
$id = (int)$_GET['id'];
mysql_query("UPDATE tbl_studentdetail SET stu_queue = 0 WHERE stu_id = $id");
Be careful, mysql_* functions are deprecated. Instead, use mysqli_* functions or PDO. And you could prefere use prepared statement for security reason.
Please note that you're supposed to mention a Javascript function for onClick event. You can't write PHP script here.
One way to overcome this problem is create a separate PHP file which will contain the query.
// page1.php
Unqueue
// action.php
<?php
$temp_id = $_GET['stu_id'];
mysql_query("UPDATE tbl_studentdetail SET stu_queue = 0 WHERE stu_id = $temp_id");
header("Location:page1.php");
?>"
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
html.php
how to call Delete($passid) function in button on Click.
<?php
function Delete($passid)
{
echo "Delete $passid";
}
?>
<button name="Delete" id="Delete" onclick="Delete($row['ID'])" >Delete</button>
I am assuming this is what you're after? - Assuming you're trying to edit the DOM using javascript
JS
function Delete(passid)
{
//Do something with passid variable
}
HTML
<button id="Delete" onclick="Delete(this.id)" >Delete</button>
(also removed name since you don't seem to be using it)
So when the button is clicked, it calls the javascript function "Delete" and passes the button's id to it (in this case "Delete")
If not, perhaps this? - Assuming you are trying to delete a row from a mysql database and you're sending the variable from your HTML to your php on the button's click
Assuming you have a database connection setup, and that there exists a table named 'table' that meets some 'condition' to get all rows matching this criteria's 'id' column value
connection setup should be in all php files that link to the database
(You can use the include function for this instead of writing it 100 times)
i.e. include("path/to/file/connection.php")
PHP populates HTML
<?php
$query = mysql_query("SELECT * FROM table WHERE condition");
while($row = mysql_fetch_array($query))
{
echo '<span>'.$row["id"].'</span>
<button class="Delete" value='.$row["id"].'>Delete</button>';
}
?>
JQuery
$(".Delete").click(function()
{
var id = $(this).attr("id");
$.ajax({
type:"POST",
url:"file.php",
data:{id:id}
});
});
PHP ---> file.php runs function
<?php
if(isset($_POST["id"]))
{
$id = $_POST["id"];
$query = mysql_query("DELETE FROM table WHERE id='$id'");
}
?>
This would delete the database table row where id is set to the id that we pass it from the HTML button's value.
So this function does the following:
Gets all ids from database table where the condition is met
Populates the HTML page with a span tag showing us the id of the element next to the button that will delete the same element
When a button is clicked, our jQuery click event captures it
jQuery function gets clicked button's id and sends it to the ajax function
Ajax function uses the post method to send the variable id to the document file.php
file.php checks to see whether or not the variable id that was sent through the post method actually exists
If the post variable id exists, it sets $id to it.
Query called to delete a table row in our database where id is equal to $id (our initial button's id value generated by the table itself)
You must use a form and submit button to POST data, then call this function with parameter from $_POST['passid'].
Use a AJAX post data and process same option 1
<form action="" method="post">
<input type="hidden" name="delID"> <?php echo $row['ID']; ?>
<input type="submit" value>
</form>
<?php
if($_POST)
{
$id=$_POST['delID'];
function delete($id)
{
echo $id;
}
}
?>
else use ajax --->
<input type="button" onclick="Delete($row['ID'])" name="delete" value="Log In" />
<script>
function Delete(e) {
alert(e);
$.ajax({
type: "POST",
url: "script.php",
data:{"delete":e},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
in php
if(isset($_POST))
{
$id=$_POST['delete'];
echo "Delete ".$id;
}
I want to be able to change the text of some pages. Using contenteditable would be perfect for me.
Problem is that I only know how to program in PHP. I have searched on the internet for hours trying to make it work, but I just don't understand the programming languages used to store the data enough to make it work.
This is how I would like it to work:
Admin hits a button 'edit'
div becomes editable.
When the admin is ready editing, he hits a button 'save'
The data is saved to a file or database (don't really know what would be the best option).
The edited content shows up when the page is opened.
This is all I have for now:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
I know how to make the part with converting the div to an contenteditable div when the admin hits 'edit'.
My problem is that i really have no idea how to save the edited data.
I also don't know if it would be hard to retrieve the data from a file, depents on the way how the data is saved. If it is saved to a database I would have no problem retrieving it, but I don't know if that is possible and if that is the best option.
Thanks for your help,
Samuël
EDIT:
#gibberish, thank you so much for your super-quick reply!
I tried to make it work, but it doesn't work yet. I can not figure out what i'm doing wrong.
Here's my code:
over_ons.php:
<div class="big_wrapper" contenteditable>
PAGE CONTENT
</div>
<input type="button" value="Send Data" id="mybutt">
<script type="text/javascript">
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'sent_data.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
</script>
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
$tekst=$_POST['myTxt'];
$query="UPDATE paginas SET inhoud='" .$tekst. "' WHERE id='1'";
mysql_query($query);
?>
Thanks again for your great help!
Can you also help me to make the div editable only when the user hits a button?
SOLUTION:
It took me over 2 weeks to finally make everyting work. I had to learn javascript, jQuery and Ajax. But now it works flawlessly. I even added some extras for the fanciness :)
I would like to share how i did this if someone wants to do the same.
over_ons.php:
//Active page:
$pagina = 'over_ons'; ?>
<input type='hidden' id='pagina' value='<?php echo $pagina; ?>'> <!--Show active page to javascript--><?php
//Active user:
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin'){
$editor = $_SESSION['gebruikersnaam']; ?>
<input type='hidden' id='editor' value='<?php echo $editor; ?>'> <!--Show active user to javascript--><?php
} ?>
<!--Editable DIV: -->
<div class='big_wrapper' id='editable'>
<?php
//Get eddited page content from the database
$query=mysql_query("SELECT inhoud FROM paginas WHERE naam_pagina='" .$pagina. "'");
while($inhoud_test=mysql_fetch_array($query)){
$inhoud=$inhoud_test[0];
}
//Show content
echo $inhoud;
?>
</div>
<!--Show edit button-->
<?php
if(isset($_SESSION['correct_ingelogd']) and $_SESSION['functie']=='admin')
{?>
<div id='sidenote'>
<input type='button' value='Bewerken' id='sent_data' class='button' />
<div id="feedback" />
</div>
<?php }
As this is a pretty long and complicated file, I tried to translate most of my comments to english.
If you want to translate something that in't already translated, the original language is Dutch.
javascript.js:
//If the system is in edit mode and the user tries to leave the page,
//let the user know it is not so smart to leave yet.
$(window).bind('beforeunload', function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Verstuur bewerkingen'){
return 'Are you sure you want to leave the page? All unsaved edits will be lost!';
}
});
//Make content editable
$('#sent_data').click(function(){
var value = $('#sent_data').attr('value'); //change the name of the edit button
if(value == 'Bewerken'){
$('#sent_data').attr('value', 'Verstuur bewerkingen'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
$('#feedback').html('<p class="opvallend">The content from<BR>this page is now<BR>editable.</p>');
}else if(value == 'Verstuur bewerkingen'){
var pagina = $('#pagina').val();
var editor = $('#editor').val();
var div_inhoud = $("#editable").html();
$.ajax({
type: 'POST',
url: 'sent_data.php',
data: 'tekst=' +div_inhoud+ '&pagina=' +pagina+ '&editor=' +editor,
success: function(data){
Change the div back tot not editable, and change the button's name
$('#sent_data').attr('value', 'Bewerken'); //change the name of the edit button
var $div=$('#editable'), isEditable=$div.is('.editable'); //Make div not editable
$div.prop('contenteditable',!isEditable).toggleClass('editable')
//Tell the user if the edditing was succesfully
$('#feedback').html(data);
setTimeout(function(){
var value = $('#sent_data').attr('value'); //look up the name of the edit button
if(value == 'Bewerken'){ //Only if the button's name is 'bewerken', take away the help text
$('#feedback').text('');
}
}, 5000);
}
}).fail(function() {
//If there was an error, let the user know
$('#feedback').html('<p class="opvallend">There was an error.<BR>Your changes have<BR>not been saved.<BR>Please try again.</p>');
});
}
});
And finally,
sent_data.php:
<?php
session_start();
include_once('./main.php');
include($main .'connectie.php');
//Look up witch page has to be edited
$pagina=$_POST['pagina'];
//Get the name of the person who eddited the page
$editor=$_POST['editor'];
//Get content:
$tekst=$_POST['tekst'];
$tekst = mysql_real_escape_string($tekst);
$query="UPDATE paginas SET naam_editer='" .$editor. "', inhoud='" .$tekst. "' WHERE naam_pagina='" .$pagina. "'";
}
if(mysql_query($query)){
echo "<p class='opvallend'>Successfully saves changes.</p>";
}else{
echo "<p class='opvallend'>Saving of changes failed.<BR>
Please try again.</p>";
}
?>
Use a client-side language, such as JavaScript (or best, jQuery), to manage whether the input boxes could be edited.
Use AJAX to grab the field data and fire it off to a PHP file, which would stick the data in your database.
Here is a very simplified example of using jQuery to manage enabling/disabling the input fields:
jsFiddle Demo
$('.editable').prop('disabled',true);
$('.editbutt').click(function(){
var num = $(this).attr('id').split('-')[1];
$('#edit-'+num).prop('disabled',false).focus();
});
$('.editable').blur(function(){
var myTxt = $(this).val();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
PHP file: some_php_file.php
<?php
$myVar = $_POST['varname'];
$secondVar = $_POST['anothervar'];
//Now, do what you want with the data in the vars
Using AJAX is quite easy. I gave a very brief example of what it would look like. Don't look in the HTML or jQuery for the moreTxt variable -- I added that to show how you would add a second var of data to the ajax.
Here are some basic examples to bring you up to speed on ajax:
AJAX request callback using jQuery
There is no short path to learning jQuery or AJAX. Read the examples and experiment.
You can find some excellent, free jQuery tutorials here:
http://thenewboston.com
http://phpacademy.org
UPDATE EDIT:
To respond to your comment inquiry:
To send data from a DIV to a PHP file, first you need an event that triggers the code. As you mentioned, on an input field, this can be the blur() event, which triggers when you leave a field. On a <select>, it can be the change() event, which triggers when you choose a selection. But on a DIV... well, the user cannot interact with a div, right? The trigger must be something that the user does, such as clicking a button.
So, the user clicks a button -- you can get the content of the DIV using the .html() command. (On input boxes and select controls, you would use .val(), but on DIVs and table cells you must use .html(). Code would look like this:
How to send DIV content after a button clicked:
HTML:
<div class='big_wrapper' contenteditable>
PAGE CONTENT
</div>
<input id="mybutt" type="button" value="Send Data" />
jQuery:
$('#mybutt').click(function(){
var myTxt = $('.big_wrapper').html();
$.ajax({
type: 'post',
url: 'some_php_file.php',
data: 'varname=' +myTxt+ '&anothervar=' +moreTxt
});
});
You could save the whole
page clientside with this:
<script>
function saveAs(filename, allHtml) {
allHtml = document.documentElement.outerHTML;
var blob = new Blob([allHtml], {type: 'text/csv'});
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
</script>
hth
I am making a exam portal in which i have option conducting exam/quiz. Now i have added 2 buttons namely Next and Previous . I wanted to fetch Question and its option on button Click.
My database has following structure: Question(qid,question,option1,option2,option3,option4,right_option)
What I am tryin to do:
<input id="first" type="button" value="NEXT" onClick = "show_next()">
<input id="second" type="button" value="PREV" onClick = "show_prev()">
<script>
function show_next()
{
<?php
$question_no; //my global php variable to keep track of question id
$question_no = $question_no + 1;
show_question($question_no); //php function which shows data according to question no
?>
}
function show_prev()
{
<?php
if($question_no>0)
{
$question_no = $question_no-1;
show_question();
}
else
{
?>
alert("Wrong Operation");
<?php
}
?>
}
</script>
I am new to php and javascript, please suggest the correct method and if possible coding snippet for my question
Use jQuery/AJAX.
All you have to do is manage Offset and Limit dynamically.
e.g.
lets consider you are showing 1 question at a time and its options.
your html file will be.
<input id="first" type="button" value="NEXT" onClick = "show_next()">
<input id="second" type="button" value="PREV" onClick = "show_prev()">
<input id="offset" type="hidden" value="0">
In your javascript file
function show_next()
{
var offset=$('#offset').val();
$.post('GetQuestion.php',{offset:offset},function(data){
$('#question_answer').html(data);
$('#offset').attr('value',offset+1);
})
}
function show_prev()
{
var offset=$('#offset').val();
$.post('GetQuestion.php',{offset:offset},function(data){
$('#question_answer').html(data);
$('#offset').attr('value',offset-1);
})
}
In your GetQuestion.php file you can access offset value using $_POST. All you have to do is use that value in your query.
mysql_query("SELECT * FROM questions LIMIT ".$_POST['offset'].",1");
echo your query result in php file so that it could be available to var data in javascript.
As far as i know, PHP is executed on the server and the JS is executed Client-Side, so you can't mix it.
You have to Options.
Load all Questions in different divs and hide them. Then you can show one by one with the next and the previous buttons.
Build the page with a parameter like this: http://myapp.com/question/1 And make the Next BUtton /question/2 The question page should now contain only 1 question.
Edit:
Here is a fiddle for the 1. method:
http://jsfiddle.net/zj7ts/
$('.question').hide()
$question_shown = $('.question').first().show();
$('.next').click(function(){
$('.question').hide()
$question_shown = $question_shown.next().show();
});
$('.prev').click(function(){
$('.question').hide()
$question_shown = $question_shown.prev().show();
});
I have a column that has a button that when pressed, links to a URL set in PHP. I want to add a checkbox next to that button so that if it's checked when a user presses the button, it will take them to an alternate url. The PHP code setting the url:
<?php
$link = 'http://www.example.com';
?>
I realize that the code needs to be in javascript, which I don't know. I know only a tiny bit of php, so any help would be apprciated.
To clarify: (and of course I know this code will never work)
What I want to do is this:
<?php
If (checkbox is checked) {
$link = 'http://www.google.com';
} else {
$link = 'http://www.example.com';
}
?>
There is probably another way to do what you want to achieve. The value of the checkbox should be sent to a single php script on the server with the rest of the form's fields' values. Then you can use the checkbox's value (boolean) in php and do what you need to do accordingly, possibly requiring external scripts.
Checkbox value is not sent to server with form submit if it is not checked.
So, you can use something like this:
<?php
if (isset($_POST['checkbox_name'])) {
$link = 'http://www.google.com';
}else{
$link = 'http://www.example.com';
}
?>
Include the jQuery from Google:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
Then write the redirect function which you call after clicking the button;
<script>
function foo() {
if ($('#checkbox').is(':checked')) {
//redirect to google.com
window.location = "http://www.google.com/";
} else {
window.location = "http://www.example.com/"
}
}
</script>
And finaly your button should look like this:
<button onclick="foo();" >Your button</button>
This code assumes your checkbox has an id "checkbox".
Also, I don't think that what you're trying to do should be done with PHP - so you should learn Javascript/jQuery straight away instead of writing code the way it shouldn't be written.
Example: http://jsfiddle.net/5bdae/
Using jQuery this is fairly simple. You bind a function to the link, this function works out whether the checkbox is checked, if it is it links to one place, otherwise it links to another.
For an HTML structure like this:
<input id='myCheckbox' type="checkbox" name="box" value="box" />
<a href='#' id='myLink'>My Link</a>
The jQuery would be:
$('#myLink').click(function(event){
event.preventDefault();
if ($('#myCheckbox').is(':checked')){
window.location.href='http://www.example.com';
} else {
window.location.href='http://www.ask.com';
}
});
This could would go outside of the PHP tags, and you would need to include jQuery in your code.
So what I am doing is trying to create a 'favorite' system. I want the user to click a button and the code on the page will submit a value into a MySQL Database. Does this need to the page need to reload if the only thing I am doing is submit and value. I am not pulling any information from the database on the button's click. Thank you:)
A great way to avoid the complexities of Ajax and cross-browser compatibility is to use Jquery!
In your non-reloading page, you can put this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script text="text/javascript">
$(function() {
$('#button_id').click(function() { //in place of "button_id" you need to put your button's id
submitInformation("some information you want to send");
});
});
function submitInformation(data1)
{
$.post(
"handle.php", //this is the name and location of your php page
{
"input_var_one":data1,
}
);
}
</script>
and in your handler php page (in this case called "handle.php")
<?php
$inData1 = $_POST['input_var_one'];
//after your mysql_connect and mysql_select_db
$query = "INSERT INTO `yourtablename` VALUES ('var1 whatever you want', '$inData1')";
mysql_query($query);
?>
Jquery handles the Ajax request for you!
If you do not use AJAX, the information must be sent to the server in order to get to a mysql database table and processed by php and that surely requires page reload.
you can use:
<script type="text/javascript">
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
function onthatbuttonclick(something)
{
window.xhr.open('GET', "somephp.php?click="+something, false);
window.xhr.send(null);
alert(window.xhr.responseText);
}
var somevar = "user 01";
</script>
<input type="button" onclick="onthatbuttonclick(somevar);" />
and in php:
<?php
// some query required code
// and yes... i does require some safety measures:
$val = mysql_real_escape_string($_GET['click']);
mysql_query("INSERT INTO `tabel` (`click`) VALUES ('".$val."')");
echo 'you cliked a button.';
?>
you should now see an alert box with the text: "you clicked a button.".