I'm have trouble resetting a from after submission. Currently I'm relying on auto refreshing the page to. I've never used php but I managed to hack something a php form set up with a MySQL database.
This form is hidden in a div which toggles in and out in visibility. So the webpage acts like a noticeboard the form is on the same page.
I have used a JQuery function to reset the form. But currently the div still displays the echo.
$(document).ready(function() {
$('submit').click(function() {
$('submission')[0].reset();
});
});
My current set up is this:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO mvmv3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('mvmv_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}else {
?>
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" required autocomplete="off">
<input name = "email" type = "text"
id = "email" autocomplete="off">
<textarea name = "proposal" type = "textarea" size="100"cols="40" rows="20"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
<?php
}
?>
What is the best way to go about this? Could I perhaps make the echo disappear after 4 seconds?
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO mvmv3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('mvmv_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
// WRAP THE "ECHOED" OUTPUT IN A DIV ELEMENT (WITH CLASS &/OR ID)
// SO YOU CAN EASILY REFERENCE IT IN JS
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
}else {
}
JAVASCRIPT
$(document).ready(function() {
$('submit').click(function() {
$('submission')[0].reset();
// FADE-OUT THE DIV 3 SECONDS AFTER CLICKING THE BUTTON USING window.setTimeout...
// THIS ASSUMES THAT YOUR FORM IS NOT SUBMITTING NORMALLY (AJAX OR SO)
/*
setTimeout(
function(){
$("#msg-box").fadeOut(500);
},
3000);
*/
});
// FADE-OUT THE DIV 3 SECONDS AFTER PROCESSING THE FORM-DATA USING window.setTimeout...
// THIS ASSUMES THAT YOUR FORM HAS SUBMITTED NORMALLY (VIA POST OR GET)
// AND THE MESSAGE IS DISPLAYED BY PHP AFTER PROCESSING...
setTimeout(
function(){
$("#msg-box").fadeOut(500);
},
3000);
});
Use something like
$('input').val('');
to clear all you input fields
Related
I'm trying to get 3 values to insert from the table, 'parents' to the table, 'children' in MySql. One of the values, entitled "code" inserts perfectly. However, I can't get the other two, "email" and "website" to insert. When I add them to the javascript code, it just inserts "code" 3 times. Can someone help me please? Here's the code that inserts just the 'code' field from parents to children:
$("a#reply").one("click", function() {
var comCode = $(this).attr("name");
var parent = $(this).parent();
parent.append("<br /><form id='reply-form-toggle' action='' method='post'><input type='text' name='user' placeholder='Your Name *' required='required' required><br><textarea class='form-text' name='new-reply' id='new-reply' placeholder='Your Reply' required='required'></textarea><input type='hidden' name='code' value='"+comCode+"' /><span style='float: right;'><a onclick='hideReplyForm();'>Cancel</a> <input type='submit' class='form-submit' id='form-reply' name='new_reply' value='Reply' /></span></form>");
});
Here is the insertion code:
<?php
// new comment
if(isset($_POST['new_comment'])) {
$new_com_name = $_SESSION['user'];
$new_com_email = $_POST['email'];
$new_com_website = $_POST['website'];
$new_com_text = $_POST['comment'];
$new_com_date = date('Y-m-d H:i:s');
$new_com_code = generateRandomString();
// automatically inserts the ESCAPE CHARACTER - Now content will insert into database with single quote character
$new_com_name = addslashes($new_com_name);
$new_com_email = addslashes($new_com_email);
$new_com_website = addslashes($new_com_website);
$new_com_text = addslashes($new_com_text);
if(isset($new_com_text)) {
$sql = "INSERT INTO `parents` (`user`, `email`, `website`, `text`, `date`, `code`) VALUES ('$new_com_name', '$new_com_email', '$new_com_website', '$new_com_text', '$new_com_date', '$new_com_code')";
$result=$dbCon->query($sql);
if ($result === TRUE) {
echo "<script type='text/javascript'>alert('Thank you for your comment! We will review it and hopefully approve it within 24 hours.');</script>";
}else{
echo "<script type='text/javascript'>alert('Your comment has not been submitted.');</script>";
}
}
header("Location: ");
}
// new reply
if(isset($_POST['new_reply'])) {
$new_reply_name = $_SESSION['user'];
$new_reply_email = $_POST['email'];
$new_reply_website = $_POST['website'];
$new_reply_text = $_POST['new-reply'];
$new_reply_date = date('Y-m-d H:i:s');
$new_reply_code = $_POST['code'];
// automatically inserts the ESCAPE CHARACTER - Now content will insert into database with single quote character
$new_reply_name = addslashes($new_reply_name);
$new_reply_email = addslashes($new_reply_email);
$new_reply_website = addslashes($new_reply_website);
$new_reply_text = addslashes($new_reply_text);
if(isset($new_reply_text)) {
$sql = "INSERT INTO `children` (`user`, `par_email`, `par_website`, `text`, `date`, `par_code`) VALUES ('$new_reply_name', '$new_reply_email', '$new_reply_website', '$new_reply_text', '$new_reply_date', '$new_reply_code')" or die(mysqli_error());
$resultReply=$dbCon->query($sql);
if ($resultReply === TRUE) {
echo "<script type='text/javascript'>alert('Thank you for your reply! We will review it and hopefully approve it within 24 hours.');</script>";
}else{
echo "<script type='text/javascript'>alert('Your reply has not been submitted.');</script>";
}
}
header("Location: ");
}
?>
I have a search bar which uses Ajax implementation to search my database and query the input data.view of results generated My question is how do I make the results show up as clickable link so that when clicked they go straight to the view which holds more information about them? I have added the code for database query and the script used for accessing the database based on what was entered by the user in the search box.
<script>
$(document).ready(function() {
$('#search-data').unbind().keyup(function(e) {
var value = $(this).val();
if (value.length>3) {
//alert(99933);
searchData(value);
}
else {
$('#search-result-container').hide();
}
}
);
}
);
function searchData(val){
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Searching...</span></div>');
$.post('controller.php',{
'search-data': val}
, function(data){
if(data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'>No Result Found...</div>");
}
).fail(function(xhr, ajaxOptions, thrownError) {
//any errors?
alert("There was an error here!");
//alert with HTTP error
}
);
}
</script>
<form>
<div class="manage-accounts" id="users">
<div id="search-box-container" >
<label > Search For Any Event:
</label>
<br>
<br>
<input type="text" id="search-data" name="searchData" placeholder="Search By Event Title (word length should be greater than 3) ..." autocomplete="off" />
</div>
<div id="search-result-container" style="border:solid 1px #BDC7D8;display:none; ">
</div>
</div>
</form>
database query:
<?php
include("fetch.php");
class DOA{
public function dbConnect(){
$dbhost = DB_SERVER; // set the hostname
$dbname = DB_DATABASE ; // set the database name
$dbuser = DB_USERNAME ; // set the mysql username
$dbpass = DB_PASSWORD; // set the mysql password
try {
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbConnection->exec("set names utf8");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function searchData($searchVal){
try {
$dbConnection = $this->dbConnect();
$stmt = $dbConnection->prepare("SELECT * FROM events WHERE title like :searchVal");
$val = "%$searchVal%";
$stmt->bindParam(':searchVal', $val , PDO::PARAM_STR);
$stmt->execute();
$Count = $stmt->rowCount();
//echo " Total Records Count : $Count .<br>" ;
$result ="" ;
if ($Count > 0){
while($data=$stmt->fetch(PDO::FETCH_ASSOC)) {
$result = $result .'<div class="search-result">'.$data['title'].'</div>';
}
return $result ;
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
?>
If all you want is making the search result clickable and browser loads the hyperlink clicked on, just echo the hyperlink from your database or JSON file depends on where they are into the html anchor element such as this:
<?php echo $row['page_title'] ?>
Note: I echoed the page link in the anchor href attribute, that should solve the problem.
You can simply add some code to make a hyperlink into the HTML your PHP is generating:
$result = $result .'<div class="search-result">'.$data['title'].'</div>';
I have made an assumption about the name of your ID field but you can see the pattern you need to use.
Yep, this old chesnut I'm afraid. I've read through a lot of the previous answers to this question but I cannot get into this if statement even though 'btn-save' is definitely set as the name attribute on my submit button.
I'm using the code from this tutorial to post form data to my database: http://www.phpzag.com/ajax-registration-script-with-php-mysql-and-jquery/
My site structure is like this:
- root
- public_html
- js
app.js
register.php
db_connect.php
form_page.php
My register.php file looks like this and I've added an echo inside the if statement:
<?php
include_once("db_connect.php");
if(isset($_POST['btn-save'])) {
echo "in if";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_id = $_POST['email_id'];
$address_1 = $_POST['address_1'];
$address_2 = $_POST['address_2'];
$address_3 = $_POST['address_3'];
$city_town = $_POST['city_town'];
$county = $_POST['county'];
$post_code = $_POST['post_code'];
$entrant_type = $_POST['entrant_type'];
$chosen_store = $_POST['chosen_store'];
$chosen_charity = $_POST['chosen_charity'];
$agree_terms = $_POST['agree_terms'];
$sql = "SELECT user_email FROM tbl_big_challenge_registrations WHERE user_email='$email_id'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!$row['user_email']){
$sql = "INSERT INTO tbl_big_challenge_registrations('uid', 'first_name', 'last_name', 'user_email', 'address_1', 'address_2', 'address_3', 'town_city', 'county', 'postcode', 'entrant_type', 'crew_store', 'charity', 'agree_terms') VALUES (NULL, '$first_name', '$last_name', '$email_id', '$address_1', '$address_2', '$address_3', '$city_town', '$county', '$post_code', '$entrant_type', '$chosen_store', '$chosen_charity', 'agree_terms', NULL)";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);
echo "registered";
} else {
echo "1";
}
}
?>
My db_connect.php file looks like this (with dummy values for purpose of this post):
<?php
/* Database connection start */
$servername = "servername.com";
$username = "username";
$password = "password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
My form_page.php form looks like this:
<form id="2017-challenge-form" method="post" data-abide>
<!-- form fields are here -->
<input id="btn-submit" type="submit" name="btn-save" value="submit">
</form>
And finally my app.js looks like this:
$('document').ready(function() {
/* handle form submit */
function submitForm() {
var data = $("#2017-challenge-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").val('Submitting...');
},
success : function(response) {
if(response==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").val('Submit');
});
} else if(response=="registered"){
$("#btn-submit").html('<img src="ajax-loader.gif" /> Signing Up ...');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".register_container").load("welcome.php"); }); ',3000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").val('Submit');
});
}
}
});
return false;
}
$("#2017-challenge-form").submit(function(event){
// cancels the form submission
event.preventDefault();
// jumps into ajax submit function
submitForm();
});
});
I have a breakpoint set just inside the ajax success and on submission of the form I would expect the response to have a value of 'registered' (just like the Demo from the PHPZag site: http://phpzag.com/demo/ajax-registration-script-with-php-mysql-and-jquery/
But I get an empty string:
Can anybody see what I'm doing wrong or am missing?
I changed the input to a button as per the demo site and this worked. As per the comment by #frz3993 the btn-save wasn't getting added to the data so the if(isset($_POST['btn-save'])) was never true as it wasn't finding it.
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
Hey guys i am very new to this so i am sorry if there is just something completely stupid i am missing here. I have the following Sign Up Form. And in the URL http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de i am trying to submit the value e. However, in all cases e is simply empty or undefined:
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$p = $_POST['p'];
$e = $_GET['e'];
echo "test";
echo "$e";
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM team WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$cryptpass = crypt($p);
include_once ("php_includes/randStrGen.php");
$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "UPDATE team
SET username='$u',password='$p_hash',ip='$ip',signup=now(),lastlogin=now(),notecheck=now()
WHERE email='$e'";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#yoursitename.com";
$subject = 'Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8">
<title>yoursitename Message</title></head>
<body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;">
<div style="padding:10px; background:#333; font-size:24px; color:#CCC;">
<img src="http://www.rockaholics-cologne.de/root/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">Account Activation</div>
<div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
I do get new entries into the database when i fill out the form. But it does neither send me an email or UPDATE the database at the specified email. It simply updates all the entries with a blank email. The echo "$e" within the script also return nothing.
I used this code to check:
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
$e = $_GET['e'];
echo "$e";
?>
And in this case it does return an array with [e]=cataras#gmx.de and it also prints out $e. But why doesnt it work in the other skript? I'm using the exact same methods to get e from the URL.
When i run my Javascript function:
function signup(){
var u = _("username").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, "") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&p="+p1);
}
}
I get Uncaught ReferenceError: e is not defined. And the site stops at "please wait...". I just took out the +e+ in the js to get to the php above. Sorry for the long post but i am really running out of ideas. THANKS in advance!!!
I think $_GET['e'] is not working in your original script because it's not getting passed to that processing script from your form page. I accessed the URL you provided (http://www.rockaholics-cologne.de/root/signup.php?e=cataras#gmx.de). Note that when you submit your form, the value of "e" in your URL is not being passed to whatever is processing your script. In your form, you need to either do this:
<form action="{yourscripturl}?e=<?php echo $_GET['e']?>" {rest of form tag}>
Or, add a hidden to hold the value of "e", and then use $_POST['e'] on your processing script instead of $_GET['e'].
<input type="hidden" name="e" value="<?php echo $_GET['e']?>" />