How to check if username exists without refreshing page using wordpress - javascript

I want to check a text field in form that if username exists in database or not.i want it without refreshing page and i am using Wordpress.I know it is possible through ajax but i have tried ajax in Wordpress and any ajax code didn't run on it. Kindly provide any piece of code or any helpful link. Last time i have tried this but didn't work:
<?php
if(!empty($user_name)){
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}?>
<label for="user_name" id="user_name">Username: </label>
<input type="text" name="user_name" id="user_name" required/>
<span id="user-result" ></span>
<script type="text/javascript">
jQuery("#user_name").keyup(function (e) { //user types username on inputfiled
var user_name = jQuery(this).val(); //get the string typed by user
jQuery.post('teacher_form.php', {'user_name':user_name}, function(data) {
jQuery("#user-result").html(data); //dump the data received from PHP page
});
});
</script>

use
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
to be
<?php
if(!empty($_POST['user_name']){
$user_name = $_POST['user_name'];
$usernamecheck = $wpdb->get_results("select id from wp_teacher_info where user_name='$user_name'");
if(!empty($usernamecheck)){
echo'username not available';
}
else {
}
}
?>
but keyup event will call the ajax each keyup .. you can use **.blur()** instead of **.keyup()**

Related

Email not storing in variable from ajax request

I'm attempting to use ajax to send input from an html form and try to fine the email in a MySQL database. I tested the search and it works just fine (using dummy data.) I have my PHP files running on WAMP. I checked Chrome to see if the email/password are showing and they are.
Here is my code:
HTML & Ajax
<html>
<head>
<!--initialize jquery from js folder-->
<script src ="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<!--output of the json-->
<div>
<!--set the id to DOM to show output-->
<ul id="DOM">
</ul>
</div>
<form>
<label><b>Email</b></label>
<input type="text" placeholder="Enter email" id="email"
required>
<br/>
<label><b>Password</b></label>
<input type="text" placeholder="Enter password" id="passwrd"
required>
<br/>
<button type="button" id="submit">Login</button>
</form>
insert
delete
show data
login
<!--Implementation of jquery/ajax-->
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
var data = {
email: $("#email").val(),
passwrd: $("#passwrd").val()
}
$.ajax({
url : "http://localhost/api/login.php",
type : "POST",
dataType : "json",
data : JSON.stringify(data),
//on success it will call this function
success : function(data){
alert(data.toString());
//if fail it will give this error
}, error : function(e){
alert("failed to work:" +JSON.stringify(e));
}
});
});
</script>
</body>
</html>
PHP
include "db.php";
header('Content-type: application/json');
//$con->escape_string
$email = isset($_POST['email']);
//$email = "fk5829#wayne.edu";
$result = $con->query("SELECT * FROM users WHERE email='$email'");
echo "$email";
if($result->num_rows == 0){ //if the user doesnt exist
$_SESSION['message'] = "user doesnt exist";
echo ' / user not exist / ';
}
else{ //user exists
$user = $result->fetch_assoc();
if(password_verify(isset($_POST['passwrd']), $user['passwrd'])){
//Verify the password entered
//if password correct, link information from DB to session
//variables
$_SESSION['f_name']= $user['f_name'];
$_SESSION['l_name']= $user['l_name'];
$_SESSION['email']= $user['email'];
$_SESSION['authorized']= $user['authorized'];
//Will be used to check if users session is logged
//in/allowed to do things
$_SESSION['logged_in'] = true;
//return to Success
return $_SESSION['logged_in'];
exit("Success");
}
else{
$_SESSION['message'] = "You have entered the wrong password,
please try again";
}
echo ' / user exists / ';
}
echo ' / After the check / ';
My question is this: Why is the email from the form id "email" not getting stored in $email? is it on my ajax request side? or is it in my PHP file when im trying to $_POST?
Any direction is appreciated.
I tried this function and got it to work. Maybe you can try this too.
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
$.post('http://localhost/api/login.php', {email:$("#email").val(),passwrd:$("#passwrd").val()},
function(data){
alert(data.toString());
}).fail(function(e){
alert("failed to work:" +JSON.stringify(e));
});
});
</script>

