how to run a php function in javascript [duplicate] - javascript

This question already has answers here:
How can I call PHP functions by JavaScript?
(13 answers)
Closed 8 years ago.
<?php
session_start();
function printTable() {
$server = "XXXXXXXX";
$user = "XXXXXXXXX";
$password = "XXXXXXXX";
$database = "XXXXXXXX";
$conn = mysql_connect($server, $user, $password);
mysql_selectdb($database, $conn);
$query = "SELECT Image, ISBN, Name, Vol, Release_date, publisher, price FROM products p";
$resultset = mysql_query($query, $conn); // retrieve data from database
if ($resultset == null || $resultset == 1) {
echo mysql_error(); // print SQL error
die(); // exit PHP program
}
$numFields = mysql_num_fields($resultset);
echo "<table border=2 align=center><tr>";
echo "</tr>";
for ($i=0; $i<(mysql_num_rows($resultset)); $i++) { // print records
$fields = mysql_fetch_row($resultset);
echo "<tr>";
echo "<tr class=$color><td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
$fields = mysql_fetch_row($resultset);
if ($fields == null) break;
echo "<td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close();
?>
<html>
<head>
<script>
function combine(value1, value2, value3) {
alert (value1 + value2 + value3);
//setcookie(value1);
}
</script>
</head>
<title>
Product Page
</title>
<body>
<body style="background:#A2A2AE">
<h1> <center> Product Page </center> </h1>
<p><center>-----------------------------------------------------------------------------------------------------------------------------------------------------------</center></p>
<?php printTable(); ?>
</body></html>
how I can run the function addcookies() to save value 1 as the cookies... Thank you!
function addcookies(value) {
$pid = $_POST['pid'];
$expiry = time() + 60 * 60 * 24 * 30;
// Update the number of items
if(isset($_COOKIE['count']))
$count = $_COOKIE['count'];
else
$count = 0;
// Put the item into shopping cart
$key = "item: ".$count;
setcookie($key, $pid, $expiry);
setcookie("count", $count+1, $expiry);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

First of all, your html code isn't correct. You oppened body tag 2 times and your title tag is out of the head tag, it's not even in the body.
As Biffen said in the comment, you cannot run the php after the page has loaded. Instead, you can use ajax. Ajax Documentation
You have to create a file with your php code inside it, and then execute it with ajax without reloading the page. And as I see you have written in a comment: "Put the item into shopping cart". Do not store shopping cart items in, neither, browser cookies nor session. Use your database instead because data stored in either cookies or session will be vulnerable.

Related

Updating mySQL table with user interface - PHP

[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
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 $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples

Change button text from "Like" to "Liked" when clicked

I am creating a forum where users are able to like and unlike posts and comments. The challenge I'm facing is that I would like the text of the like button to change without reloading the page. How can I go about differentiating between the buttons on the page and change individual button-texts from "Like" to "Liked" and vice versa? The buttons are, at the moment created and show like this:
<?php
$result3=mysqli_query($link, "SELECT * FROM cs_comments WHERE post_id = $postID");
while($row3 = mysqli_fetch_assoc($result3)){
$commentID=$row3['comment_id'];
$memberID=$row3['member_id'];
$likes=$row3['likes'];
$content= $row3['content'];
$anonymous=$row3['anonymous'];
if($anonymous=='1')
$name='Anonym';
else{
$result4= mysqli_query($link, "SELECT firstname, lastname FROM cs_members WHERE member_id = $memberID");
$row4=mysqli_fetch_assoc($result4);
$name = '' . $row4['firstname'] . " " . $row4['lastname'] . '';
}
$result5=mysqli_query($link,"SELECT * FROM cs_likes WHERE comment_id=$commentID AND member_id={$_SESSION['memberID']}");
if(mysqli_num_rows($result5)!=0)
$liked="unlike";
else
$liked="like";
echo '<div class="post_container">';
echo ' <div class="info_header">';
echo ' <div class="info_name">' . $name . '</div>';
echo ' <div class="info_group"></div>';
echo ' </div>';
echo ' <div class="post_content">';
echo $content;
echo ' </div>';
echo ' <div class="post_footer">';
echo ' <div class="like_button"><button onclick="likeComment('. $commentID . ')">' . $liked . '(' . $likes . ')</button></div>';
echo ' </div>';
echo '</div>';
}
mysqli_close($link);
?>
Javascript for onclick-event:
function likeComment(id) {
$.ajax({
url: '/resources/phpScript/like.php',
type: 'POST',
data: {comment_id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
Like.php
<?php
session_start();
include "./db-connect.php";
$memberID= $_SESSION['memberID'];
if(isset($_POST['post_id'])){
$postID=mysqli_real_escape_string($link,$_POST['post_id']);
$sqlCheck="SELECT * from cs_likes WHERE post_id = $postID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (post_id, member_id) VALUES ('$postID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE post_id= $postID AND member_id = $memberID";
}
elseif(isset($_POST['comment_id'])){
$commentID=mysqli_real_escape_string($link,$_POST['comment_id']);
$sqlCheck="SELECT * from cs_likes WHERE comment_id = $commentID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (comment_id, member_id) VALUES ('$commentID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE comment_id= $commentID AND member_id = $memberID";
}
else
echo "Something went wrong";
$checkResult=mysqli_query($link, $sqlCheck);
if(mysqli_num_rows($checkResult)==0)
$result=mysqli_query($link,$sqlInsert);
else
$result=mysqli_query($link,$sqlDelete);
?>
Any help is appreciated!
So I found the solution! I have little to no experience with javascript, which is why this may have been too simple of a question for anyone to find out what I was after!
This is what I did:
I simply sent the element clicked by adding this to the function call on click:
echo ' <div class="like_button"><button onclick="likePost('. $postID . ',this)">' . $liked . '</button></div>';
I then added this tiny bit to my function:
function likePost(id, elem) {
if(elem.innerHTML== "like")
elem.innerHTML="unlike";
else
elem.innerHTML="like";
I still want to thank everyone who made and effort to try understanding what I was asking.

Not receiving dynamically generated form data

i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter

Popup inside the window

Right now I have a grid and each grid part/bit contains an image, the name of the item and different buttons that can delete the item from the mysql database and update the price. What I want to do know is that when a user say clicks on the image a window would pop up where extra information would be displayed. However it is not a pop up in a usual sense that it would create another window but rather a pop up within the current window/tab. E.g. When you press on a photo in Facebook it creates almost like a popup on which you can comment or change to the next photo. Does anyone have any idea on how to do this or at least what is the whole thing/process called?
Sorry if I can't give a proper name but I don't know it myself :/
Here is the code to what I have now. I would prefer an actual code solution but if you can lead me to where I should look for it I would also be happy. I tried looking online however everything I get is window pop ups.
<div class="boxes">
<?php
$ID = $_SESSION['SESS_MEMBER_ID'];
$con = mysql_connect("", "", "");
if (!$con){
die("Cannot connect: " . mysql_error());
}
mysql_select_db("test", $con);
$sql = "SELECT * FROM items WHERE member_id = $ID";
$myData = mysql_query($sql, $con);
$dir = 'Images';
$symbol = '\\';
$end = 'r.jpg';
$currency = '£';
while($record = mysql_fetch_array($myData)) {
$real_name = str_replace('_', ' ', $record['Name']);
$result = $dir . $symbol . $record['Name'] . $end;
$value = $currency . $record['price_now'];
$link = $record['url'];
echo "<div class = frame>";
echo "<div class = bit-3>";
echo "<div class = box>" . "<img src=" . $result . " alt=some_text>";
echo "<br />";
echo "<br />";
echo $real_name;
echo "<br />";
echo "<br />";
echo "Price now: " . $value;
echo "<form action = member-profile-page.php method = post>";
echo "Desired price: ";
echo "<td>" . "<input type = text name = desired_price value = " . $record['desired_price'] . " </td>";
echo "<td>" . "<input type = hidden name = hidden value = " . $record['Id'] . " </td>";
echo " ";
echo "<td>" . "<input type = submit name = update value = Update" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = delete value = Delete" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = buy value = Buy" . " </td>";
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
if (isset($_POST['buy'])){
$query = "select url from items where Id = '$_POST[hidden]'";
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
$code = $row['url'];
echo "$code";
header("Location: $code");
}
};
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE items SET desired_price = '$_POST[desired_price]' WHERE Id = '$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM items WHERE Id = '$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
mysql_close($con);
?>
</div>
Sounds like you're looking for an overlay:
http://jquerytools.org/demos/overlay/index.html
or a modal:
https://jqueryui.com/dialog/
These are by no means the only examples; there are hundreds of such solutions. These will get you started, though. Good luck!
What you think about is just a layer in the current browser viewport, having some controls to let the user handle it like a "desktop window".
There are quite a lot of JS frameworks offering handy solutions for this, i.e. jQuery UI. Within there, look for "dialog"

Clickable data displayed from mysql using PHP

I'm not very good at JavaScript but here is my problem.
I have three pages: page1.php, page2.php, page3.php
On page1.php, I have a form for users to select grade level they want to view, then the action is performed on page2.php -- displaying the list of all students in that grade.
This is the code for page2.php
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
The question...now is How can I write the code on page3.php so that when users clicks on view or sdq button next to each column, the student ID should be captured, send a request to the database, and query other data related to this particular student such as age, address, phone..etc. and display them on that page3.php
page2.php
You have to add a hidden input with the id of the student in page2.
<input type="hidden" value="'.$row["std_id"].'" name="std_id">
Change your action page to page3 (if that's where you want to display the student info: name, age...)
<form action='page3.php' method='post'>page2.php
The code for page2:
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$level = $_POST['level_group'];
$room = $_POST['room_group'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT std_id, std_name FROM students WHERE std_level LIKE '$level%' AND std_room LIKE '$room';");
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Action</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo"<form action='page3.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td> <input type='hidden' value='" . $row["std_id"] . "' name='std_id'>";
echo "<input type='submit' value='view'>";
echo "<input type='submit' value='sdq'></td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
page3.php
A posible solution for page3 can be: (add your columns you need: age, address, phone..)
<?php
//database variables
require_once('admin_settings.php');
//these variables are from a form used to display the current data
$id = $_POST['std_id'];
$con=mysqli_connect("$host","$dbuser","$dbpass","$dbname");
mysqli_set_charset($con, "utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM students WHERE std_id ='$id';");
echo '<h3>Student detail</h3>';
//table
echo"
<table border='1' id='mytable'>
<tr bgcolor = #99CCFF>
<th><b>Student ID</b></th>
<th><b>Name</b></th>
<th><b>Age</b></th>
</tr>";
//loop through the database
while($row = mysqli_fetch_array($result))
{
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo "<td>" . $row['std_age'] . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
?>
You can modify your code like this. A hidden field will send the student id to the page of view_one_student.php.
while($row = mysqli_fetch_array($result))
{
echo"<form action='view_one_student.php' method='post'>";
echo "<tr bgcolor = '#c0eae4n' id = 'listings'>";
echo "<td name= 'stdid'>" . $row['std_id'] . "</td>";
echo "<td>" . $row['std_name'] . "</td>";
echo '<input type="hidden" value="'.$row["std_id"].'" name="std_id">';
echo "<td>" . '<input type="submit" value="view"> <input type="submit" value="sdq">' . "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con);
On view_one_student.php you have to catch that with:
$_POST["std_id"]
And eventually input that into a sql sentense in view_one_student.php:
$sql = "SELECT * FROM <table> WHERE id=".$_POST["std_id"];
Thats the general idea.

Categories

Resources