Translating a Contact Form's placeholders / JQuery / JavaScript / Contact Form - javascript

Hello,
I've written a multilanguage website using jquery and localStorage. The translator works perfect. There are no bugs.
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
var arrLang = {
'pl': {
'home': 'Strona główna',
'about': 'O nas',
'contact': 'Kontakt',
'gallery': 'Galeria',
'callnow': 'Zadzwoń teraz i umów przeprowadzkę!'
},
'en': {
'home': 'Home',
'about': 'About',
'contact': 'Contact',
'gallery': 'Gallery',
'callnow': 'Call now and sign up!'
}
};
function translateLang(lang) {
$('.lang').each(function(index, item) {
$(this).text(arrLang[lang][$(this).attr('key')]);
});
};
$(function() {
//first check for stored language in localStorage i.e. fetch data from localStorage
let stored_lang = localStorage.getItem("stored_lang");
//if any then translate page accordingly
if(stored_lang != null && stored_lang != undefined)
{
lang = stored_lang;
translateLang(lang);
}
$('.translate').click(function() {
var lang = $(this).attr('id');
//on click store language to localStorage
localStorage.setItem("stored_lang",lang);
translateLang(lang);
});
});
</script>
<button id="pl" class="translate">Polski</button>
<button id="en" class="translate">English</button>
<nav class="header-bottom-left">
<ul>
<li class="lang" key="home">Strona główna</li>
<li class="lang" key="about">O nas</li>
<li class="lang" key="gallery">Galeria</li>
<li class="lang" key="contact">Kontakt</li>
</ul>
</nav>
Now I'm having a problem with translating a Contact Form's placeholders. I figured out to use JavaScript document.getElementById('id').placeholder='string'; and it works just great, but the data isn't being saved in localStorage and after the refresh of the site it's showing the basic strings again. I also changed on my translator buttons to so don't be confused about my code above.
<div class="contact-form-container">
<div class="contact-form">
<form id="contact-form" action="contact-form-handler.php" method="POST">
<p class="lang" key="contact-form" style="margin: 0 auto; font-size: 22px; font-family: Open Sans; color: #ff4800; margin-bottom: 8px;">Formularz kontaktowy</p>
<div class="flex-break"></div>
<input id="contact-form-name" class="contact-form-content" type="text" name="name" placeholder="Imię" required><div class="flex-break"></div>
<input id="contact-form-email" class="contact-form-content" type="email" name="email" placeholder="E-mail" required><div class="flex-break"></div>
<input id="contact-form-topic" class="contact-form-content" type="text" name="topic" placeholder="Temat" required><div class="flex-break"></div>
<!-- <select style="flex-basis:12%; padding: 6px;" class="contact-form-content" id="prefix" name="whereFromPrefix">
<option value="ul.">ul.</option>
<option value="os.">os.</option>
<option value=" "></option>
</select>
<input style="flex-basis:67%;" class="contact-form-content" type="text" name="whereFrom" placeholder="Skąd? Adres, Miasto"><div class="flex-break"></div>
<select style="flex-basis:12%; padding: 6px; margin-bottom: 12px;" class="contact-form-content" id="prefix" name="whereToPrefix">
<option value="ul.">ul.</option>
<option value="os.">os.</option>
<option value=" "></option>
</select>
<input style="flex-basis:67%; margin-bottom: 12px;" class="contact-form-content" type="text" name="whereTo" placeholder="Dokąd? Adres, Miasto"><div class="flex-break"></div> -->
<textarea id="contact-form-text" style="line-height:16px; font-size: 14px; font-family: calibri;" class="contact-form-content" name="message" id="contact-form-message" cols="" rows="10" placeholder="Dodatkowe informacje"></textarea>
<div class="flex-break"></div>
<button class="contact-form-content-submit" name="submit" type="submit">Wyślij<img id ="Contact_icon_white" src="img/Contact_icon_white.png" alt="White contact icon"></button>
</form>
</div>
</div>
<div class="header-top-right-translate">
<div id="pl" class="translate translate-button"><p onclick="
document.getElementById('contact-form-name').placeholder='Imię';
document.getElementById('contact-form-email').placeholder='E-mail';
document.getElementById('contact-form-topic').placeholder='Temat';
document.getElementById('contact-form-text').placeholder='Dodatkowe informacje';
">Polski</p></div>
<div><p style="opacity: 0.7; font-size: 12px;">|</p></div>
<div id="en" class="translate translate-button"><p onclick="
document.getElementById('contact-form-name').placeholder='Name';
document.getElementById('contact-form-email').placeholder='E-mail';
document.getElementById('contact-form-topic').placeholder='Topic';
document.getElementById('contact-form-text').placeholder='More information';
">English</p></div>
</div>
Can someone tell me how to change the placeholders inside Contact Form but to not lose them after refreshing the site?

