How to disable submit button until validation passed in specific field - javascript

I am trying to submit a form. In the form, I have a field calles sitename. If the user enters a sitename which is already in the database, it will show the message "That name is already in use" and give some suggestions. Up to this point, it works. But what I want, is to hide the submit button until the user enters a valid value to that field.
Here is my code:
form.php:
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
check_name.php:
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
/*echo "<span style='color:white;'>Available</span>";*/
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
}

Try this code,
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html != 'success')
{
$("#disp").html(html);
$("#btn-signup").hide();
}
else
{
$("#btn-signup").show();
}
},
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none;">Submit</button>
</div>
And in your check_name.php
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo "success";
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
die;
}
?>

You will need to keep track on the outcome of your PHP script.
Change your code to:
PHP
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo json_encode([ "status" => 1, "html" => "<span style='color:white;'>Available</span>" ]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode([ "status" => 0, "html" => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>" ]);
}
}
?>
HTML
<script type="text/javascript">
$(document).ready(function () {
$("#btn-signup").hide();
$("#sitename").keyup(function () {
$("#btn-signup").hide();
var sitename = $('#sitename').val();
if (sitename == "")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename=" + sitename,
dataType: "json",
success: function (result) {
if (result.status == 1) {
$("#btn-signup").show();
}
$("#disp").html(result.html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
That is, hide the button on start, if a user enters something, hide the button and wait till the text is validated. If it is valid, show it. If the user changes the text, then the button will be hidden again.
Please note:
1) mysql_* functions are deprecated since version 5.5 and have been removed in version 7. This on its own is enough indication that you need to move on and use something more secure and actively supported.
2) mysql_real_escape_string and mysqli_real_escape_string are not safe since they don't reliably consider server encoding. If you want to be safe, use real prepared statements (i.e. prepared statements which are prepared on the MySQL server).

I would suggest you to use json to return the data like this:
{
"status": "success",
"html" : "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"
}
and here's the javascript code:
$(document).ready(function()
{
/** Hide the button first */
$('button').hide();
$('#sitename').on('input', function()
{
var sitename = $('#sitename').val();
if(sitename == '')
{
$("#disp").html("");
}
else
{
$.ajax(
{
type : "POST",
dataType: "json"
url : "check_name.php",
data : "sitename=" + sitename ,
success : function(data)
{
/** When the data is invalid */
if(data.status === 'error')
{
$('button').hide();
$("#disp").html(data.html);
}
else
{
$('button').show();
/** Hide the html when the data is valid */
$("#disp").html('');
}
},
});
}
})
});
And your php code:
<?php
include('dbconnect.php');
header('Content-Type: application/json; charset=utf-8');
if(isset($_POST['sitename']))
{
$sitename = mysql_real_escape_string($_POST['sitename']);
$query = mysql_query("select * from template_users where sitename='$sitename'");
$row = mysql_num_rows($query);
if($row == 0)
{
echo json_encode(['status' => 'success',
'html' => "<span style='color:white;'>Available</span>"]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode(['status' => 'error',
'html' => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"]);
}
}
?>

$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html !== "") {
$("#btn-signu").attr("disabled", true);
}
else {
$("#btn-signu").removeAttr("disabled");
}
$("#disp").html(html);
}
});
Check the html param in success callback function.

In form.php change Javascript to:
<script type="text/javascript">
$(document).ready(function(){
//get the button by its ID
var $button = $('#btn-signup');
$("#sitename").keyup(function() {
//hide the button always
$button.hide();
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
if(!html.length){
//show the submit button if no error html
$button.show();
}
}
});
return false;
}
});
});
</script>
The Button should be initial hidden. If the field can be prefilled, you need to check if the value is not empty before hiding the button.
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none">Submit</button>
</div>

Related

Mailchimp Wordpress Plugin

