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.
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 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.
Well I have a problem with my code:
if ($_POST) {
//send confirmation email (or insert into database, etc...)
if(isset($_POST['del'])) {
$Link = $_POST['del_link'];
$query = "UPDATE comentarios SET del = '1' WHERE id = '".$Link."'";
mysql_query($query) or die ('Error: ' . mysql_error());
//header('Location: http://google.es'); //For debug
}
}
echo '<form name="del" method="post">
<input type="hidden" name="del_link" value="'.$rowComen['id'].'" />
Delete
</form>';
But when I press the link the web refreshes and that's all...
I had tried with: header('Location: http://google.es'); But I don't redirect to google...
And I don't know if the problem is in the post or in the query...
if(isset($_POST['del'])) {
You dont seem to have del form field. so the code inside this if statement is never executed. i think you are trying to check for del_link. so make it as if(isset($_POST['del_link'])) {
Have you checked in your browser if it contains the right value? The form as it is will contain the exact value '.$rowComen['id'].', unless a part of the PHP code is missing and the form is actually inside a string..
[edit]
I see. The form's name is 'del', but that name is never sent. Make the name of your submit button 'del', or add another hidden element. Easier still: Just check for the existence of del_link instead of del:
if(isset($_POST['del_link'])) {
$Link = $_POST['del_link'];
guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead
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?