jQuery form validation with PHP variables - javascript

I'm working on a form validation with PHP variables, just to not repeat myself in HTML when it comes to displaying default values of text inputs & textareas. Basically, what I want to achieve, is that each field has it's own default value, which disappears on focus and appears back on blur, if user hasn't typed anything in.
Then it validates, if user hasn't left fields with default values (which would make default values red, to bring users focus to them). After submitting, form slides up and shows div#thanks with button allowing to show the form again, with text area cleared.
Validation is working ok without PHP variables (there is also server side validation, in case of switched off JS).
PS. Also form appears after clicking on a#opt4, but that part works fine, too.
PS2. My head is melted at this stage, so wouldn't be surprised if there is some ridiculous bugs, just to warn you
$(document).ready(function() {
<!--
<?php
$defaultMsg = "Please type in your message";
$defaultEmail = "Your Email";
$defaultName = "Your name (optional)";
?>
-->
$('#contact-form').hide();
$('a#opt4').click(function (e) {
e.preventDefault();
$('#contact-form').slideToggle("normal", function() {
if ( $(".mobile-sp").css("display") === "none") {
$('html, body').toggleState(function (el) {
el.animate({
scrollTop: $("#anchor").offset().top
}, 800);
}, function (el) {
});
}
});
$('textarea, input[type="text"]').focus(function() {
if ( $(this).hasClass('error')) {
$(this).removeClass('error');
}
var text = $(this).val();
$(this).animate({
color: "#fff"
},400, function () {
if ((text === <?php echo $defaultMsg; ?>) || (text === <?php echo defaultEmail; ?>)) {
$(this).val("");
}
});
});
$('textarea, input[type="text"]').blur(function() {
$(this).animate({
color: "#6599cb"
},400, function () {
if ($.trim(this.value) == '') {
$(this).val(this.defaultValue);
}
});
});
});
// validation
$("#thanks").hide();
$("#submit").click(function(e) {
e.preventDefault();
});
$("#submit").click(function(){
$(".error").hide();
$("#one-more").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailFromVal = $("#emailFrom").val();
var defaultEmail = <?php echo $defaultEmail; ?>;
if((emailFromVal == '') || (emailFromVal === defaultEmail)) {
$("#email").val('defaultEmail');
hasError = true;
} else if(!emailReg.test(emailFromVal)) {
$("#email").val('defaultEmail');
hasError = true;
}
var messageVal = $("#message").val();
var defaultMsg = <?php echo $defaultMsg; ?>;
if((messageVal == '') || (messageVal === defaultMsg)) {
$("textarea").val('#message'.defaultValue).addClass('error');
hasError = true;
}
if(hasError == false) {
$(this).hide();
$("#sendEmail button").append('<img src="modules/contact/loading.gif" alt="Loading" id="loading" />');
$.post("modules/contact/sendEmail.php",
{ emailFrom: emailFromVal, message: messageVal },
function(data){
$("#sendEmail").slideUp("normal", function() {
$("#thanks").slideDown("normal", function() {
$("#one-more").slideDown("slow");
});
});
}
);
}
return false;
});
$("#one-more").click(function(e) {
e.preventDefault();
var defaultMsg = <?php echo $defaultMsg; ?>;
$('#thanks').slideUp("slow",function() {
$('form').slideDown('slow', function() {
$('#submit').show();
$('#message').val('defaultMsg');
});
});
});
});
// HTML
<div id="form">
<?php include('modules/contact/verify.php'); ?>
<h2>Talk to us about your project</h2>
<form action="" method="post" id="sendEmail">
<textarea name="message" id="message"><?php if(isset($_POST['message'])) { echo $_POST['message']; } else { echo $defaultMsg; } ?></textarea><?php if(isset($messageError)) echo '<span class="error">'.$messageError.'</span>'; ?>
<input type="text" name="emailFrom" id="emailFrom" value="<?php if(isset($_POST['emailFrom'])) { echo $_POST['emailFrom']; } else { echo $defaultEmail; } ?>"><?php if(isset($emailFromError)) echo '<span class="error">'.$emailFromError.'</span>'; ?>
<input type="text" name="name" id="name" value="<?php echo $defaultName; ?>">
<input type="submit" id="submit" value="Send">
<input type="hidden" name="submitted" id="submitted" value="true">
</form>
<div id="thanks">
<div class="container">
<img src="gfx/sprites/icn-contact-success.png">
<h3>Thank you.</h3>
<p>We will get back to you as soon as possible.</p>
</div>
Oh no, wait! I want to add something!
</div>
</div>