I have built this Mailchimp Newsletter sign up plugin. PHP its not my strength so I am not being able to fix the error it has.
I used This Mailchimp wrapper: https://github.com/drewm/mailchimp-api.
My PHP file is:
<?php
include('MailChimp.php'); // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;
function sm_mailchimp_subscribe()
{
// Settings:
$mcAPIKey = '70000000000000000007e-us00';
$mcListID = '323231214212';
$status = 'subscribed';
// Settings End
$MailChimp = new MailChimp($mcAPIKey);
$email = $_POST['email'];
$fname = $_POST['fname'];
$sname = $_POST['sname'];
$merge_vars = array(
'FNAME' => $fname,
'LNAME' => $sname
);
if (isset($email) and isset($fname) and isset($sname)) {
$result = $MailChimp->post("lists/" . $mcListID . "/members", [
'email_address' => $email,
'merge_fields' => $merge_vars,
'status' => $status,
]);
return json_encode($result);
}
}
if ($_POST['ajax']) {
echo sm_mailchimp_subscribe();
} elseif ($_POST['action'] == 'setCookies') {
echo setCookiesTemp();
}
function setCookiesTemp()
{
setcookie('sm_mailchimp-temp', true, time() + (86400 * 28), '/');
}
function setCookiesPerm()
{
setcookie('sm_mailchimp-perm', true, time() + (86400 * 28 * 24), '/');
}
And here is the JS:
jQuery(function($) {
// From wp_localized
const ajaxURL = ajax_obj.ajax_url;
$(document).ready(function() {
var body = $("body");
var modal = `<div class="sm_mailchimp-modal">
<div class="sm_mailchimp-box">
<button class="sm_mailchimp-close">X</button>
<h3>Join Our Mailing List</h3>
<form name="sm_mailchimp-form" method="post" class="sm_mailchimp-form light">
<p>Subscribe to our newsletter and receive tips for a successful business.</p>
<input type="email" name="email" placeholder="Type Your Email" class="sm_sname">
<div class="sm_mailchimp-message"></div>
<button type="submit">SIGN UP</button>
</form>
</div>
</div>`;
if (!document.cookie.includes("sm_mailchimp-temp=1")) {
$(modal)
.hide()
.appendTo(body);
setTimeout(function() {
$(".sm_mailchimp-modal").fadeIn();
}, 5000);
}
$(".sm_mailchimp-close").click(function() {
closeModal();
});
$(".sm_mailchimp-modal").click(function(e) {
if (e.target == this) {
closeModal();
}
});
function closeModal() {
$(".sm_mailchimp-modal").fadeOut();
$.ajax({
url: ajaxURL,
method: "POST",
data: { action: "setCookies" },
success: function(data) {
console.log("Cookie added as sm_mailchimp-temp=1");
}
});
}
$(".sm_mailchimp-form").submit(function() {
var emailVal, fnameVal, snameVal;
emailVal = $(".sm_email", this).val();
fnameVal = $(".sm_fname", this).val();
snameVal = $(".sm_sname", this).val();
if (emailVal === "" || fnameVal === "" || snameVal === "") {
$(".sm_mailchimp-message").html("Please fill out all the fields!");
return false;
} else {
$(".sm_mailchimp-message").html("Adding your email address...");
var form = $(this);
$.ajax({
url: ajaxURL,
type: "POST",
data: form.serialize() + "&ajax=true",
success: function(msg) {
var message = $.parseJSON(msg),
result = "";
if (message.status === "pending") {
result =
"Success! Please click the confirmation link that will be emailed to you shortly.";
} else if (message.status === "subscribed") {
result =
"Success! You have been subscribed to our mailing list.";
} else {
result = "Oops: " + message.title;
console.log("Error: ", message);
}
$(".sm_mailchimp-message").html(result);
}
});
return false;
}
});
});
});
The error is the following:
Once the Sign Up button is clicked the message "Adding your email address..." shows as it should but then it freezes there. The console shows the following error:
Weirdly, it used to work fine. And without a change it stopped. I built it a couple of months ago.
UPDATE
The error is actually coming from the success: function(msg) { line. The msg is empty. So, when it gets to message.status it cannot read the property of status null.
Question: Why is the success callback returning msg empty?

Ajax post with php-mysql is not working properly

I need a ajax call to post data to the database and fetch the data from database and update in live. I have the following codes
HTML Form
<div class="hover_bkgr_fricc">
<span class="helper"></span>
<div>
<div class="popupCloseButton">×</div>
<p>
<form>
<input type="hidden" name="check_num" value="123" />
<p>Please provide more details</p>
<input type="text" name="reason" />
<a id="submit">Mark Reviewed</a>
</form>
</p>
</div>
</div>
<b id="review_result"></b>
<a class="trigger_popup_fricc">
<button> Mark Reviewed</button>
</a>
Javascript Block
$(document).ready(function() {
$(".trigger_popup_fricc").click(function() {
$('.hover_bkgr_fricc').show();
});
$('.popupCloseButton').click(function() {
$('.hover_bkgr_fricc').hide();
});
$('#submit').click(function() {
var check_num = $('input[name=check_num]').val();
var reason = $('input[name=reason]').val();
var form_data =
'check_num=' + check_num +
'&reason=' + reason;
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(html) {
//if process.php returned 1/true (send mail success)
if (html == 1) {
//hide the form
$('.hover_bkgr_fricc').fadeOut('slow');
$('#review_result').html(data);
} else alert('Sorry, unexpected error. Please try again later.');
}
});
});
And the php block
$link = mysqli_connect($HOST, $USER, $PWD, $DB_NAME);
$check_num = $_POST['check_num'];
$reason = mysqli_real_escape_string($link, $_POST['reason']);
$insert = mysqli_query($link, "INSERT INTO `vloer_paylink_reason` (`id`, `check_number`, `reason`) VALUES (DEFAULT, '$check_num', '$reason')");
$update = mysqli_query($link, "UPDATE vloer_paylink SET reviewed = 1 WHERE check_number ='$check_num'");
$get_check_data = mysqli_query($link, "SELECT reviewed FROM vloer_paylink WHERE check_number = '$check_num'");
$check_data = mysqli_fetch_array($get_check_data);
if($check_data['reviewed']==1){
echo "Reviewed done";
}
else {
echo "Not Reviewed done";
}
Data is inserting and updating to the database but after that not returning to html update. Its returning false (Sorry, unexpected error. Please try again later.)
Add .error : function(e){ console.log(e)} to your ajax call, to return the error.
The function will be:
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(data) {
if(data == "Reviewed done"){
// code goes here
}
},
error : function(e) { console.log(e)} // this will print error
});
You are sending Reviewed done or Not Reviewed done in the php code as a response. Change the javascript code like below.
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(response) {
//if process.php returned 1/true (send mail success)
if (response === "Reviewed done") {
//hide the form
$(".hover_bkgr_fricc").fadeOut("slow");
$("#review_result").html(response);
} else alert("Sorry, unexpected error. Please try again later.");
},
error: function(error) {
console.log(e);
} // To catch any network errors
});

