how to call php function with value? [duplicate] - php

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;
}

Related

mysql_query executes automatically but not when onClick

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");
?>"

Insert into database using onclick function

I'm developing a kind of question search engine based on Course wise, Subject wise by entering the keyword or question.
Here I am querying the database based on search term against 3 tables namely table_one, table_two, and table_three. Code as follows
<?php
if(isset($_GET['submit']))
{
$query = $_GET['query'];
$query = htmlspecialchars($query);
$query = mysqli_escape_string($link,$query);
$searchTerms = explode(' ', $query);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "question LIKE '%$term%'";
}
}
$subject_id = $_GET['subject'];
$course_id = $_GET['course'];
$min_length = 1;
if(strlen($query) >= $min_length)
{
$res = "SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_one
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_two
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_three
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')";
$raw_results = mysqli_query($link,$res) or die (mysqli_error());
if(mysqli_num_rows($raw_results) > 0)
{
echo "<h3 style='text-align:center;color:#3366CC'><span style='color:#000000'>Search Results For : </span> $query </h3>";
while($results = mysqli_fetch_array($raw_results))
{
echo "<div class='content'>";
echo"<h4 id=".$results['id'].">" .preg_replace("/".preg_quote($query, "/")."/i", "<span class=\"highlight\">$query</span>", $results['question']) . "</h4>";
echo"<p id=".$results['id']."><span style='padding-left:20px'>option A : " .$results['option_a']."</span> <br><span style='padding-left:20px'> option B : ".$results['option_b']."</span><br/><span style='padding-left:20px'>option C : ".$results['option_c'].
"</span><br><span style='padding-left:20px'>option D : ".$results['option_d']."</span><br><span style='padding-left:20px'> option E : ".$results['option_e']."</span><br><span style='color:#253E66;font-weight:bold;padding-left:20px'>Correct Ans : ".$results['correct_ans'].
"</span><br><span style='padding-left:20px'>Question Year : ".$results['question_year']."</span><br><span style='padding-left:20px'>Contributor : ".$results['contributor']."</span><br />
<a onclick=addQuestion('".$results['id']."') href='#'><span class='button'>Add to Question Bank</span></a></p>";
echo "</div>";
}
}
else{
echo "<span style='height:21px;syle=background-color: #F1F0FF;font-size:25px;color:#CC0000'>Your search - $query - did not match any queries.</span> ";
}
}
}
?>
I'm Calling the following addQuestion() function when i click the Add to Question Bank link.
<script>
function addQuestion(val)
{
var conf=confirm("Are you sure you want to add this question to Question Bank")
if(conf){
//Here I Want some code to update my database.
}
}
</script>
The script above displaying confirmation box when i click the button,
My Question is,
After confirmation I want to insert my question into the new table in the database and display message like "Question added" in front of the question permanently as i know i can't write PHP inside Jquery function Any help may appreciated.
You can achieve this by including the ajax.
put the ajax code which may looks like the following:
if(conf){
$.ajax({
type: "POST",
url: "$$phpfilepath",
data: {param:'$$value'},
success: function(data) {
// do the message display code
}
});
}
Don't forget to include the jquery cdn link in the head tag of the html page.
you need to send an ajax request.
you need to send it either by a post or get method to a php script that will return json so you can be updated on the page with results.
the answer above has an example ajax script sent with a post method:
data needs to be sielized if you are submitting it via form or an array.
this should help you
http://www.w3schools.com/php/php_ajax_database.asp
https://api.jquery.com/serialize/
Onclick - You need to do that with ajax. So basically, you need PHP plus javascript involved. You can use Jquery of similar JS library for easy ajax support.
Just and example with jquery library version 1.11.2 how to include:
<head>
<script src="jquery-1.11.2.min.js"></script>
</head>
For example, if this is your input field you want to save and button for submitting:
<input id="title" name="title" />
<input type="submit" value="Save">
Change it to button and give it javascript save() function (can be any name you give).
<input type="button" onclick="save($('#title').val());" value="Save">
In this example, I added 1 param to that save function, which is supposed to grab a value from html input filed with id "title".
On this page, there that html is, you need to include mentioned jquery(or similar) library and also include piece of javascript function for generating ajax request, which is named "save" here.
If you included jquery library, you must call javascript function for saving your data before your tag:
<script type"text/javascript">
function save(){
$.ajax({
type: "POST",
url: "yourpath/yourfile.php",
data: {title: title},
success: function(data) {
alert("Ajax save executed!");
}
});
}
</script>
When javascript function you named save() will execute, it will send POST request to yourpath/yourfile.php
There, you can easily get your POST data by in yourpath/yourfile.php:
if(isset($_POST['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}
If you want to send it with GET, you easily replace POST with GET:
function save(){
$.ajax({
type: "GET",
and also in .php file you write:
if(isset($_GET['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}

Saving data to database using Jquery

I'm creating a browser RPG game. I want to allow a user to save their current stats by updating the mysql db without having to reload the page... So I thought jquery could help.
The user will not be adding their own stats. The stats are generated through user actions, such as solving a challenge. I want the user to be able to save those updated stats to the database whenever they would like.
The issues are:
the jQuery is outputting the echo "saved..." . $stats . ", " . $stats2; before I click the Save button.
When I click save, the database field isn't being updated.
I'm wondering why this isn't working. When I click save, the stats fields shouldn't be 0, but should be the stats that are shown- 11. The database fields should also be updated.
For testing purposes, I've just created js variable var stats that is updated when the arrow keys are pressed.
I call the function updateHUD() to do $('#stats').html(stats); which updates the HTML.
function updateHUD() {
$('#stats').html(stats);
}
Then updateHUD is called after arrow key is pressed.
HTML
<div class="span12">
<button onclick="saveData(stats)" name="input" value="">Save Data</button>
<br /><span id="output"></span><br />
<ul>
<li><b>Stats 1:</b> <span id="stats"></span> </li>
</ul>
</div>
jQuery
//Pass saved data to store in DB
$(document).ready(function() {
saveData();
});
function saveData() {
$.get("php/CRUD.php", {"_input" : $('input[name=input]').val()},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
PHP
<?php
//store all player data in array and save to/update db
include 'DbConnect.php';
session_start();
$stats = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$formvars = array();
array_push($formvars, $stats);
echo $stats;
echo $_SESSION['username'];
$qry = 'UPDATE users SET stats="'.$stats.'" WHERE username="' . $_SESSION['username'] . '"';
$mysqli->query($qry) or die(mysqli_error($mysqli));
echo "saved..." . $stats;
mysqli_close($mysqli);
?>
Output
saved...0 //this should be 11
Stats 1: 11
You do a
$('input[name=input]').val()
but you have named the submit button "input" instead of adding a input box with this name.
But the question is unclear anyways.
You want to give a user the permission to update his stat with the value that he wants? You should update the question to make it more clear since it does not make much sense at the moment.
First your selector where you are getting your data from is incorrect. You need to either change your html...
<button name="input"></button>
to an...
<input type="button" name="input" />
or change your jQuery selector...
$('input[name=input]')
to select the correct element
$('button[name=input]')
Second you need to make sure your button's 'value=""' actually has data in it when the ajax function is being called.
<button onclick="saveData(stats)" name="input" value="[Data Value Goes Here]">Save Data</button>
Finally the reason your jQuery is outputting before you click the the save button is because you are executing the function as soon as the document loads.
$(document).ready(function() {
saveData();
});
Try something more like this:
HTML
<button name="input" value="[data goes here]">Save Data</button>
JavaScript / jQuery
//Pass saved data to store in DB
$('button[name=input]').on('click', saveData);
function saveData() {
$.get("php/CRUD.php", {"_input" : $(this).val()},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
Also you can try using load:
//Pass saved data to store in DB
$(document).ready(function() {
saveData();
});
$.fn.saveData=function(){
$('#divforload').css('display','none');
$('#divforload').load("php/CRUD.php?stats="+$('#stats').val(),function(){$('#divforload').fadeIn();});
}
//Just call the function onClick...
//Need an input called 'stats'
});

i wanted to use next and previous button for fetching data from database using php

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();
});

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 }
});

Categories