Showing "Thank you message" with AJAX and running php script - javascript

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>

Related

Access POST values sent by Ajax in PHP

I'm using Ajax to get POST values from a form. However, when I try to insert the form values in a database on submit, it doesn't get inserted. I still have no idea why it does not work.
Here is my HTML
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font><br>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
My JS (the first console.log does go through and work):
if (validForm)
{
console.log("valid form");
console.log(JSON.stringify($('#home-sign-up-form')[0].seriaize()));
$.ajax(
{
type:'POST',
url:'form-submit.php',
data:$('#home-sign-up-form')[0].serialize(),
success:function(response)
{
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
$emailSentTextEmail.text($suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
}
And my PHP/MySQL:
<?php require 'dbconnect.php'; ?>
if (isset($_POST['suEmail']))
{
echo "<script type='text/javascript'>alert('got');</script>";
$suFirstName = mysqli_real_escape_string($_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($_POST['suLastName']);
$suEmail = mysqli_real_escape_string($_POST['suEmail']);
$suPassword = mysqli_real_escape_string($_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
}
The alert in the PHP code so I would assume that it isn't getting the 'signUp' POST variable. Thanks so much! Any help is appreciated! :D
$("#home-sign-up-form").submit(function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
$.ajax({
type: 'POST',
url: 'form-submit.php',
data: $('#home-sign-up-form').serialize(),
success: function(response) {
console.log(response);
var data = JSON.parse(response);
$suForm.hide();
$tosppText.hide();
$mailSentIcon.show();
$emailSentText.show();
//$emailSentTextEmail.text($suEmail);
$emailSentTextEmail.text(data.suEmail);
$suBox.css("padding-left", "10px");
$suBox.css("padding-right", "10px");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input">
<br><font class="text-error" id="sign-up-error-text"></font>
<br>
<label>
<input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font>
</label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<?php
if (isset($_POST['suEmail']))
{
$con=mysqli_connect("localhost","root","cakpep","backoffice");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$suFirstName = mysqli_real_escape_string($con,$_POST['suFirstName']);
$suLastName = mysqli_real_escape_string($con,$_POST['suLastName']);
$suEmail = mysqli_real_escape_string($con,$_POST['suEmail']);
$suPassword = mysqli_real_escape_string($con,$_POST['suPassword']);
$suDisplayName = mysqli_real_escape_string($con,$_POST['suDisplayName']);
$code = substr(md5(mt_rand()),0,15);
$query = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName,confirmCode,verified)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}','{$confirmCode},'{$verified}')");
echo json_encode($_POST);
}
?>
add this to trigger when submit form
$("#home-sign-up-form").submit(function(event) {
and then on php return the response with json string
echo json_encode($_POST);
and then in the response ajax parse json text to object like this
var data = JSON.parse(response);
$emailSentTextEmail.text(data.suEmail);
i hope this what you want..

AJAX form not submitting data to database

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();
?>

Getting Blank Email

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;

preventDefault() won't work with form.submit()

I'm trying to get my login form to either close my lightbox, or change the text of an errorbox depending on whether or not the login attempt was a success. I'm not sure, but i think it has to do with my
onclick="formhash(this.form, this.form.password);"
which is a JS function that hashes a password, then continues the form submit. it ends with
form.submit();
Here's my code:
HTML:
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="button" class="searchform"
value="Submit" size="40" style="height:45px; width:90px"
onclick="formhash(this.form, this.form.password);" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
</form>
JS:
<script>
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
function(data){//error callback
data = $.parseJSON(data);
if(data.forbidden){
$("#errorBox").html("Error!");
}
else if(data.error){
$("#errorBox").html("Invalid request!");
}
});
});
return false;
});
})(window.jQuery);
</script>
PHP:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
$response = array();
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p'];
if (login($email, $password, $mysqli) == true) {
http_response_code(200);//HTTP OK, requires php 5.4
$response['success'] = true;
} else {
// Login failed
$response['error'] = true;
http_response_code(401);//HTTP forbidden
}
} else {
// The correct POST variables were not sent to this page.
$response['error'] = true;
http_response_code(400);//HTTP bad request
}
echo json_encode($response);
When I log in, the preventDefault() doesn't work. It opens process_login.php in a new page and displays "{"success":true}" on a blank page. Any suggestions? (keeping in mind that it needs to be as secure as possible)
You could try moving it all into a single handler call. By changing the type="button" to type="submit" on your form.
<form action="includes/process_login.php" method="post" name="login_form">
Email: <input class="searchform" type="text" name="email" size="20"/><br />
Password: <input class="searchform" type="password" name="password" id="password" size="20"/><br />
<input type="submit" class="searchform" value="Submit" size="40" style="height:45px; width:90px" />
<input type="text" id="errorbox" style="height:45px; width:180px" value=""><br>
Then you could move your formhash function into the submit function
!(function($){
$(function() {
$('form[name="login_form"]').on('submit', function(event){
event.preventDefault();//don't reload the page
formhash(var1, var2);
$.post('includes/process_login.php', $(this).serialize(), function(data){
//data is a json object which contans the reponse
data = $.parseJSON(data);
$("fade").fadeOut();
$("light").fadeOut();
},
...//the rest of your code

Form values via AJAX to PHP first being cut off and then not being recognized

Submitting the following form:
<form name="register" method="post" onSubmit="registerUser();">
<fieldset>
<label for="user_name">Name</label>
<input name="user_name" type="text" id="user_name" placeholder="Name" />
<label for="user_email">Email</label>
<input name="user_email" type="email" id="user_email" placeholder="Email"/>
<label for="user_password">Password</label>
<input name="user_password" type="password" id="user_password" placeholder="Password" />
<input name="s" type="hidden" value="register" />
</fieldset>
<input type="submit" value="Register" />
</form>
via AJAX
function registerUser(){
var myform = $("form[name='register']"),
data = {};
myform.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: urlService,
type: 'POST',
data: data,
success: function(response){
}
});
return false;
}
The "s" value of "register was being cut off to "regist" when echoed in following PHP statement. So in an effort correct it I escaped the values as so in the prior jQuery statement:
value = escape(that.val());
This then allowed the full value to be passed, although adding "%20" to the name value. I continued as follows...
forwarded on to PHP
print_r($_POST);
try{
$db = new PDO('mysql:host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
switch($_POST['s']){
case 'register':
$response = 'registered ok + ';
break;
case 'login':
break;
}
$response = 'services read';
echo $response;
} catch(PDOException $e){
echo $e->getMessage();
}
At this point all of the $_POST values are being echoed, HOWEVER the value of "register" is not being recognized by the SWITCH statement.
I am not sure what I am doing incorrectly nor at which point... any help in cleaning up these glitches would be greatly appreciated.

Categories

Resources