jQuery call with ajax not responding, no error

I have a small problem with a giftlist generated from SQL. My goal is to echo each row as a form with a textbox and a button, then when any button clicked, pass the textbox value, and an id number (hidden field value) to a function. Then this function would have get the values, and sends them with AJAX get method to a php, which would update a row with the giver's name in the SQL database. I cannot find the error in my code, so please help me in this regard.
EDIT: i need to figure out too, how to identify the button which was clicked.
This would be my script:
<script type="text/javascript">
var aname = '';
var tid = 0;
$('.giftok').click(function()
{
if ($('.aname').val() === '')
{
alert('You have not provided your name.');
}
else
{
aname = $('.aname').val();
tid = $('.id').val();
$.ajax
({
url: "kosarba.php",
data: { ganame: aname, tid: gtid },
type: "GET",
context: document.body
}).done(function() {
alert("OK, it works.");
});
alert('Thank you!');
}
});
</script>
Here is my HTML+PHP:
echo "<table id='giftlist' align='center' font-size='10pt'>";
while($sor=mysql_fetch_array($sordb))
{
echo "<tr>
<td width='420px'>$sor[gname]</td>
<td width='65px'>$sor[gprice] Ft</td>";
if (strlen($sor[aname]) !== 0)
{
echo "<td width='200px'>Sorry, someone already bought this one for us.</td>";
}
else
{
echo "<td width='335px'><form id='rendelget'>Your name: <input type='textbox' id='aname' name='aname' value='$aname'/><input type='hidden' class='id' name='id' value='$sor[id]'/> <button type='button' id='$sor[id]' class='giftok' value='Megveszem'>Megveszem</button></form> </td>";
}
echo "</tr>";
}
echo "</table>";
You have mistaken a variable name tid = $('.id').val() tid
should be gtid
I think that would be your script
$(document).ready(function(){
var aname = '';
var tid = 0;
$('.giftok').click(function()
{
if($(this).closest('form').attr('name') == 'myId'){ //or id
if ($('.aname').val() === '')
{
alert('You have not provided your name.');
}
else
{
aname = $('.aname').val();
gtid = $('.id').val();
$.ajax
({
url: "kosarba.php",
data: { ganame: aname, tid: gtid },
type: "GET",
context: document.body
})
.error(function(){
alert('Ajax worked but error form server.');
})
.done(function() {
alert("OK, it works.");
});
alert('Thank you!');
}
}
});
})
//Update: If you identify the form holding the button gitve the form a name or id
Inside the ajax call,
data: { ganame: aname, tid: gtid }
'tid' is the post parameter, while gtid is the javascript variable.
Mistakenly, you have used gtid instead of tid .
use :
data: { ganame: aname, tid: tid }