Related

Login button keep refreshing the page

I'm starting to learn Web Development and trying to build the login screen for my site.
Normally when the user logged in, he will be redirected to the Welcome page( which is the case before I work with all the Javascript). Now click Login will just refresh the page.
Here is my PHP file
<head>
<?php include $_SERVER['DOCUMENT_ROOT'] . "\include\header.php";?>
<title>Login</title>
<link rel="icon" type="image/png" href="http://localhost/image/login/navi.png"/>
</head>
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true && time() < $_SESSION["expire"]){
header("location: http://localhost/main/welcome.php");
exit;
}
$email = $password = "";
$email_err = $password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate credentials
if(empty($email_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT userid, username, email, password FROM users WHERE email = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_email);
// Set parameters
$param_email = $email;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $email, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION['start'] = time(); // Taking now logged in time.
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
// Redirect user to welcome page
header("location: http://localhost/main/welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "Wrong password";
}
}
} else{
// Display an error message if username doesn't exist
$email_err = "Wrong email";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
// Close connection
mysqli_close($link);
}
?>
<body class="background">
<div class="bgoverlay">
<div class="login-container">
<div class="wrap-login">
<span class="login-form-title">
Account Login
</span>
<form class="login-form login-validate-form" >
<div id="email" class="login-wrap-input login-validate-input" data-validate = "Enter email">
<input class="login-input" type="text" name="email" placeholder="Email">
<span class="login-focus-input" data-placeholder=""></span>
</div>
<div class="login-wrap-input login-validate-input" data-validate="Enter password">
<input id="password" class="login-input" type="password" name="password" placeholder="Password">
<span class="login-focus-input" data-placeholder=""></span>
<span toggle="#password" class="login-show-pass see toggle-password"></span>
</div>
<div class="container-login-form-btn">
<?php
if($email_err != null || $password_err !=null) {
echo '<script type="text/javascript">alert("'.$email.$password.'");</script>';
}
?>
<input type="submit" class="login-form-btn" value="Login">
</div>
</form>
</div>
</div>
</div>
<div id="dropDownSelect1"></div>
<script src="http://localhost/root/js/jquery-3.5.0.min.js"></script>
<script src="http://localhost/root/js/login.js?<?php echo(rand(0,999999));?>"></script>
</body>
</html>
*I honestly don't know which part to give so I think it's best to just put them all just in case.
Here is the Javascript that I have been fixing
(function ($) {
"use strict";
/*==================================================================
[ Focus input ]*/
$('.login-input').each(function(){
$(this).on("blur", function(){
if($(this).val().trim() != "") {
$(this).addClass('login-has-val');
}
else {
$(this).removeClass('login-has-val');
}
})
})
/*==================================================================
[ Validate ]*/
var input = $('.login-validate-input .login-input');
function validate (input) {
if($(input).attr('type') == 'email' || $(input).attr('name') == 'email') {
if($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) {
return false;
}
}
else {
if($(input).val().trim() == ''){
return false;
}
}
}
$('.login-validate-form').on('submit',function(){
var check = true;
for(var i=0; i<input.length; i++) {
if(validate(input[i]) == false){
showValidate(input[i]);
check=false;
}
}
return check;
});
$('.login-validate-form .login-input').each(function(){
$(this).focus(function(){
hideValidate(this);
});
});
function showValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).addClass('login-alert-validate');
}
function hideValidate(input) {
var thisAlert = $(input).parent();
$(thisAlert).removeClass('login-alert-validate');
}
/*==================================================================
[ Show pass ]*/
jQuery(document).ready(function() {
jQuery(".show-pass").hide();
});
jQuery("#password").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery(".show-pass").hide();
} else {
jQuery(".show-pass").show();
}
});
jQuery(".show-pass").change(function() {
jQuery("#password").val("");
jQuery(this).hide();
});
$(".toggle-password").click(function() {
$(this).toggleClass("unsee");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
})(jQuery);
This is what the URL look like after pressed Login
Look at your PHP code, you taking in consideration the request should be POST
if($_SERVER["REQUEST_METHOD"] == "POST") ...
and your HTML markup for your form has no method, which is by default going to be GET.
You need to edit you form tag to be like this
<form class="login-form login-validate-form" method="post" action="URL.php">
It's possible that your are not choosing the correct path, please reconfirm the correct path or you can try changing your header to:
header("location:welcome.php");