Table form dynamically refresh with php and ajax

I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>
change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});
If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.

php function to display which field is not filled in

I have a simple JavaScript function that will not allow a form to be submitted if all the fields are not filled out. On top of that I would like PHP to write out an error message next to just the fields that are empty. The problem is the function activates upon the $_POST and yet my JavaScript function will not allow for $_POST to occur as long as one of the fields are empty.
If I keep the action outside of the $_POST condition then the page will load with the error message already showing. I am fairly new to PHP and JavaScript and would like any insight on perhaps another available condition that I could use to trigger my error messages to appear in my form. I am also open to any other suggestions for error handling. I do prefer to keep my JavaScript present due to it's ability to keep the form from being submitted if it is not properly filled. Unless there is another way to take that action then I have to keep the JavaScript.
PHP:
function cleanCrew ($id, $pswrd) {
$id = stripslashes($id);
$pswrd = stripslashes($pswrd);
$id = strip_tags($id);
$pswrd = strip_tags($pswrd);
return array($id, $pswrd);
}
require_once 'dbServ.php';
$db_server = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
if ($db_server) {
$error_1 = "";
} else{
$error_1 = "connection to database unsuccessful";
}
$error_2 = "";
$error_3 = "";
if ($_POST) {
$user_id = mysqli_real_escape_string($db_server, $_POST['userId']);
$user_pass = mysqli_real_escape_string($db_server, $_POST['pass']);
$id_and_pass = cleanCrew($user_id, $user_pass);
if ($user_id == "" || $user_id == null) {
$error_2 = "please fill in proper User Id";
} else{
$error_2 = " ";
}
if($user_pass == "" || $user_pass == null){
$error_3 = "please fill out password";
} else{
$error_3 = " ";
}
echo $id_and_pass[0];
echo $id_and_pass[1];
}
HTML:
<div id="intro">
<h1 id="the_blog" align="center">The <span id="blog_animate" style="position:relative;">Blog</span></h1>
<div id="log-in"><p id="log">Log In</p><br> <?php echo $error_1; ?>
<form action="blog.php" method="post" onsubmit="return checkForm(this)" name="form1">
<p id="log">User ID :</p> <input type="text" placeholder="johnnyApple175" name="userId"></input><?php echo $error_2 ?><br>
<p id="log">Password:</p> <input type="password" name="pass"></input><?php echo $error_3; ?><br>
<input type="submit" value="submit" class="button" ></input>
</form>
First:
It's always a very good idea to validate the data server side, like you're doing.
Reason is simple: Javascript is client-side and can easily be modified to e.g. bypass those checks. Also, good that you escaped the sent data prior using it in the Database query.
Your problem is, that you're checking for $_POST to exist - it always exists, it's a super global var. You actually want to check if it's empty:
if (!empty($_POST))...
You might want to think over it, if you really want to give detailed information what exactly was wrong. Giving more info is more user friendly, but it makes attacks easier, especially if you don't block the user after X retries.

validate captcha before submit