form field is not stored in mysql database

I have created a simple form consisting of a textarea field, so when user clicks on submit button its linked to a jquery script containing a url executing the process and store the data, but problem is every time i hit submit, ID & created_at data is stored but the data given on textarea is ignored and not stored, never faced this problem before..please help me out!
HTML
<form id="form" name="form" method="POST" action="profile_1.php" class="wizard-big" autocomplete="off" enctype="multipart/form-data" required="">
<div class="form-group col-sm-12">
<textarea type="text" name="status" id="status" placeholder="What's on your mind.." class="form-control" style="height:100px;"></textarea>
</div>
<div class="col-sm-12 form-group">
<input style="width:100%" type="submit" name="submit" id="submit" value="Post" class="btn btn-success">
</div>
</form>
Jquery
$(document).ready(function() {
$("#submit").click(function(e) {
var status = $('form')[0].checkValidity();
if (status) {
var formData = new FormData($('form')[0]);
$.ajax({
url: "form_post.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json) {
if (json.error) {
alert(json.error_msg);
e.preventDefault();
} else {
alert("Post updated successfully!");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
});
php
<?php
session_start();
define('HOST','localhost');
define('USER','**');
define('PASS','**');
define('DB','**');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
/*foreach($_POST as $value){
if(empty($value)){
$error_flag = true;
break;
}
}*/
if(!$error_flag){
//receiving post parameters
$status =$_POST['status'];
// create a new user profile
$sql = "INSERT INTO status (via, status, created_at) VALUES ('".$_SESSION['vault_no']."', '$status', NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
$response['via'] = $via;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
Note: The solution is in the comments for other readers of this question
Maybe this helps you out. You need to change it to your wish offcourse
And save this function, it could be usefull for you in the future.
This function serializes the form as how it should be done.
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var formData = $('form').serializeObject();
$.ajax({
data: formData,
type: 'POST',
url: 'form_post.php',
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
return false;
});
});
</script>

Call php script with php variables via JavaScript

I have a url that I can call with a userid, and it will update an SQL table. (e.g. domain.com/postback.php?userid=userid). That works fine manually, but not when trying to get JavaScript to call it. I've only just started learning JavaScript as of 3 days ago, so please forgive me if it's an easy one - but I can't see it.
I call the JS in question here:
<input type='button' id='countdw' value='Wait 30s' class='btn btngo disabled'>
<script>
var secsLeft = 30;
setInterval(function(){
secsLeft--;
if(secsLeft > 0){
$('#countdw').val('Wait ' + secsLeft + 's');
} else if(secsLeft == 0){
$('#countdw').removeClass('disabled');
$('#countdw').val('Go');
$('#countdw').attr("onclick","doSomething2()");
}
}, 1000);
Here is my JS. I've tried many different ways and this is just one of them.
<script type="text/javascript">
$(document).ready(function(){
function doSomething2(){
$.ajax
{ url: 'update.php',
data: { userid : userid },
type : 'GET',
dataType: 'json',
success : function ( jsXHR) {
},
failed : function(status,data){ }
}
);
}
});
</script>
<?php
$subid = $_GET['userid'];
?>
Here is the update.php script (I'm aware it's not mySql - yes I need a new book.) I just can't get the JS above to call it.
$uped = 1;
$subid = $_REQUEST['userid'];
mysql_query("UPDATE ".MYSQLTABLE." SET view=view+".$uped." WHERE userid='".$subid."'") or die(mysql_error());
mysql_close();
?>
This seems to be working for me.
function count() {
window.secsLeft--;
if (window.secsLeft > 0) {
$('#countdw').val('Wait ' + window.secsLeft + 's');
} else if (window.secsLeft === 0) {
$('#countdw').removeClass('disabled');
$('#countdw').val('Go');
$('#countdw').attr("onclick", "doSomething2()");
}
}
function doSomething2() {
$.ajax({
url: 'update.php',
data: {
userid: <?php echo $userid; ?>
},
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
(function () {
"use strict";
window.secsLeft = 30;
setInterval('count()', 1000);
}());
<input type="button" id="countdw" value='Wait 30s' class="btn btngo disabled">

Categories