Related

How to order icon next to a span in HTML with CSS?

I am trying to do something like a verification on contact form, e.g if email does not contain "#" and "." show icon of red X and if the conditions are done show green check mark. I need answer on 2 questions: 1. How to align the icon next to the span and the 2. How to center the form in the middle of the screen? I tried with display:flex, many other floats, positions, aligns and every solution I found in the internet, but I anything had success in setting the icon between different tags and centering the form in the middle of the screen but the only one thing I came to is: link
< script type = "text/javascript" >
$(document).ready(function() {
$('.submit').click(function(event) {
console.log('Clicked button')
var name = $('.name').val()
var email = $('.email').val()
var phone = $('.phone').val()
var message = $('.message').val()
var statusElm = $('.status')
statusElm.empty()
if (email.length > 5 && email.includes('#') && email.includes('.')) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
if (phone.length > 7 && phone.legth < 14) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
if (message.length > 20) {
statusElm.append('<i style="color: green; font-size:2.3em;" class="fas fa-check"></i>')
} else {
event.preventDefault()
statusElm.append('<i style="color: red; font-size:2.3em;" class="fas fa-times"></i>')
}
})
}) <
/script>
<div class="mail " id="mail">
<div class="container">
<h3 class="w3l_head w3l_head1">Contact Me</h3>
<p class="w3ls_head_para w3ls_head_para1">send Me a message</p>
<div class="w3_mail_grids">
<form action="https://formspree.io/ntodorov301#gmail.com" method="POST" class="justify-content-center">
<div class="col-md-6 w3_agile_mail_grid">
<span class="input input--ichiro"><input
class="input__field input__field--ichiro" type="text" name="name"
id="input-25" placeholder=" " >
<label class="input__label input__label--ichiro" for="input-25">
<span class="input__label-content input__label-content--ichiro">Your
Name</span>
</label>
</span>
<a class="status" name="status"></a> <span class="input input--ichiro"> <input
class="input__field input__field--ichiro email" type="email" name="Email"
id="input-26" placeholder=" " > <label
class="input__label input__label--ichiro" for="input-26">
<span class="input__label-content input__label-content--ichiro">Your
Email</span>
</label>
</span> <span class="input input--ichiro"> <input
class="input__field input__field--ichiro phone" type="text" name="phone"
id="input-27" placeholder=" " > <label
class="input__label input__label--ichiro" for="input-27">
<span class="input__label-content input__label-content--ichiro">Your
Phone Number</span>
</label>
</span>
</div>
<div class="col-md-6 w3_agile_mail_grid">
<textarea class="message" name="message" placeholder="Your Message"></textarea>
<input type="submit" value="Submit" class="submit">
</div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
The Bootstrap is alredy used on the page. Thus, I recommend you to apply validation feature of the framework instead of creation of custom CSS rules. You could use .is-valid and .is-invalid styles for the controls or constraint validation API within custom validation methods.
The following example will help you to get started. I don't want to post too much code, therefore my form contains a single control.
document.getElementById('emailField')
.addEventListener('input', function(e) {
this.classList.remove('is-valid', 'is-invalid')
if (!isValidEmail(this.value))
this.classList.add('is-invalid');
else
this.classList.add('is-valid');
}, false);
document.getElementById('myForm')
.addEventListener('submit', function(e) {
checkEmail(document.getElementById('emailField'));
if (!this.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
this.classList.add('was-validated');
}, false);
function checkEmail(control) {
if (!isValidEmail(control.value)) {
control.setCustomValidity('The e-mail is invalid.');
console.log(control.validationMessage);
} else {
control.setCustomValidity('');
}
}
function isValidEmail(email) {
return /^[\w!#$%&'*+-\/=\?^_`{|}~](\.?[\w!#$%&'*+-\/=\?^_`{|}~])*#gmail\.com$/i.test(email);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container">
<form id="myForm" novalidate>
<div class="form-group">
<label for="emailField">Email address</label>
<input type="email" class="form-control" id="emailField" aria-describedby="emailHelp" placeholder="Enter email">
<small class="valid-feedback">The e-mail address is valid!</small>
<small class="invalid-feedback">The e-mail address is invalid.</small>
<small id="emailHelp" class="form-text text-muted">Only Gmail is supported</small>
</div>
<button class="btn btn-primary" type="submit">Send</button>
</form>
</div>
The snippet uses .is-invalid and .is-valid classes to indicate validation result while user is inputing e-mail address. In the submit event handler the constraint validation API is used. The forms allows to send only address of Gmail. If you will try to use another domain it throws an error.

Submission form is not properly submitting information to SQL (PHP and JS)

I've made a jobs post form in which a user fills out and after submitting the form, the job should be displayed on the same page under it. for some reason, the job description and job location data that's returned comes up as undefined. I'm thinking it might be because they're a drop-down list and text area? but I can't see to fully comprehend why the error shows up. Also, how would I go about submitting radio buttons to a database? would they need specific values?
Below is the jobs.html page
<?php
//allow the config
define('__CONFIG__', true);
//require the config
require_once "inc/config.php"; //possibly have to change the location
Page::ForceLogin();
?>
<!DOCTYPE html>
<html>
<head>
<!-- UIKit CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.24/css/uikit.min.css" />
<link rel="stylesheet" href="style.css">
<title>Login Page</title>
<base href="/"/>
<nav class="uk-navbar-container uk-margin" uk-navbar>
<div class="uk-navbar-left">
<a class="uk-navbar-item uk-logo" href="comp1687/index.php"><img src="/comp1687/jobswatchsmall.png" alt="sitelogo"></a>
<ul class="uk-navbar-nav">
<li>
<a href="comp1687/index.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>Home Page</b>
</a>
</li>
<li>
<a href="comp1687/jobs.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>Jobs</b>
</a>
</li>
</div>
<div class="uk-navbar-center">
<div class="uk-navbar-item">
<form action="javascript:void(0)">
<input class="uk-input uk-form-width-small" style="width:350px; border-radius: 10px; " type="text" placeholder="Input">
<button class="uk-button uk-button-default" style="border-radius: 10px;">Button</button>
</form>
</div>
</div>
<div class="uk-navbar-right">
<ul class="uk-navbar-nav">
<li>
<a href="comp1687/about.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>About Us</b>
</a>
</li>
<li>
<a href="comp1687/dashboard.php">
<span class="uk-icon uk-margin-small-right" ></span>
<b>Profile Page</b>
</a>
</li>
</div>
</nav>
</head>
<body>
<div class="uk-section uk-container">
<div class="uk-grid uk-child-width-1-3#s uk-child-width-1-1" uk-grid></div>
<h2><b><center>Jobs</center></b></h2>
<div style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;">
<h4><center>Welcome to the job browsing section. You are able to browse the available jobs below, and if desired, you may post your own job!</center></h4>
<div class="jobspost" style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;">
<h4><center><b>Post a job</b></center></h4>
<form class="uk-form-stacked js-jobs">
<fieldset class="uk-fieldset">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job title:</b></label>
<input id="jobTitle" class="uk-input" type="text" required placeholder="Insert the name of the job">
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Skills required:</b></label>
<input id="jobSkills" class="uk-input" type="text" required placeholder="Insert the skills needed for the job">
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job description:</b></label>
<textarea id="jobDescription" class="uk-textarea" rows="5" required placeholder="Insert a description of the job"></textarea>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Images (If necessary):</b></label>
<input id="jobImage" class="uk-button uk-button-default" type="file" name="jobImage" >
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job location:</b></label>
<select id="jobLocation" required class="uk-select">
<option>-Select a region of london for the jobs location-</option>
<option>-------CENTRAL-------</option>
<option>Camden</option>
<option>City of London</option>
<option>Kensington and Chelsea</option>
</select>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text"><b>Job reward:</b></label>
<input id="jobReward" class="uk-input" required type="text" placeholder="Insert the amount of credits this job is worth">
</div>
<div class="uk-margin uk-grid-small uk-child-width-auto uk-grid">
<label class="uk-form-label" for="form-stacked-text"><b>Job status:</b></label>
<label><input id="jobStatus" class="uk-radio" type="radio" name="radio2" checked> Available</label>
<label><input id="jobStatus" class="uk-radio" type="radio" name="radio2"> Completed</label>
</div>
<center><button id="jobbtn" name="jobbtn" class="uk-button uk-button-default" type="submit"><b>SUBMIT JOB</b></button></center>
<br>
</fieldset>
</form>
</div>
<br>
<div class="jobsbrowse" style="border: 3px solid #ddd; border-radius: 10px; padding: 10px;">
<h4><center><b>Browse the jobs</b></center></h4>
</div>
</div>
</div>
<?php require_once "inc/footer.php"; ?> <!-- possibly have to change the location -->
</body>
</html>
The code below is the ajax/jobs
<?php
//allow the config
define('__CONFIG__', true);
//require the config
require_once "../inc/config.php"; //possibly have to change the location
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//Always return JSON format
//header('Content-Type: application/json');
$return = [];
$jobTitle = Filter::String($_POST['jobTitle']);
$jobSkills = Filter::String($_POST['jobSkills']);
$jobDescription = Filter::String($_POST['jobDescription']);
$jobLocation = Filter::String($_POST['jobLocation']);
$jobReward = Filter::String($_POST['jobReward']);
$jobStatus = Filter::String($_POST['jobStatus']);
// make sure the user adds a job.
$addJob = $con->prepare("INSERT INTO jobs(jobTitle, jobSkills, jobDescription, jobLocation, jobReward, jobStatus) VALUES(:jobTitle, :jobSkills, :jobDescription, :jobLocation, :jobReward, :jobStatus)");
$addJob->bindParam(':jobTitle', $jobTitle, PDO::PARAM_STR);
$addJob->bindParam(':jobSkills', $jobSkills, PDO::PARAM_STR);
$addJob->bindParam(':jobDescription', $jobDescription, PDO::PARAM_STR);
$addJob->bindParam(':jobLocation', $jobLocation, PDO::PARAM_STR);
$addJob->bindParam(':jobReward', $jobReward, PDO::PARAM_STR);
$addJob->bindParam(':jobStatus', $jobStatus, PDO::PARAM_STR);
$addJob->execute();
// return the proper information back to Javascript to redirect us.
echo json_encode($return, JSON_PRETTY_PRINT);
} else {
//Kill the script. Redirect the user.
exit('Invalid URL');
}
?>
The code below is the JS responsible for submittion.
.on("submit", "form.js-jobs", function(event) {
event.preventDefault();
var _form = $(this);
var _error = $(".js-error", _form);
var jobObj = {
jobTitle: $("input[id='jobTitle']", _form) .val(),
jobSkills: $("input[id='jobSkills']", _form) .val(),
jobDescription: $("input[id='jobDescription']", _form) .val(),
jobLocation: $("input[id='jobLocation']", _form) .val(),
jobReward: $("input[id='jobReward']", _form) .val(),
jobStatus: $("input[id='jobStatus']", _form) .val(),
};
if(jobObj.length < 1) {
_error
.text("Please fill in all fields.")
.show();
return false;
}
// Assuming the code gets this far, we can start the ajax process
_error.hide();
console.log(jobObj)
$.ajax({
type: 'POST',
url: 'comp1687/ajax/jobs.php', //possibly have to change the location
data: jobObj,
dataType: 'json',
async: true,
})
.done(function ajaxDone(data) {
// Whatever data is
if(data.redirect !== undefined) {
window.location.reload();
console.log('data');
} else if(data.error !== undefined) {
_error
.html(data.error)
.show();
console.log('data');
}
})
.fail(function ajaxFailed(e) {
//this failed
console.log(e);
})
.always(function ajaxAlwaysDoThis(data) {
//always do
console.log('Always');
})
return false;
})

Ajax form submit doesn't work on 1 page

I've a form that I submit with JQuery AJAX. But after I clicked submit, my page is redirect to my form submit.php. I've tried almost everything, but I can't find the bug...
The PHP script is working fine. I only echo once,
HTML:
<form class="offerte-form" method="post">
<div class="col-sm-6">
<input type="text" class="name" id="naamofferte" name="naam" placeholder="Naam*" required="" style="border-radius: 4px;">
<input type="text" class="name" id="naambedrijf" name="naambedrijf" placeholder="Naam bedrijf" style="border-radius: 4px;">
<input type="text" class="name" id="adresofferte" name="adres" placeholder="Adres" style="border-radius: 4px;">
<input type="text" class="name" id="vestplaats" name="vestplaats" placeholder="Vestigingsplaats" style="border-radius: 4px;">
<input type="text" class="name" id="postcode" name="postcode" placeholder="Postcode" style="border-radius: 4px;">
<input type="email" class="name" id="emailofferte" name="email" placeholder="Emailadres*" required="" style="border-radius: 4px;">
</div>
<div class="col-sm-6">
<input type="text" class="name" id="telnrofferte" name="telnr" placeholder="Telefoonnummer*" required="" style="border-radius: 4px;">
<select class="name" name="offertevoor" id="offertevoor" style="border-radius: 4px;" required>
<option value="none">
Selecteer een optie
</option>
<option value="pallets aanbieden">
Ik wil pallets aanbieden
</option>
<option value="pallets kopen">
Ik wil pallets kopen
</option>
<option value="containerservice">
Containerservice
</option>
</select>
<textarea placeholder="Uw opmerkingen" id="messageofferte" name="message" required="" style="border-radius: 4px;"></textarea>
<input type="submit" value="Verstuur">
</div>
</form>
JS:
$(function() {
// Get the form.
var form3 = $('.offerte-form');
// Get the messages div.
var formMessages3 = $('.offerte-form-message');
$(form3).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData3 = $(form3).serialize();
console.log(formData3);
$.ajax({
type: 'POST',
url: $(form3).attr('action'),
data: formData3
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages3).removeClass('alert alert-danger');
$(formMessages3).addClass('alert alert-success');
// Set the message text.
$(formMessages3).text(response);
// Clear the form.
$('#naamofferte').val('');
$('#naambedrijf').val('');
$('#adresofferte').val('');
$('#vestplaats').val('');
$('#postcode').val('');
$('#emailofferte').val('');
$('#telnrofferte').val('');
$('#offertevoor').val('');
$('#messageofferte').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages3).removeClass('alert alert-success');
$(formMessages3).addClass('alert alert-danger');
// Set the message text.
if (data.responseText !== '') {
$(formMessages3).text(data.responseText);
} else {
$(formMessages3).text('Helaas, er ging iets fout, probeer het opnieuw');
}
});
});
Sorry for these lines, I needed to add more 'details' but I don't have them.
Thanks in advance!
ajax url u call to attr('action') of .offerte-form but I cant see action in your form.check it please.
<form class="offerte-form" method="post" action="submit.php">