Loop through fields in a form

Assume I have a table. Each row contains form fields that can be populated or not by the user. I need to check that for each row either all the form fields are populated or none.
The html is this:
<tr class="riga_gar">
<td class="report">
<input type="hidden" id="crediti[<?php echo $i; ?>]" name="crediti[<?php echo $i; ?>]"
value="<?php echo $cred['id_cre']; ?>" >
<?php echo $cred['id_cre'] ?>
</td>
<td class="report gbv" data-gbv="<?php echo $cred['gbv_tot']; ?>">
<?php echo num2cur($cred['gbv_tot']); ?>
</td>
<td class="report">
<?php echo veicolo2name($cred['titolare'],$pdo); ?>
</td>
<td class="report">
<?php echo $cred['stato']; ?>
</td>
<td class="report">
<input class="input_field numerico" id="chiesto" type="text" name="garanzia[<?php echo $i; ?>]" value="<?php echo $chiesto; ?>">
</td>
<td class="report">
<select name="tipo_gar[<?php echo $i; ?>]">
<option value="">Scegli</option>
<?php foreach($tipo_gars as $tipo_gar){
echo '<option value="'.$tipo_gar['id'].'">'.$tipo_gar['descrizione'].'</option>';
}?>
</select>
</td>
</tr>
What I am trying to do is to check that for each row both the input and the select have a value or none.
I started with this js:
function ajax_submit(){
var submit_val=$("#garante").serialize();
dest="anagrafiche/new_garante1.php";
$('.riga_gar').each(function(i,obj){
if ($(this).val()!='') {
}
});
}
and I want to run this ajax function:
$.ajax({
type: "POST",
url: dest,
data: submit_val,
success: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_success").html(data1[1]).fadeTo(900,1)});
}else if(data1[0]=="Errore"){
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_error").html(data1[1]).fadeTo(900,1)});
}
},
complete: function(){
$.fancybox.close();
//setTimeout(function(){ $('.container').load('sofferenze/dashboard.php?from=<?php echo $id_soff ?>');},3000);
setTimeout(function(){
$('#upper').load('sofferenze/soff.php?soff=<?php echo $id_soff ?>');
$("#spnmsg").fadeTo(200,0.1,
function(){$(this).removeClass().addClass("spn_normal").html('Cruscotto della sofferenza <?php echo soff2name($id_soff,$pdo); ?>').fadeTo(900,1)});
},3000);
} //chiudo complete function
}); //chiudo $.ajax
only when:
at least one row have both values;
all the rows that have values have both of them;
but I get stuck at how to refer to the value of input and select in the each loop so that I can check my conditions.
I think this will help you. This will read each row and ignore your hidden field. Once code will find both values populated than validateForm variable will be true and will become false if in next row one value from both input or select will be empty.
$(document).ready(function(){
var validateForm = false;
var check = 0;
$("form").on('submit',function(){
$("tr").each(function(){
console.log($.trim($(this).find("input.input_field").val()) +", "+ $.trim($(this).find("select").val()));
if($.trim($(this).find("input.input_field").val()) != "" && $.trim($(this).find("select").val()) != ""){
validateForm = true;
}
else{
if($.trim($(this).find("input.input_field").val()) == "" && $.trim($(this).find("select").val()) != ""){
if(validateForm){
validateForm = false;
check = 1;
return false;
}
}
if($.trim($(this).find("input.input_field").val()) != "" && $.trim($(this).find("select").val()) == ""){
if(validateForm){
validateForm = false;
check = 1;
return false;
}
}
}
});
if(validateForm && check == 0){
validateForm = true;
}
else{
validateForm = false;
}
if(validateForm){
//call ajax
}
});
});
Demo:https://jsfiddle.net/87tkraas/
This is untested but how about something like this:
var allowSubmit = false;
$("form").on("submit", function(e) {
$("tr").each(function() {
var input = $(this).find("input").val();
var select= $(this).find("select").val();
if ((input == "" && select != "") || (input != "" && select == "")) {
return;
} else if (input != "" && select != "") {
allowSubmit = true;
}
});
if (allowSubmit == false) {
e.preventDefault();
}
});

