I'm trying to store form data in database but my code is reflecting anything.
Here is my code
add.php
<form name='reg' >
<fieldset>
<legend>Student information:-</legend>
<ul>
<li>
<label> FirstName: </label><input type="text" id="name" name="name" required>
<span id='error' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label> LastName: </label><input type="text" id="lname" name="lname" required>
<span id='error1' style="display:none;color:red;"> Only alphabets </span>
</li>
<li>
<label>Username:</label>
<input type="text" id="username" name="username"/>
</li>
<li>
<label>Password:</label>
<input type="password" id="password" name="password"/>
</li>
<label>
Gender: </label>
<input type="radio" id='gender' name="gender" value="male" required> Male
<input type="radio" name="gender" id='gender' value="female" required> Female
<input type="radio" name="gender" id='gender' value="other" required> Other
<li>
<label>
Email: </label>
<input id="email" type="text" name="email" required>
<span id='error2' style="display:none;color:red;"> Invalid email </span>
</li>
<li>
<label> Mobile:</label>
<input id="mobile" type="text" maxlength="10" name="mobile" required >
<span id='error3' style="display:none;color:red;"> only digits </span>
</li>
<li>
address: <textarea name="address" id="address" type="text" rows="3" cols="40"></textarea></textarea>
</li>
</ul>
<p>Register</p>
</fieldset>
</form>
and javascript file is as
serve.js
$(document).ready(function () {
$("#btnBooking").on("click", function (e) {
// as you have used hyperlink(a tag), this prevent to redirect to another/same page
e.preventDefault();
// get values from textboxs
var name = $('#name').val();
// alert('name');
var lname = $('#lname').val();
var username = $('#username').val();
var password = $('#password').val();
var gender = $('#gender').val();
var mail = $('#email').val();
var mobNum = $('#mobile').val();
var address = $('#address').val();
$.ajax({
url: "http://localhost/project_cloud/fun.php",
type: "post",
dataType: "json",
data: {type: "add", Name: name, Lname: lname, User: username, Pass: password, Gen: gender, Email: mail, Mob_Num: mobNum, Addr: address},
//type: should be same in server code, otherwise code will not run
ContentType: "application/json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (err) {
alert(JSON.stringify(err));
}
})
});
});
and another php file which stores the result in database
fun.php
<?php
header('Access-Control-Allow-Origin: *');
mysql_connect("localhost", "root", "");
mysql_select_db("ocean");
if (isset($_GET['type'])) {
$res = [];
if ($_GET['type'] == "add") {
$name = $_GET ['Name'];
$lname = $_GET['Lname'];
$userN = $_GET['User'];
$passW = $_GET['Pass'];
$gen = $_GET['Gen'];
$mail = $_GET ['Email'];
$mobile = $_GET ['Mob_Num'];
$address = $_GET['Addr'];
$query1 = "insert into oops(username, password, firstname, lastname, gender, email, mobile, address) values('$userN','$passW','$name','$lname','$gen','$mail','$mobile','$address')";
$result1 = mysql_query($query1);
if ($result1) {
$res["flag"] = true;
$res["message"] = "Data Inserted Successfully";
} else {
$res["flag"] = false;
$res["message"] = "Oppes Errors";
}
}
} else {
$res["flag"] = false;
$res["message"] = "Invalid format";
}
echo json_encode($res, $result1);
?>
When I write my serve.js file code in add.php file it gives me result as stored in database .But when I tried to separate it js file it shows nothing. What wrong in it or I missing something.
You have
type:"post",
in your AJAX request, but server side handle $_GET parameters:
$lname = $_GET['Lname'];
Change $_GET to $_POST and you'll see your values.
But all your code is terrible. You can't publish this in Internet. You have bad JavaScript and many issues serverside, include MySQL Injection. Need to rewrite all of this with prepared statements and JS to:
$(function() {
$("#btnBooking").on("click", function(e){
e.preventDefault();
var data = $(this).parents('form').serializeArray();
data.type = 'add'
$.post('/project_cloud/fun.php',data)
.done(function(response){
alert(JSON.stringify(response));
})
.fail(function(err){
alert(JSON.stringify(err));
})
});
})
Related
I created a registration form following an online tutorial.
The current code doesn't insert anything into a database yet. I am just trying to get the basic error messages working.
When the form is submitted the error message "There was an error" is shown. This comes from my action page where the register button has been pressed.
I am not sure what has caused this.
I know there is a lot of code.
Any help is appreciated.
Main Page(With my form):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var forename = $("#txtfirstname").val();
var surname = $("#txtsurname").val();
var username = $("#txtusername").val();
var password = $("#txtpassword").val();
$(".form-message").load("aregisteraction.php", {
forename : forename,
surname : surname,
username : username,
password : password
});
});
});
</script>
</head>
<body>
<?php
require 'leftnav.php';
?>
<div class="two-thirds column">
<h1> Not Registered?</h1>
<h3>Register</h3>
<form method="post" action="aregisteraction.php">
<p>
<label for="txtfirstname" >Firstname: </label> </br>
<input type="text" name="firstname" id="txtfirstname" />
</p>
<p>
<label for="txtsurname" >Surname: </label> </br>
<input type="text" name="surname" id="txtsurname" />
</p>
<p>
<label for="ddage" >Age: </label> </br>
<select name="ddage">
<option value="0">Select a value</option>
<option value="1">0-10</option>
<option value="2">11-30</option>
<option value="3">31-50</option>
<option value="4">51-70</option>
<option value="4">71+</option>
</select>
</p>
<p>
<label >Gender: </label> </br>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
</p>
<p>
<label for="txtusername" >Email: </label> </br>
<input type="text" name="username" id="txtusername" />
</p>
<p>
<label for="txtpassword" >Password: </label> </br>
<input type="password" name="password" id="txtpassword" />
</p>
<p>
<label for="txtpassword1" >Re-enter Password: </label> </br>
<input type="password" name="password1" id="txtpassword1" />
</p>
<input type="submit" name="register" value="Register" />
<p class="form-message"></p>
</form>
Action Page:
<?php
if(isset($_POST['register'])){
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$username = $_POST['username'];
$password = $_POST['password'];
$errorEmpty = false;
$errorEmail = false;
if(empty($forename)||empty($surname)||empty($username)||empty($password)){
echo "<span> Fill in all fields </span>";
$errorEmpty = true;
}
elseif (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'> Fill in a valid email </span>";
$errorEmail = true;
}
else{
echo "<span class='form-success'> Success </span>";
}
}
else{
echo "There was an error!";
}
?>
<script>
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").removeClass("input-error");
var errorEmpty ="<?php echo $errorEmpty; ?>";
var errorEmail ="<?php echo $errorEmail; ?>";
if(errorEmpty == true){
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").addClass("input-error");
}
if(errorEmail == true){
$("#txtusername").addClass("input-error");
}
if(errorEmail == false && errorEmpty == false){
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").val("");
}
</script>
In your JavaScript you doesn't send any value for register.
Two options: add a value to register:
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var forename = $("#txtfirstname").val();
var surname = $("#txtsurname").val();
var username = $("#txtusername").val();
var password = $("#txtpassword").val();
$(".form-message").load("aregisteraction.php", {
forename : forename,
surname : surname,
username : username,
password : password,
register: "ok",
});
});
});
Or simply test $_POST on another field (as register is a button and will always contains a value in the form).
Also, to test values of your form in PHP you can user print_r():
print_r($_POST);
I have a form and I want when someone click submit, run upis.js write thank you message and run php script for inserting into database. For now it takes values I can see them in my url but it doesnt run upis.php. Can you tell me why?
Here is the code for form:
<form>
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>
and upis.js
<script>
function upis(){
var ime = document.getElementById("ime").value;
var prezime = document.getElementById("prezime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var prezime_slavljenik = document.getElementById("prezime_slavljenik").value;
var email = document.getElementById("email").value;
var dataString = "ime="+encodeURIComponent(ime)+"&prezime="+encodeURIComponent(prezime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik)+"&prezime_slavljenik="+encodeURIComponent(prezime_slavljenik)+"&email="+encodeURIComponent(email);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
data: dataString,
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
and upis.php
<?php
require_once 'include/db.php';
require_once 'include/functions.php';
$allowed_params = allowed_post_params(['ime', 'prezime', 'ime_slavljenik', 'prezime_slavljenik', 'email','submit']);
// niz sadrzi dozvoljene maksimalne duzine za sva polja
$fields_lengths = ['ime' => 64, 'prezime' => 64, 'ime_slavljenik'=>64, 'prezime_slavljenik'=>64, 'email' => 64];
// provera da li su polja odgovoarajuce duzine
foreach ($fields_lengths as $field => $length) {
if (!has_length($_POST[$field], ['min' => 0, 'max' => $length])) {
header('Location: greska.html');
die();
}
}
try {
// Priprema upita za unos podataka u bazu
$prep = $db->prepare("INSERT INTO prijavljeni (ime, prezime, ime_slavljenik, prezime_slavljenik, email) VALUES(:ime, :prezime, :ime_slavljenik, :prezime_slavljenik, :email)");
$prep->bindParam(':ime', $ime);
$prep->bindParam(':prezime', $prezime);
$prep->bindParam(':ime_slavljenik', $ime_slavljenik);
$prep->bindParam(':prezime_slavljenik', $prezime_slavljenik);
$prep->bindParam(':email', $email);
$ime = isset($allowed_params['ime']) ? $allowed_params['ime'] : "";
$prezime = isset($allowed_params['prezime']) ? $allowed_params['prezime'] : "";
$ime_slavljenik = isset($allowed_params['ime_slavljenik']) ? $allowed_params['ime_slavljenik'] : "";
$prezime_slavljenik = isset($allowed_params['prezime_slavljenik']) ? $allowed_params['prezime_slavljenik'] : "";
$email = isset($allowed_params['email']) ? $allowed_params['email'] : "";
// izvrsavanja upita
$rez = $prep->execute();
$htmltable = "Hvala na poslatoj prijavi.";
echo $htmltable;
} catch (PDOException $e) {
echo 'greska kod upita';
}
?>
I cant see what can be problem here because js takes values from form but doesnt actually run upis.php(it doesnt take url upis.php) I dont understand why..
If you're developing your application using Firefox or Chrome look in the network tab of web inspector to ensure the JavaScript resource successfully sends an XHR request. Check the URL that the POST XHR request is sent to.
Is the URL set correctly in the url property of the AJAX settings?
You may need to prepend "upis.php" with a forward slash e.g. "/upis.php"
You should call script from index.php, you missed action and method in form
<form action="upis.php" method="post">
<label>Ime</label>
<input type="text" name="ime" id="ime" required><br>
<label>Prezime</label>
<input type="text" name="prezime" id="prezime" required><br>
<label>Ime slavljenika</label>
<input type="text" name="ime_slavljenik" id="ime_slavljenik" required><br>
<label>Prezime slavljenika</label>
<input type="text" name="prezime_slavljenik" id="prezime_slavljenik" required><br>
<label>Kontakt email</label>
<input type="email" name="email" id="email" required>
<button onclick="return upis()">Posalji</button>
<div id="placefortableanketa">
</div><br><br>
</form>
I am not sure where the steps go wrong in here since everything goes as it should with the exception of the serialized data not being submitted into the database.
I know the connection to the DB works. I use it in other pages that are pulling data from the DB. I just can't seem to be able to INSERT.
Step 1: Fill out form
Step 2: Data from form is validated. Disclaimer: I fully intend to put in full security checks and trim to avoid SQL injections. Simply working on function first.
Step 3: Serialized data passed to usersubmit.php for DB insertion.
Any help is very appreciated.
register.php
<script src="js/click.js"></script>
<form action="js/click.js" method="post">
<label for="first_name">First Name:</label>
<input type="text"id="first_name" name="first_name" /><br>
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" /><br>
<label for="username" >Username:</label>
<input type="text" id="username" name="username" /><br>
<label for="password">Password:</label>
<input type="text" id="password" name="password" /><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br><br><br>
<button type="submit" id="reg-submit" name="submit">Submit</button>
</form>
click.js
$(document).ready(function(){
$('#reg-submit').click(function() {
var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var userName = $('#username').val();
var userPass = $('#password').val();
var userEmail = $('#email').val();
if (firstName =='' || lastName =='' || userName =='' || userPass =='' || userEmail =='') {
alert ('Nope');
}
else
{
var formData = $("form").serialize();
$.ajax({
type: "POST",
url: "usersubmit.php",
data: formData,
cache: false,
success: function(){
$('#main-content').load('next-page.php').hide().fadeIn('slow');
}
});
};
return false;
});
});
usersubmit.php
<?php include 'users_db.php'; ?>
<?php
$first1=$_POST['first_name'];
$last1=$_POST['last_name'];
$username1=$_POST['username'];
$pass1=$_POST['password'];
$email01=$_POST['email'];
$userinfo = $conn->prepare("INSERT INTO registered_users (FirstName, LastName, Username, Password, Email) VALUES (:first, :last, :user, :pass, :email)");
$userinfo->bindParam(':first', $first1);
$userinfo->bindParam(':last', $last1);
$userinfo->bindParam(':user', $username1);
$userinfo->bindParam(':pass', $pass1);
$userinfo->bindParam(':email', $email01);
$userinfo->execute();
$userinfo->close();
$conn->close();
?>
I am trying to create a email form that does not redirect to another other page. I am a newbie at PHP and Javascript .. so basically i have coded like this -
I have included the following code in the mail.php file
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent=" From: $name \n Phone: $phone \n Message: $message";
$recipient = "devtest#xxx.org";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='test.html' style='text-decoration:none;color:#ff0099;'> Return Home</a>";
?>
I have uploaded all the files to web server but the problem is that when I am sending test emails, I am not getting blank emails.
The email only contains name of the sender and the email id.
Please let me know where I am messing things up.
<div class="contact">
<div class="contact-wrap">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if (document.getElementById("name").value == "" || document.getElementById("email").value == "") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name = $('#name').val();
var email = $('#email').val();
var formData = "name=" + name + "&email=" + email;
$.ajax({
url: "mail.php",
type: "POST",
data: formData,
success: function (data, textStatus, jqXHR) {
//data - response from server
alert(data);
},
});
}
}
</script>
<div class="quick-contact">
<form action="#" id="ContactForm" method="post" action="mail.php">
<p>Your Name (required) <br>
<input type="text" class="form-bt" value="" size="40" name="name" id="name" required>
</p>
<p>Your Email (required) <br>
<input type="email" class="form-bt" value="" size="40" name="email" id="email" required>
</p>
<p>Subject <br>
<input type="text" class="form-bt" value="" name="phone" size="40">
</p>
<p>Your Message<br>
<textarea cols="40" rows="10" class="text-area" name="message" required></textarea>
</p>
<p>
<input type="submit" id="send" onClick="verify()" value="Send" class="btton" onmouseover="this.style.backgroundColor = 'black'" ; onmouseout="this.style.backgroundColor = '#74b9e4'" ;>
</p>
</form>
</div>
</div>
</div>
kind regards
deb
You have just sent email and name. Replace
var formData = "name="+name+"&email="+email;
to
var formData = "name="+name+"&email="+email+"&message="+message;
Also get message variable as :
var message=$('#message').val();
And change the textarea to :
<textarea cols="40" rows="10" class="text-area" name="message" id="message" required></textarea>
You are posting form data with name and email only.
var formData = "name="+name+"&email="+email;
Add fields as necessary.
Also a good way to do this is:
var formData = {
name : $('#name').val(),
email : $('#email').val(),
message : $('#message').val() //Say ID for your message is "message"
}
rather than:
var formData = "name="+name+"&email="+email+"&message="+message;
HELP!
Undefined values for all fields
function UpdateData(){
var id = $('#id').attr('value');
var name = $('#name').attr('value');
var department = $('#departament').attr('value');
var phone = $('#phone').attr('value');
var mail = $('#mail').attr('value');
$.ajax({
url: 'updatePersonal.php',
type: "POST",
data: "submit=&name="+name+"&department="+department+"&phone="+phone+"&mail="+mail+"&id="+id,
success: function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
}
});
return false;}
When I call the function it doesn't work, the value stored in the db is undefined for all fields and I tried to solve it by adding {} to the string on data: -->
data: {"submit=&name="+name+"&department="+department+"&phone="+phone+"&mail="+mail+"&id="+id},
but if I do that, the next part is not executed
success: function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
}
updatePersonal.php -->
<?php
require('functions.php');
if(isset($_POST['submit'])){
require('clases/personal.class.php');
$objPersonal = new Personal;
$id = htmlspecialchars(trim($_POST['id']));
$name = htmlspecialchars(trim($_POST['name']));
$department = htmlspecialchars(trim($_POST['department']));
$phone = htmlspecialchars(trim($_POST['phone']));
$mail = htmlspecialchars(trim($_POST['mail']));
if ($objPersonal->actualizar(array($name,$department,$phone,$mail),$id) == true){
echo 'Saved';
}else{
echo 'There was an error...';
}
}else{
if(isset($_GET['id'])){
require('clases/personal.class.php');
$objPersonal = new Personal;
$consult = $objPersonal->show_person($_GET['id']);
$personal = mysql_fetch_array($consult);
?>
<form method="post" action="updatePersonal.php" onsubmit="UpdateData(); return false">
<input type="hidden" name="id" id="id" value="<?php echo $personal['id']?>" />
<p>
<label>Name<br />
<input class="text" type="text" name="name" id="name" value="<?php echo $personal['name']?>" />
</label>
</p>
<p>
<label>Department<br />
<input class="text" type="text" name="department" id="department" value="<?php echo $personal['department']?>" />
</label>
</p>
<p>
<label>Phone<br />
<input class="text" type="text" name="phone" id="phone" value="<?php echo $personal['phone']?>" />
</label>
</p>
<p>
<label>Mail<br />
<input class="text" type="text" name="mail" id="mail" value="<?php echo $personal['mail']?>" />
</label>
</p>
<p>
<input type="submit" name="submit" id="button" value="Send" />
<label></label>
<input type="button" name="cancel" id="cancel" value="Cancel" onclick="Cancel()" />
</p>
</form>
<?php
}
}
?>
Your data should be in JSON format:
{"submit": "", "name": name, "department": department}
and so on..
First, make sure your variables are being properly populated, maybe using a simple alert(varname) after the initialization... I suspect they are not being set.
Then I would suggest to try assigning the values like this:
var id = $('#id').val();
var name = $('#name').val();
var department = $('#departament').val();
var phone = $('#phone').val();
var mail = $('#mail').val();
Use val() function instead of attr() and write param in JSON format like so:
function UpdateData(){
var id = $('#id').val();
var name = $('#name').val();
var department = $('#departament').val();
var phone = $('#phone').val();
var mail = $('#mail').val();
$.ajax({
url: 'updatePersonal.php',
type: "POST",
data: {
id: id,
name: name,
department: department,
phone: phone,
mail: mail
}
}).done(function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
});
return false;
}
Instead of fetching value for each input field and using JSON format inside data object, use $('form').serialize() like so
function UpdateData(){
$.ajax({
url: 'updatePersonal.php',
type: "POST",
data: $('#form').serialize()
}).done(function(datos){
alert(datos);
consultingData();
$("#form").hide();
$("#table").show();
});
return false;
}
On updatePersonal.php page the $_POST['param'] will be according to name attribute of input field. For eg. for phone input field it may be $_POST['phone'] if the name attribute value will be equal to phone.
Search for relevant questions here, before asking any question.