Auto populate dropdown fields doesn't work

I have 2 drop down fields which both auto populated.
Example :
car_model -> dropdown_field1
car_model_variants -> dropdown_field2
When I select a model in car_model field, car_model_variants must update its values.
In my case, I have index.php where you can click a button that will show the modal box and you'll find the auto populated drop down fields.
First attempt, when selecting a car_model it works the car_model_variants field is updating its values. But it doesn't work if I submit a form when car_model_variants is empty, If I try to select a car_model again? the dropdown 2 field is not updating. Below is my code.
(function ($) {
$('.edit').formPopup({
'modalParams': {
'parent_container': $('div.autodeal')
},
'callback': function (settings)
{
$('.modal')
.addClass('large')
.css({'z-index': 101});
$('#used_car_car_model').change(function () {
var select = $(this);
$.ajax({
'url': '{{ path("autodeal_backend_filter_select") }}',
'data': {'carModelId': select.val(), 'carGuideOnly': 0, 'isVerified': 1, 'showCompleteName': 1},
success: function (html)
{
$('#used_car_car_model_variant').html(html);
}
});
});
},
'formSubmitParams': {
'retainFormUrl': false,
'submit_callback': function ()
{
window.location.reload();
},
'error_callback': function (form, settings)
{
$('.close, .exit', $(settings.container))
.click(function () {
window.location.reload();
});
}
}
});
})(jQuery);
Here's the full code.
<form novalidate="" action="/app_dev.php/used-car-listings/164/edit" method="POST">
<div class="marginbottom row gutters">
<div class="col span_12">
<div>
<div>
<label for="used_car_plate_number" class="required">Plate number</label>
<input type="text" id="used_car_plate_number" name="used_car[plate_number]" required="required" value="GS0909">
</div>
<div>
<label for="used_car_year" class="required">Year</label>
<input type="text" id="used_car_year" name="used_car[year]" required="required" value="2015">
</div>
<div>
<label for="used_car_car_model" class="required">Car Model</label>
<select id="used_car_car_model" name="used_car[car_model]" required="required">
<option value="">Select A Model</option><option value="102">Mercedes-Benz A-Class</option><option value="401" selected="selected">Mercedes-Benz AMG</option><option value="103">Mercedes-Benz B-Class</option><option value="105">Mercedes-Benz C-Class Coupe</option><option value="104">Mercedes-Benz C-Class Sedan</option><option value="115">Mercedes-Benz CLA-Class</option><option value="576">Mercedes-Benz CLC-Class</option><option value="577">Mercedes-Benz CLK-Class</option><option value="106">Mercedes-Benz CLS-Class</option><option value="107">Mercedes-Benz E-Class</option><option value="578">Mercedes-Benz G-Class</option><option value="108">Mercedes-Benz GL-Class</option><option value="109">Mercedes-Benz GLK-Class</option><option value="110">Mercedes-Benz M-Class</option><option value="111">Mercedes-Benz S-Class</option><option value="112">Mercedes-Benz SL-Class</option><option value="113">Mercedes-Benz SLK-Class</option><option value="114">Mercedes-Benz SLS-Class</option><option value="579">Mercedes-Benz Viano</option></select>
</div>
<div>
<label for="used_car_car_model_variant" class="required">Car Model Variant</label>
<select id="used_car_car_model_variant" name="used_car[car_model_variant]" required="required"><option value="">Select Mercedes-Benz A-Class Variant</option><option value="343">2014 Mercedes-Benz A-Class A 250 Sport 4MATIC</option><option value="344">2014 Mercedes-Benz A-Class A 45 AMG</option></select>
</div>
<div>
<label for="used_car_mileage" class="required">Mileage</label>
<input type="text" id="used_car_mileage" name="used_car[mileage]" required="required" value="1700">
</div>
<div>
<label for="used_car_price" class="required">Price</label>
<input type="text" id="used_car_price" name="used_car[price]" required="required" value="3288300">
</div>
<div>
<label for="used_car_used_car_color" class="required">Color</label>
<select id="used_car_used_car_color" name="used_car[used_car_color]" required="required">
<option value="">Select A Color</option><option value="1">Red</option><option value="2">Blue</option><option value="3">Black</option><option value="4">White</option><option value="5">Green</option><option value="6">Silver</option><option value="7" selected="selected">Grey</option><option value="8">Yellow</option><option value="9">Brown</option><option value="10">Beige</option><option value="11">Orange</option><option value="12">Purple</option><option value="13">Pink</option><option value="14">Turquoise</option><option value="15">Bronze</option></select>
</div>
<div>
<label for="used_car_description" class="required">Description</label>
<textarea id="used_car_description" name="used_car[description]" required="required" cols="4" rows="3">Body color, Tenorite Gray</textarea>
</div>
<div>
<label class="required">City</label>
<input type="hidden" id="used_car_city_id" name="used_car[city][id]" value="20"><input type="text" id="used_car_city_text" name="used_car[city][text]" required="required" autocomplete="off" value="San Juan, Metro Manila">
</div>
<div>
<label class="required">Is service record submitted</label>
<div id="used_car_is_service_record_submitted"><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_0" name="used_car[is_service_record_submitted]" required="required" value="1">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_service_record_submitted_1" name="used_car[is_service_record_submitted]" required="required" value="0" checked="checked">No</label></div>
</div>
<div>
<label class="required">Is LTO verified</label>
<div id="used_car_is_lto_verified"><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_0" name="used_car[is_lto_verified]" required="required" value="1" checked="checked">Yes
</label><label class="marginleft marginright"><input type="radio" id="used_car_is_lto_verified_1" name="used_car[is_lto_verified]" required="required" value="0">No
</label></div>
</div>
<div>
</div>
</div>
<input type="hidden" id="used_car__token" name="used_car[_token]" value="4e4UOHBr5SmtV7Pb0WoWv4xSz90LoVarNG8hw0dy_RY"> <hr class="nomargin marginbottom30 margintop20">
<div class="row">
<button type="submit" class="button">Save</button>
</div>
</form>