rsvp form in a WordPress Widget: submits twice, why?

I'm creating a custom WordPress widget that contains a rsvp form. When submited the form sends 2 emails, one to the organizer, one to the guest.
My problem: both email are sent twice (twice to the organizer, twice to the guest). What is wrong in my code?
The code is similar to this:
function widget($args, $instance)
{
//init my vars here
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$raw_datas = $_POST["widget-my_widget_name"];
if (!empty($raw_datas)) {
//this fct treats form data
$rsvpdata = nd_manage_rsvp($raw_datas);
if ($rsvpdata['status'] == 'success') {
//init $to, $subject, $message, $headers according to $rsvpdata
$sent = wp_mail( $to, $subject, $message, $headers, $attachments );
$sent2 = wp_mail( $to2, $subject2, $message2, $headers2, $attachments2 );
if(!($sent === true && $sent2 === true)) {
//failure notice here
$rsvpdata['status'] = 'failure';
} else {
//reinit my vars here
$rsvpdata['status'] = 'sent';
}
}
}
} ?>
<div class="description-text">
<form id="<?php echo $this->get_field_id('rsvp-form'); ?>" name="<?php echo $this->get_field_name('rsvp-form'); ?>" action="#<?php echo $this->id; ?>" method="post" onsubmit="return validate(<?php echo '\'' . $this->id . '\''; ?>)">
//some form inputs here
<input class="rsvp-submit mybutton" type="submit" value="<?php _e('Send','textdomain');?>">
</form>
</div>
<?php
}
Edit: my JS function "validate" is only validation, there is no ajax to handle form:
//validate rsvp form values
function validate(formid) {
var attends = jQuery("#widget-"+formid+"-attend_yes");
var events = jQuery("#widget-"+formid+"-events_check");
var minOneCB = jQuery('#'+formid+' input:checkbox').is(':checked');
var CName = jQuery("#widget-"+formid+"-name");
var CEmail = jQuery("#widget-"+formid+"-email");
CName.tipsy({trigger: 'manual', title: 'data-tipsy', offset: 1});
CEmail.tipsy({trigger: 'manual', title: 'data-tipsy', offset: 1});
events.tipsy({trigger: 'manual', title: 'data-tipsy', offset: 5});
events.tipsy("hide");
CName.tipsy("hide");
CEmail.tipsy("hide");
jQuery(document).on('click', function(event) {
if (!jQuery(event.target).closest('.rsvp-submit').length) {
events.tipsy("hide");
CName.tipsy("hide");
CEmail.tipsy("hide");
}
});
if (attends.is(':checked') && !minOneCB){
events.tipsy("show");
return false;
}
if(CName.val() == ''){
CName.tipsy("show");
return false;
}
//isEmail is a function that check if email is valid
if(CEmail.val() == '' || !isEmail(CEmail.val()) ){
CEmail.tipsy("show");
return false;
}
}

