I have a file named a.php which has a html button with a script function within the same page.Code is given bellow
//a.php
<input name="wpost" type="button" value="Publish" onClick="wall_publish()"/>
<script type="text/javascript">
function wall_publish(){
//some codes here..
//php database part
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'uploader';
$con = mysql_connect($host,$username,$password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
mysql_query("UPDATE image_uploader SET Tag_Count = '$tag_count', Tag_List = '$tag_list' WHERE Image_Link = '$source'");
mysql_close($con);
?>
}
</script>
I want to execute the php database part when the user click the "Publish" button(Not when the page is loaded).,
Is there a way to do this?
Just placing this php code inside the script function doesn't work.It is executed when the page is loaded.
If you want to call PHP code from javascript, the short answer is: you can't. PHP is server side code, and javascript is client side code. They run on different computers.
What you can do, however, is using javascript to send a HTTP request to the server - AJAX. You can then execute the code with the information the javascript has sent with the HTTP request.
Here is a short ajax tutorial from tizag that might get you started:
http://www.tizag.com/ajaxTutorial/
You will have to put the PHP code into a seperate file and make the form action point to that script. Then, when the user clicks the button it will fetch the file and execute the script on the server. If you do not want a page replacement to happen, instead of making a traditional post form, you can run an ajax request upon clicking the button. This will prevent a page replacement.
First you should read some tutorials on PHP and JavaScript, and not just the programming part, but rather the theory part. JavaScript is executed on the client, PHP on the server.
The solution is for JS to make an AJAX request to the server.
<input name="wpost" type="button"id="my_button" value="Publish" />
put this javascript into the head section of your a.php file.
<script type="text/javascript">
$("#my_button").click(function() {
$.post("page.php");
});
</script>
don't forget to include jquery library file as I jquery is used for the solution.
in page.php u should write:
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'uploader';
$con = mysql_connect($host,$username,$password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
mysql_query("UPDATE image_uploader SET Tag_Count = '$tag_count', Tag_List = '$tag_list' WHERE Image_Link = '$source'");
mysql_close($con);
?>
notice you did not assign values for $tag_count, $tag_list.
Don't u want to show any success or failure message after the sql query operation?
Related
I have a button which has a onclick attribute which calls a function. My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.
I've tried different variatons of syntax but nothing worked. I swapped 'button' for 'input type=button' but that didn't help anything.
this is in books.php
$sql = "SELECT books.id, books.name as bookname, authors.name as authorname, autori.surname, genre, description, stock FROM books JOIN authors ON books.author_id=authors.id ORDER BY books.name ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Name of the book</th><th>Author</th><th>Copies available</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["bookname"]."</td><td>".$row["authorname"]." ".$row["surname"]."</td><td>".$row["stock"]."</td>";
if (isAvailable($row["id"]) && isset($_SESSION["id"])) {
?>
<td><input type="button" value="Borrow" class="button" id="btnBorrow" onclick="<?php borrowBook($row["id"])?>"></td></tr>
and I'm calling the function borrowBook from functions.php which looks like this.
function borrowBook($idbook) {
$servername = "aaa";
$username = "bbb";
$password = "ccc";
$dbname = 'ddd';
$iduser = $_SESSION["id"];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE books SET stock = stock - 1 where id = " . $idbook;
$conn->query($sql);
$sql = "INSERT INTO reservations(id, dateBorrowed, dateReturn, returned, kniha_id, uzivatel_id) VALUES (NULL, NOW(), DATE_ADD(NOW(), INTERVAL 34 DAY), 0, $idbook, $iduser)";
$conn->query($sql);
}
So the SQL query and everything actually works. When I check the database I actually get new entries and everything is as expected. The only problem I'm having is that the button's onclick event is always triggered on every page load and I can't seem to fix it. From searching online everybody is using stuff like JavaScript or jQuery so it didn't really help me.
Hi and welcome to Stack Overflow!
Looks like you are trying to call php function from the client (browser). This is however impossible.
The way the PHP works is, that it prepares the content for the client and sends it to the client. After it is send, you cannot interact with the PHP code anymore. What you need to do is make client send another request.
My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.
The page load does not trigger onclick event. The PHP looks for all <?php and runs the code inside it even before it is sent to client.
How to do it?
You need to change the infrastructure a bit. For the beginning i'd suggest not using JS at all, but instead create second PHP page, that just does the borrowBook using GET parameter (you can expand it later) (See PHP's $_GET)
First you need to actually create the second page (let's call it borrowBook.php)
This page will get book's id using GET parameter (let's call that bookid)
This page's code may look something like this (Note: code is not tested)
<?php
borrowBook($_GET["bookid"]);
header("Location: /books.php");
?>
And now you need to change original code's line
<input type="button" value="Borrow" class="button" id="btnBorrow" onclick="<?php borrowBook($row["id"])?>">
To something like this
Borrow
What this does is, that PHP sees <?= and run the code inside it (in this case replaces the <?= ?> section with value of $row["id"]. Which if id is 1 will result in this:
Borrow
Sorry for my bad english.
You should use js (or jquery) in onclick handler that call your php-script with ajax.
PHP scripts works only in server.
Like this (jquery example):
<button id="handled-button">Click Me</button>
<script>
$('#handled-button').click(function() {
$.get('/myscript.php');
});
</script>
And in myscript.php call your function.
I am trying to create a simple chat application. Below, you notice that my PHP code is inside a div, which is for the chat data, and that div is inside another div representing the chat box. Inside my PHP code, I wrote my PHP function. It connects to the myPHPadmin server and then it has a query to place the inputted data from the person's name into the database. I have an echo statement to write what the person wrote. As soon as I press the submit button, it will show what the person wrote, but if I type another message in, the message text gets replaced. How do I get my PHP code to dynamically create echo statements as if it were a chat conversation? It should create a new line each time I send a message.
<div id="chat_box">
<div id="chat_data">
<?php
function sendMessage()
{
//I hid my login credentials
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$dbc = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($dbc->connect_error)
{
die("Connection failed: " . $dbc->connect_error);
}
$name = $_POST['name'];
$msg = $_POST['log'];
$query = "INSERT INTO `chatApp` (`name`, `pwd`, `message`) VALUES ('$name', NULL, '$msg')";
$run = $dbc->query($query);
echo "<p>" . $name . " : </p> ";
echo "<p>" . $msg . "</p>";
}
?>
</div>
</div>
Use Ajax (Asynchronous Javascript and XML) to fullfill your requirement.
Since, PHP is a server side programming language, on clicking submit button the page need to contact with the server and should refresh for getting data.
Ajax will remove the headache of refreshing and get the data from the server on the way without refreshing your page.
Learn the basics of Ajax and apply it in your project on your own.
I was actually trying to retrieve the input submit button value. But I don't know why it does not work. Can anyone help me?
When the user click the buttons, the button's value will be send to the next page.
<?php
include('connect.php');
// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM userauth";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
?>
<html>
<head>
<title>GAF APPS</title>
</head>
<body>
<form method="post" action="branch.php">
<input type="submit" name="submit" value="<?php echo $row["Company"]; ?>">
</form>
</body>
</html>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is where I was going to retrieve the value:
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>
You don't have an input named "action", therefore the isset() will never happen which is why you did not get an error for it
Having added an else condition for it, would have shown you that instead.
When debuging in PHP I tend the use the shotgun approach and output everything that could be remotely interesting and then narrow it down.
So when looking at parsing form variables use echo var_export($_GET, true) or vardump($_GET).
Not sure if GET or POST? Use _REQUEST which has both in 1 variable.
Use the HTML tag to make it more readable and htmlspecialchars() to convert characters that would normally be invisible because of your browser.
Using those will make it far easier to see what you are doing with your form.
So to answer the above question:
Look at the the mentioned request variables and determine by looking at the HTML and the code if the expected variables should be parsed and send by the browser when the submit button is pressed.
AND
See if the values actually received by PHP will have the expected outcome when handled.
Try to keep those 2 things separate, because what is in your HTML now does not mean it was there when you parsed the form. That's a bit of a bind when developing with PHP/HTML and forms, when you change the code and do not fully reload, but just press Submit on the form:
the code that will parse the current form will be changed, but the contents of the form parsed are the ones that where loaded in your browser and might be out dated.
So I have a simple working user log in script that carries forward myusername and mypassword.
What I am trying (and failing) to do is recall a specific piece of information from that users Mysql database to modify the page that they are on.
MYSQL DATABASE ('members'):
id:1
username:cornellmatt
password:encrypted(md5)
email:example#email.com
active: 0/1
**permission:1**
The field I need to extract is permission, as it holds the number that will relate the the scene that the user is currently on.
In order to do this I am running Jquery on the page that you arrive at after logging in, that links to connect.php
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$.get("connect.php", function(data) {
alert("Data Loaded: " + data);
});
I understand that there are all kinds of problems with my JavaScript at the moment, but for now I want to get the server side stuff done so I can focus on the JavaScript fully
The (Current) problem with my Php is that it doesn't seem to be getting anything from the database at all, I know it is connected, it just wont echo the value inside 'permission';
connect.php:
<?php
include "Session.php";
$dbhost = "host";
$dbuser = "username";
$dbpass = "password";
$dbname = "databasename";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
//this selects everything for the current user, ready to be used in the script below
$result = mysql_query("SELECT * FROM members WHERE username = '$myusername' LIMIT 1");
//this function will take the above query and create an array
while($row = mysql_fetch_array($result))
{
//with the array created above, I can create variables (left) with the outputted array (right)
$permission = $row['permission'];
}
echo '<u><b>Permision ID:</b></u> - - No:' . $row['permission'] ;
?>
If you are wondering what'Session.php' is, it is a script that handles the startup, and is the reason I know I am still logged in. Courtesy of Daryl Gill who helped me in a previous post.
Session.php
<?php
session_start();
if (!isset($_SESSION['Username']))
{
include "Logout.php";
exit;
// session is not set, so enforce logout
}
?>
So my quest is, Why doesn't connect.php echo the value permission, even when I go to the page direct? Please help, I am currently coding this for my student project and have been going in circles for days.
When $_SESSION['Username'] is not set you have putted exit;
And because of that it doesn't prints permission
And When you do Ajax call may be the $_SESSION['Username'] is set and it prints permission.
Also change
echo '<u><b>Permision ID:</b></u> - - No:' . $row['permission'] ;
to
echo '<u><b>Permision ID:</b></u> - - No:' . $permission;
Because outside while loop you can't access $row['permission'].
$row['permission'] doesn't exist here. You just need $permission.
echo '<u><b>Permision ID:</b></u> - - No:' . $permission;
Make sure you get any rows by doing this:
while($row = mysql_fetch_array($result)) {
var_dump($row);
$permission = $row['permission'];
}
Have searched for the answer but no joy, so here goes...
I'm working on a mobile hybrid app. I want the user to fill in their id number, which is then submitted to a javascript function for basic validation, then kicks in a jQuery.getJSON request to my serverside PHP which returns the data and then my jQuery will repopulate the form div with the data.
Currently it doesn't really work at all in Firefox, and only works correctly in Safari after I press the submit button for a second time. It returns the correct data, so the link is ok.
My problem is: Why does the div not get repopulated after the first click?
HTML:
<div id="login540div">
<form id="login540form" onSubmit="login540()">
Enter Student ID number<input type="text" name="login540id" id="login540id"/>
<input type="submit" value="Submit" />
</form>
</div>
Javascript:
function login540(){
// validates the data entered is an integer.
var loginNo = document.getElementById("login540id").value;
//if(!isNaN(loginNo))
if((parseFloat(loginNo) == parseInt(loginNo)) && !isNaN(loginNo))
{
//jSonCaller(loginNo);
$.getJSON('http://localhost:8888/c05673160/login540.php?q='+loginNo, function(data){
//alert(data);
$('#login540div').html("<p>First Name ="+
data.firstName+
"</p> Last Name ="+data.lastName+" </p>Module No.1 ="+
data.moduleNo1+"</p> Module No.2 ="+
data.moduleNo2+"<p> Course ID="+
data.courseID+"</p>");
})
}
else
{
// alert(loginNo); CHECKED
alert("Please make sure to insert only a whole number");
}
Then the PHP goes like this...
<?php
include ("config.php");
/*
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
$var = array('i'=>10, 'j'=>20);
$firephp->log($var, 'Iterators');
*/
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'collegeData';
$q=$_GET["q"];
$table = "studentTable";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table} WHERE studentID = '".$q."'");
if (!$result)
die("Query to show fields from table failed!" . mysql_error());
$json = array();
while($row = mysql_fetch_array ($result))
{
$json = array(
'firstName' => $row['firstName'],
'lastName' => $row['lastName'],
'moduleNo1' => $row['moduleNo1'],
'moduleNo2' => $row['moduleNo2'],
'courseID' => $row['courseID']
);
}
$jsonstring = json_encode($json);
echo $jsonstring;
mysql_close($conn);
?>
I can't figure out what's wrong, and I've been messing around with various things for the last few days trying to fix it, but no joy, so I'd really appreciate any help you can give.
#Robbie had a good point that you don't appear to be stopping the default behavior of the form submission. To do this you need to change a couple things:
onSubmit="login540()" needs to change to onSubmit="return login540()" otherwise whatever you return from the login540() function will be ignored.
At the end of the login540() function you need to return false; to stop the form from submitting normally. You can also pass in the event object as the first argument and use event.preventDefault() instead: function login540(event){event.preventDefault();...}.
To do yourself a favor however, you can use jQuery to bind the submit event handler to the form rather than using inline JS (tisk, tisk, :) )
$('#login540form').on('submit', login540);
This way you can keep all of your JS in one place rather than spread-out all over your HTML.
The bottom of Function login540() is missing, but this needs to kill the default "submit" action: this can be done with "return false;" at the end. As I can't see the end, not sure if this happens or not, but the form probably "submits" while the AJAX is running.
This is compounded as the form doesn't have an action, which probably explains the different browser behaviour. I suggest setting action to "#" and then, if you see "#" added in the URL then the form has submitted and not been stopped by your function.