What I am trying to achieve is have the form appear if there was nothing submitted. So I add the form html to a variable and then echo the variable inside the html.
However ever since I implemented AJAX, inside the #results div. It also exports the jquery.js and my ajax script.
If I remove the PHP else code that displays the form, I won't see the form at all.
So how would someone make sure the js scripts aren't being inserted where they shouldn't be?
PHP:
if( isset($_POST["u_name"]) && isset($_POST["u_lastname"]) && isset($_POST["u_email"]) ){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testTable (Name, Lastname, Email)
VALUES ('".$_POST["u_name"]."','".$_POST["u_lastname"]."','".$_POST["u_email"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."";
}
$conn->close();
}else {
$final_content = '<form action="script.php" method="post" id="user_form">
<input type="text" name="u_name" placeholder="Name" id="user_name"> <br>
<input type="text" name="u_lastname" placeholder="Lastname" id="user_lastname"> <br>
<input type="email" name="u_email" placeholder="Email" id="user_email"> <br>
<input type="submit" value="Submit" name="submit">
</form>';
}
?>
HTML
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
//Set form variable
var form = $("#user_form");
form.submit(function(event){
//Set data variables
var user_name = $("#user_name").val();
var user_lastname = $("#user_lastname").val();
var user_email = $("#user_email").val();
//Check if values are set
if( ($.trim(user_name) != "") && ($.trim(user_lastname) != "") && ($.trim(user_email) != "") ){
$.post("script.php", {u_name: user_name, u_lastname: user_lastname, u_email: user_email}, function(data){
$("#results").html(data);
});
}
event.preventDefault();
});
});
</script>
</head>
<body>
<?php echo $final_content ?>
<div id="results"></div>
</body>
</html>
Add an exit(); right after $conn->close();, just above the else.
This will make sure that once you have output the results, you do not continue with the rest of the code (not included in your question) where you output the full HTML page with script tags and <div id="results"> ...etc.
Apparently that display code is not all inside the else block, but also further down, after the else block.
Related
I the following code, I have a form that consists of three fields and two buttons. In the Review button, I would like to show any word in Arabic randomly and let the user show its translation in English by ticking the Show translation button.
<html>
<body>
<script>
function myFun1(var) {
document.getElementById("demo").innerHTML = "The translation in English is " + var;
}
</script>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="english" rows="4" cols="70" placeholder="English">English</textarea>
<br>
<textarea name="arabic" rows="4" cols="70" placeholder="Arabic">Arabic</textarea>
<br>
<textarea name="example" rows="4" cols="70" placeholder="Example">Example</textarea>
<br><br>
<input type="submit" name="add" value="Add new">
<input type="submit" name="review" value="Review">
<br>
<p id="demo"></p>
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "vdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['add'])) {
$sql = "INSERT INTO Vocabulary (English, Arabic, Example)
VALUES ('$english', '$arabic', '$example')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['review'])) {
$sql = "SELECT COUNT(ID) as total FROM Vocabulary";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
#echo $row['total'];
$generated = rand(1,$row['total']);
$sql1 = "SELECT * FROM Vocabulary where ID = $generated";
$result1 = $conn->query($sql1);
$row1 = $result1->fetch_assoc();
echo "<br>";
echo $row1['Arabic'];
echo "<br><br>";
$eng = $row1['English'];
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
}
$conn->close();
?>
</body>
</html>
In the code, the following line creates the button and trigger the myFun1() function:
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
The problem is when the button is clicked, nothing happens (the message is not shown at all). Any ideas how to fix it?
Firstly change the argument var to some another argument name as var is a keyword in javascript
<script type="text/javascript">
function myFun(as) {
document.getElementById("demo").innerHTML = "The translation in English is " + as;
}
</script>
Secondly, you have to pass the string value in single or double quotes for that use inverted slash \ and rectify the function name from myFun() to myFun1()
echo '<button onClick = "myFun1(\''.$eng.'\')">Show translation</button>';
Rest your code is perfect.
You have definition of function myFun1(var), but you are calling myFun(). I guess this is the problem why there is nothing after clicking on button.
Add this to the top before
< html > tag
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
So I'm working on an assignment for my class in which I am supposed to take a username and password and check it against a list contained in a table on a database I am connecting too.
Problem is when I am clicking the submit button nothing is happening I think this is likely to be some sort of error in syntax. Since I am new to PHP there is a good possibility it is something obvious, but not so much to me.
I have my database data stored in two PHP arrays (one for each field). I then converted the arrays to json which I will use in my JavaScript function that will be checked against the user inputted data.
I am including a form, a PHP script, and a JavaScript script in one document could this cause the issue?
Here is my code and thank you for any help!
<html>
<body>
<?php
/*config is included in order to protect my login info*/
require('config.php');
Echo "Project 4";
/*SQL connection*/
$conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
/*Checking Connection*/
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM p4Data";
$data2 = mysqli_query($conn, $sql);
/*Display Data*/
echo "<table border = 1 style='float:left'>
<tr>
<th>Username</th>
<th>Password</th>
</tr>";
//Array Declarations
$usernameArr = [];
$passwordArr = [];
while($records = mysqli_fetch_array($data2)){
array_push($usernameArr,$records["username"]);
array_push($passwordArr,$records["password"]);
}
echo "</table>";
//JSON Conversion
$usernameJson = json_encode($usernameArr);
$passwordJson = json_encode($passwordArr);
mysqli_close($conn);
?>
<!-- JAVA SECTION -->
<script type="text/javascript">
var obj = JSON.parse('<?= $usernameJson; ?>');
var obj2 = JSON.parse('<?= $passwordJson; ?>');
function verifUser(){
var usernameData = document.getElementById("username").value;
var passwordData = document.getElementById("password").value;
for (i = 0; i < 30; i++){
if(usernameData == obj[i]){
alert("Username verfied at " + i);
indexLocated = i;
break;
}
}
}
</script>
<form name='form-main'>
Username: <input type="text" id="username"><br>
Password: <input type="password" id="password"><br>
<input type="button" value="Login >>" id="submitButton"
onclick="verifUser()">
</form>
</body>
</html>
You can use post method to get the value of user input like this
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="submit" value="login">
</form>
and use this php code to get value when form is submitted
if(isset($_POST['submit'])){
$username_input = $_POST['username'];
$password_input = $_POST['password'];
}
Then make a query to sql where username = $username and password = $password. Like below
$sql query = " SELECT * FROM TABLE WHERE username = $username and password = $password";
And use
$num_rows = mysqli_num_rows($sql_query);
Now do a check of $num_rows = 1 that means input username and password is valid else echo Not valid
if($num_rows = 1){
**some code **
}else{
echo "Invalid information provided";
};
I was looking for a way to submit data through a button so that the data will be saved or updated in database, without reloading. Now updating and inserting of data works. But I have used dataString a javaScript variable. I thought through this dataString variable post data are passed. But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
How post method gets the data from my ajax call here.
<html>
<title>Registration</title>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
$dbname = "registration_project";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<div style="width:350px">
<div style="float:left;width:40%">
Id:<br/><br/>
First Name:<br/><br/>
Last Name:<br/><br/>
Age:<br/><br/>
</div>
<div style="float:left;width:60%">
<form action="" method="post">
<input type="number" id="id_id" name="id" value=<?php
if (isset($_POST['id']))
echo $_POST['id'];
?>><br /><br />
<input type="text" id="id_fname" name="fname" value=<?php
if (isset($_POST['fname']))
echo $_POST['fname'];
?>><br /><br />
<input type="text" id="id_lname" name="lname" value=<?php
if (isset($_POST['lname']))
echo $_POST['lname'];
?>><br /><br />
<input type="number" id="id_age" name="age" value=<?php
if (isset($_POST['age']))
echo $_POST['age'];
?>><br /><br />
<input type="submit" id="id_submit" name="submit">
</form>
</div>
</div>
<script src="js/jquery-1.11.3.js"></script>
</body>
</html>
<?php
if (isset($_POST['id']))
echo $_POST['id'] . "<br/><br/>";
if (isset($_POST['fname']))
echo $_POST['fname'] . "<br/><br/>";
if (isset($_POST['lname']))
echo $_POST['lname'] . "<br/><br/>";
if (isset($_POST['age']))
echo $_POST['age'] . "<br/><br/>";
?>
<?php
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "select max(id) from registration";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row["max(id)"];
}
} else {
echo "0 results";
}
if ($id==$_POST['id']) {
$id = $_POST['id'];
$sql = "update registration set firstName='$fname', lastName='$lname', age=$age where id=$id";
mysqli_query($conn, $sql);
} else {
$id=$_POST['id'];
$sql = "Insert into registration(id,firstName,lastName,age) values($id,'$fname','$lname',$age)";
mysqli_query($conn, $sql);
}
}
mysqli_close($conn);
?>
<script>
$("#id_submit").click(function(e) {
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
</script>
Your click handler doesn't have e.preventDefault() in it. So after the AJAX call is sent, the form is also submitted normally. So even if you don't fill in dataString, the database will be updated from the form.
To make it only use AJAX, you should call e.preventDefault(). You also need to submit a value for the submit parameter, because the PHP code uses if(isset($_POST['submit'])) to know if it should process the form parameters.
$("#id_submit").click(function(e) {
e.preventDefault();
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "submit=submit&id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
In your case, values aren't getting passed. More over, the way you're trying to do ( ?id=...&fname=... etc) would be for passing it with $_GET.
You have to make something similar to :
$.ajax({
type:'POST',
data: { id : $("#id_id").val(),
fname : $("#id_fname").val(),
lname : $("#id_lname").val(),
age : $("#id_age").val()
},
url:'Registration.php',
success:function(data) {
// code
}
});
But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
Answer
When you remove var dataString all the fields having name attribute are automatically submitted along with form
I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});
First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;
The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)
Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.
I'm working on a program but I'm new to js/jQuery/Ajax. I am trying to get user input from a form (html) and send it over to a php file that will insert the data into a MySQL database and then ultimately spit out the information into a div. I press submit but my user submitted data does not get inserted into the database. I initially had the submission redirect to my php file through the tag (action="post.php") which had worked in terms of inserting the data into the mysql database but had also redirected it to that post.php file upon submission.
my js file datawire.js:
$( 'button#submit').on('click', function() {
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
My php file post.php
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
}
?>
and my HTML file:
<html>
<head>
<!-- latest jQuery direct from google -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- for getting data -->
<script src="datawire.js"></script>
<!-- for posting data -->
<script type="text/javascript">
$(document).ready(function() {
$('#viewer').load("getdata.php");
});
</script>
</head>
<body>
<div id="viewer"> </div>
<br>
<!-- User form -->
<form method='post'>
<input type="text" id="uName" name="username" placeholder="Name" value="" maxlength="15" />
<br />
<input type="text" id="uMessage" name="message" placeholder="Message" value="" maxlength="100" />
<br />
<button id="submit" type="submit">Submit!</button> <button type="reset">Clear!</button>
</form>
</body>
</html>
Try wrapping the contents of datawire.js with $(document).ready like you did in html file. This insures $ is actually defined before it's used.
Prevent your form submit with preventDefault() function
$( 'button#submit').click(function(e) {
e.preventDefault();
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
Return the text message from the server like this
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
if($result)
{
echo " Data Inserted Successfully";
}else{
echo " Data insert failed - ".mysql_error();
}
}else{
echo " Required fields are missing";
}
?>