Upload image and text by same form

When I upload image and text by separate form, its work well. But Its not work when I add together.
My form text upload by js and image upload by a php file.
And I think my problem in my form.
If I upload together with js, What change in my js and submit.php, which also add below.
Here is my form code that not work together
<form action="" method="post" id="cmntfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<legend class="pyct">
What's your mind
</legend>
<input type="hidden" name="username" size="22" tabindex="1" id="author" value="'.$pname.'"/>
<input type="hidden" name="email" size="22" tabindex="2" id="email" value="'.$email.'"/>
<p><textarea name="comment" rows="10" tabindex="4" id="comment"></textarea></p>
<div id="ajaxuploadfrm">
<form action="uploadpostimg.php" method="post" enctype="multipart/form-data">
<b>Select an image (Maximum 1mb)</b>
<input type="file" name="url" id="url" />
</form>
</div>
<p><input type="submit" name="submit" value="Post comment" tabindex="5" id="submit"/></span></p>
</fieldset>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
</form>
js
$(document).ready(function(){
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputEmail = $("#email");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
var commentCountList = $("#updatecommentNum");
var error = $("#error");
error.fadeOut();
function updateCommentbox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=update&tutid="+ tutid,
complete: function(data){
commentList.prepend(data.responseText);
commentList.fadeIn(2000);
}
});
}
function updateCommentnum(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=updatenum&tutid="+ tutid,
complete: function(data){
commentCountList.html(data.responseText);
commentList.fadeIn(2000);
}
});
}
function error_message(){
error.fadeIn();
}
function checkForm(){
if(inputAuthor.attr("value") && inputComment.attr("value") && inputEmail.attr("value"))
return true;
else
return false;
}
//on submit event
$("#cmntfrm").submit(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var email = inputEmail.attr("value");
var comment = inputComment.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
//we deactivate submit button while sending
$("#submit").attr({ disabled:true, value:"Sending..." });
$("#submit").blur();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=insert&author="+ author + "&url="+ url + "&email="+ email + "&comment="+ comment + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
commentList.prepend(data.responseText);
updateCommentbox();
updateCommentnum();
//reactivate the send button
$("#submit").attr({ disabled:false, value:"Submit Comment!" });
$( '#cmntfrm' ).each(function(){
this.reset();
});
}
});
}
else //alert("Please fill all fields!");
error_message();
//we prevent the refresh of the page after submitting the form
return false;
});
});
Submit.php
<?php header('Content-Type: charset=utf-8'); ?>
<?php
include("db.php");
include_once("include/session.php");
switch($_POST['action']){
case "update":
echo updateComment($_POST['tutid']);
break;
case "updatenum":
echo updateNumComment($_POST['tutid']);
break;
case "insert":
date_default_timezone_set('Asia/Dhaka');
echo insertComment($_POST['author'], $_POST['comment'], $_FILES['url']['name'], $_POST['email'], $_POST['tutid'], $_POST['parent_id'], $date = date("M j, y; g:i a"));
break;
}
function updateNumComment($tutid) {
//Detail here
}
function updateComment($tutid) {
//Detail here
}
function insertComment($username, $description, $url, $email, $qazi_id, $parent_id, $date ){
global $dbh;
//Upload image script that not work here when i try together so i took it at separate file and then tried with above form
$output_dir = "comimage/";
$allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
$extension = #end(explode(".", $_FILES["url"]["name"]));
if(isset($_FILES["url"]["name"]))
{
//Filter the file types , if you want.
if ((($_FILES["url"]["type"] == "image/gif")
|| ($_FILES["url"]["type"] == "image/jpeg")
|| ($_FILES["url"]["type"] == "image/JPG")
|| ($_FILES["url"]["type"] == "image/png")
|| ($_FILES["url"]["type"] == "image/pjpeg"))
&& ($_FILES["url"]["size"] < 504800)
&& in_array($extension, $allowedExts))
{
if ($_FILES["url"]["error"] > 0)
{
echo "Return Code: " . $_FILES["url"]["error"] . "<br>";
}
if (file_exists($output_dir. $_FILES["url"]["name"]))
{
unlink($output_dir. $_FILES["url"]["name"]);
}
else
{
$pic=$_FILES["url"]["name"];
$conv=explode(".",$pic);
$ext=$conv['1'];
$user = $_SESSION['username'];
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["url"] ["tmp_name"],$output_dir.$user.".".$ext);
$pic=$output_dir.$user.".".$ext;
$u_imgurl=$user.".".$ext;
}
}
else{echo '<strong>Warning !</strong> File not Uploaded, Check image' ;}
}
//Submit main comment
if ($parent_id == 0){
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub = "Comment to";
$query = "INSERT INTO comments_lite VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
} else {
if ($parent_id >= 1){
global $dbh;
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub2 = "Reply to";
$query = "INSERT INTO comments_reply VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
}
}
}
?>
on click of submit you can put the code in js you have to make change in the js file
$.post('phpapgename.php',data:jquerydata,function(){
})
in the .php page you can put your query to submit your data.
You cannot have nested form. Try to avoid it and separate out the forms as below. And while submitting any form if you data from other form, create a hidden fields in this form and submit it.
Another suggestion: Since you're working with javascript anyway, outsource the upload-form to an invisible div and make it pop up by clicking/hovering an upload-button or entering the last field of form1 or whatever.