My captcha is not working into my registration form

I'm making my registration form to which if user types correct captcha code then user's data will be stored into database, if captcha code is wrong then it'll print output as a wrong but my problem is if user enters the wrong captcha's code it will store user's data into database as well as showing "wrong code" output, pls help where i'm wrong?
here is my code.
<?php session_start(); ?>
<?php
// show potential errors / feedback (from registration object)
if (isset($registration)) {
if ($registration->errors) {
foreach ($registration->errors as $error) {
echo '<div class="alert-box error"><span>Error: </span>'.$error.'</div>';
}
}
if ($registration->messages) {
foreach ($registration->messages as $message) {
echo '<div class="alert-box success"><span>Success: </span>'.$message.'</div>';
}
}
}
/** Validate captcha */
if (!empty($_REQUEST['captcha'])) {
if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) {
$captcha_message ="Invalid captcha";
$style = "background-color: #FF606C color:#555
border-radius: 0px
font-family:Tahoma,Geneva,Arial,sans-serif font-size:11px;
font-size: 18px
padding: 30px 36px
margin:10px font-weight:bold
text-transform:uppercase border:2px solid #0c0b0b
background-color: #ff7e48 ";
echo'
<div id="result" style="$style">
<h2><div class="alert-box error"><span>error: </span>'.$captcha_message.'</div></h2>
</div>';
} else {
$captcha_message = "Valid captcha";
$style = "background-color: #CCFF99";
}
$request_captcha = htmlspecialchars($_REQUEST['captcha']);
unset($_SESSION['captcha']);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration with Linkvessel and collaborate with college's friends</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function(){
$("#datepicker").datepicker();
});
</script>
<style>
.alert-box {
color:#555;
border-radius: 0px;
font-family:Tahoma,Geneva,Arial,sans-serif; font-size:11px; font-size: 18px;
padding: 30px 36px;
margin:10px;
}
.alert-box span {
font-weight:bold;
text-transform:uppercase;
}
.error {
border:2px solid #0c0b0b;
background-color: #ff7e48;
}
.success{
border:2px solid #0c0b0b;
background-color: #a3ea42;
}
</style>
</head>
<body onload="document.getElementById('captcha-form').focus()">
<div id="header">
<img id="logo_size" src="./images/logo.png" onmousedown="return false">
</div><br><br><br>
<form id="form_box" method="post" action="register.php" name="registerform">
<div id="title">
<h2>REGISTRATION FORM</h2>
</div>
<div class="controls pos_selectbox">
<select id="basic" name="user_college" class="input-medium">
<option>Select College</option>
<option>MAIIT kota</option>
</select>
<select id="basic" name="user_branch" class="input-medium">
<option>Select Branch</option>
<option>Computer science</option>
<option>Civil</option>
<option>Mechanical</option>
<option>Electrical</option>
<option>Bioinformatic</option>
</select>
<select id="basic" name="user_year" class="input-medium">
<option>Select year</option>
<option>1st year</option>
<option>2nd year</option>
<option>3rd year</option>
<option>4th year</option>
<option>Year completed</option>
</select>
</div><br>
<input id="input_pos" type="email" name="user_email" required="" placeholder="Email address" /><br><br>
<input id="input_pos" type="password" name="user_password_new" required="" placeholder="Password" /><br><br>
<input id="input_pos" type="password" name="user_password_repeat" required="" placeholder="Confirm password" /><br><br>
<input id="name_pos" type="text" name="user_firstname" required="" placeholder="First name" />
<input id="name_pos2" type="text" name="user_lastname" required="" placeholder="Last name" /><br><br>
<input id="datepicker" type="text" name="user_dob" required="" placeholder="Date of birth" /><br><br>
<input id="name_pos" type="text" name="user_state" required="" placeholder="State" />
<input id="name_pos2" type="text" name="user_city" required="" placeholder="city" /> <br><br>
<img src="captcha.php" id="captcha" /><br/>
<a href="#" onclick="
document.getElementById('captcha').src='captcha.php?'+Math.random();
document.getElementById('captcha-form').focus();"
id="change-image">Not readable? Change text.</a><br/><br/>
<input type="text" name="captcha" id="captcha-form" autocomplete="off" placeholder="Type code here" /><br><br>
<input type="submit" name="register" id="pos_submit" class="btn btn-primary btn-large" value="Create account.."/>
</form>
</html>
EDITED
<?php
// checking for minimum PHP version
if (version_compare(PHP_VERSION, '5.3.7', '<')) {
exit("Sorry, Simple PHP Login does not run on a PHP version smaller than 5.3.7 !");
} else if (version_compare(PHP_VERSION, '5.5.0', '<')) {
// if you are using PHP 5.3 or PHP 5.4 you have to include the password_api_compatibility_library.php
// (this library adds the PHP 5.5 password hashing functions to older versions of PHP)
require_once("libraries/password_compatibility_library.php");
}
// include the configs / constants for the database connection
require_once("config/db.php");
// load the registration class
require_once("classes/Registration.php");
// create the registration object. when this object is created, it will do all registration stuff automatically
// so this single line handles the entire registration process.
$registration = new Registration();
// show the register view (with the registration form, and messages/errors)
include("views/register.php");
?>
Simple example, remove register.php and on the Else add information on database if captcha is correct.
/** Validate captcha */
if (!empty($_REQUEST['captcha'])) {
if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) {
$captcha_message ="Invalid captcha";
$style = "background-color: #FF606C color:#555
border-radius: 0px
font-family:Tahoma,Geneva,Arial,sans-serif font-size:11px;
font-size: 18px
padding: 30px 36px
margin:10px font-weight:bold
text-transform:uppercase border:2px solid #0c0b0b
background-color: #ff7e48 ";
echo'
<div id="result" style="$style">
<h2><div class="alert-box error"><span>error: </span>'.$captcha_message.'</div></h2>
</div>';
} else {
$captcha_message = "Valid captcha";
$style = "background-color: #CCFF99";
//insert in database here and redirect to index or profil
}
$request_captcha = htmlspecialchars($_REQUEST['captcha']);
unset($_SESSION['captcha']);
}
and replace
<form id="form_box" method="post" action="register.php" name="registerform">
with
<form id="form_box" method="post" action="" name="registerform">

Categories

Resources