I've use captcha for form registration, within that I have validation engine for form inline validation. I'm stuck in validating the equity of captcha.
<p class="veriText">
<label>Enter the Verification Text </label> <span style="color:red;">*</span>
<input class="validate[required] text-input" type="text" name="captcha" id="captcha" class="text" value="" />
</p>
<img src="<?= get_bloginfo('template_url'); ?>/captcha_code_file.php?rand=<?php echo rand();?>" id='captchaimg'><br/>
PHP validation: (works perfectly)
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
}
But the same thing in js I have tried like
var session = <?php echo $_SESSION['code'] ?>; // this value is different
// from captcha image
Is it possible to validate captcha before submitting the form in Javascript/jQuery?
Assuming the line var session = <?php echo $_SESSION['code'] ?>; is in your html page.
When the page is generated your captcha image script is not invoked and thus $_SESSION['code'] is not initialized. The value you are getting is the code from the previous request to captcha_code_file.php. Once your page is loaded (at-least the html part) and the browser decides to call captcha_code_file.php your captcha image gets invoked and a new $_SESSION['code'] is created.
I don't recommend this, but if you want to get the current $_SESSION['code'] try to use an Ajax request to retrieve the new $_SESSION['code'] from another php file (don't call captcha_code_file.php or your session will be reset again.
Note: Never try to validate your captcha at user end. You are defeating the main purpose of captcha.
Create one ajax request for checking capcha using JavaScript, example is provided below:
var postData = $("form").serialize();
var requestUrl = '/check_capcha.php';
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: requestUrl,
success:function(data){
// success or fail message
}
});
check_capcha.php contains:
if(strcasecmp($_SESSION['code'], $_POST['captcha']) != 0){
//----mismatch values
echo 0;
}else{
echo 1;
}
exit;
You can put the javascript code before (although session is same throughout the page).
Just try a dummy code in a plain file and check the session value
OR
You can use $.ajax() to call PHP page for captcha validation
html look like this
$rand = mt_rand(100000,999999);
<span class="captcha"><?php echo $rand; ?></span>
<input name="captcha" type="text" id="captcha-compare" />
In javascript use something like that for validation engine
$('#frm-register').submit(function() {
if( $('#captcha-compare').val() != $('.captcha').text() ) {
$('#captcha-compare').validationEngine('showPrompt', 'Invalid captcha', 'load');
return false;
}
});
and in php first take $rand in session then submitting capture the input text captcha and session
You can try the below code to validate the captcha or you can also use AJAX code to validate the values before submitting the code.
<script language="JavaScript">
var session = '<?php echo $_SESSION['code'] ?>';
if(Form.captcha.value == session)
{
return true;
}
else
{
Form.submit();
}
</script>

Search button not working in instant search with jQuery

I have tried instant search using jQuery. It is working fine until I click the search button. When I click the search button the page will reload and the results would disappear.
Here's my code:
search.php
<div id="search-container">
<form action="search.php" method="POST">
<input type="text" name="key" id="key" placeholder="search" onkeydown="searchIt();"></input>
<input type="submit" name="search" id="search" value="search"></input>
</form>
</div>
<div id="res-container"></div>
And the script is:
<script type="text/javascript">
function searchIt(){
var text = $("input[name='key']").val();
text = text.trim();
if(text.length>3){
$.post("query.php",{index: text}, function(data){
$("#res-container").html(data);
});
}
}
</script>
query.php
if(isset($_POST['index'])){
$key = mysqli_real_escape_string($con, $_POST['index']);
$key = trim($key);
$result = "";
if(!empty($key)){
$query = "SELECT * FROM users WHERE first_name LIKE '%$key%' OR last_name LIKE '%$key%'";
$query_run = mysqli_query($con, $query);
$row_count = mysqli_num_rows($query_run);
if($row_count == 0){
$result = "No results!!!";
}else{
while($query_row = mysqli_fetch_array($query_run)){
$fname = $query_row['first_name'];
$lname = $query_row['last_name'];
$name = $fname.' '.$lname;
$mail = $query_row['email_id'];
$id = $query_row['emp_id'];
$result .="<div class=\"qitems\"><div class=\"name\">$name</div><div class=\"mail\">$mail</div></div>";
}
}
}else{
$result = 'please enter a word';
}
}
echo ($result);
Until this everthing is working fine, but when I try to click search button the results would disappear.
I tried adding this in the script:
$(document).ready(function(){
$("input[name='search']").click(searchIt());
});
But there is no change. Please help me with this.
This should work:
$(document).ready(function(){
$('body').on('click', 'input[name="search"]', function(event)
{
event.preventDefault(); // This is important, since you are interacting with a valid html form/element
searchIt();
});
});
Update:
I've made a codepen for you. Look at it, it works perfectly fine:
http://codepen.io/dschu/pen/VmRJPZ
The reason is button of type "submit" effectively submits the page to form URL, which is the same page, thus has the same effect, as reloading, - here is your "reset" behaviour. Besides solution above you can also change input type from submit to button, which will avoid submitting the form (and manually preventing the event).

Categories