Checkbox Input doesn't work at all in chrome. Doesn't function in other browsers

Basically I want a checkbox to onClick change whether or not to show explicit content. I'll get right to the code HTML (and PHP):
</form>
<?php if (login_check($mysqli) == true) {
$username = $_SESSION['username'];
echo '
<form name="explicit">
<input type="checkbox" onClick="changeexplicit();" value="Filter Explicit Content" id="explicitcheckbox" ' ;
if (checkadult($mysqli,$username)!=1){echo "checked";}
echo ' /> <label for="explicitcheckbox" class="explicit">Filter Explicit Content</label>
</form>';}?>
Jquery: (i left the error handling blank because I didn't realize JQuery doesn't have a built in popup alert)
<script>
changeexplicit()
{
!(function($){
$(function() {
$.post('includes/changeadult.php', $('form[name="explicit"]').serialize(), function(data){
data = $.parseJSON(data);
if(data.success){
window.location.reload(true);
}
else if(data.error){
}
else{
}
});
});
})(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 (login_check($mysqli) == true) {
$username=$_SESSION['username'];
$result=mysqli_query($mysqli,'SELECT isAdult FROM members WHERE username = "'.$username.'"');
$userinfo = mysqli_fetch_array($result);
$isAdult=$userinfo['isAdult'];
if ($isAdult==1)
{mysqli_query($mysqli,'UPDATE members SET isAdult=0 WHERE username="'.$username.'"');}
else{
{mysqli_query($mysqli,'UPDATE members SET isAdult=1 WHERE username="'.$username.'"');}}
$response['success'] = true;
}
else if(login_check($mysqli) == false) {
$response['error'] = true;
}
echo json_encode($response);
<script>
function changeexplicit(){
$.post('includes/changeadult.php', $('form[name="explicit"]').serialize(), function(data){
data = $.parseJSON(data);
if(data.success){
window.location.reload(true);
}else if(data.error){
}else{}
});
}
</script>
Try change onClick toonchange?

Categories