Javascript doesn't allow '#' sign - javascript

I have an issue with changing the mail address by using AJAX. Somehow when I enter an email address it doesn't see the change but it should. It's a place to change mail address. Can you check it?
PHP
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="icon-email-icon tooltip mrgn-bot">Email</div>
<input type="text" value="<?php echo $update_['email'];?>"
class="profile-textbox pull-right"
onchange="saveToDatabase(this.value,'email','<?php echo $getID; ?>');">
</div>
JS
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(../img/loaderIcon.gif) no-repeat right");
var result = window.confirm("Are you sure?");
if(result == true) {
var str = 'column='+column+'&editval='+editableObj+'&id='+id;
$.ajax({
url: "saveedit.php",
type: "POST",
data: str,
success: function(data){
$(editableObj).css("background","#FDFDFD");
alert("Your Information was successfully changed.");
}
});
}
else
return 0;
}

Related

How to disable submit button until validation passed in specific field

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>

Login on same page, check SESSION without reload

I currently have a form at the top of every page on my website that lets the user input the username and password to login.
but Once the button is clicked, I use JQuery AJAX method to submit it to login.php without page refresh where it validates credentials and returns users whether the username / password submitted was valid or invalid.
Finally, the result is returned back to the page the user tried to login on.
I would also like the page to after once there is a successful login, the form disappears and is replaced with "Welcome back, USER!"
Everything works except for I want this to happen without a page reload. Here is what I have so far:-
Display form if session is not set, otherwise say Welcome back, user:-
<div class="user">
<?php
if (isset($_SESSION['logged_user'])) {
$logged_user = $_SESSION['logged_user'];
print("<p>Welcome back, $logged_user!</p>");
}
else {
print('<div class="forms">
<form id="login">
<label>Username <input type="text" name="username" id="username"></label>
<label>Password <input type="text" name="password" id="password"></label>
<input type="submit" class="submit" value="Login" id="login">
<span class="error"></span>
</form>
</div>');
}
?>
</div>
Javascript / AJAX to handle submission:
$(document).ready(function() {
$("#login").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+'&password='+password;
if(username != '' && password != '') {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
success: function(responseText) {
if(responseText == 0) {
$("error").html("Invalid login.");
}
else if(responseText == 1) {
window.location = 'index.php';
}
else {
alert('Error');
}
}
});
}
return false;
});
And my login.php does everything fine.
Right now, the only way for my page to update to show the Welcome back message is if I include the line: window.location = 'index.php'; so that the page reloads. But without this, the user will have logged in successfully but will not be able to see this.
Is there a way to do this without AngularJS? This is for a class and we are not allowed to use frameworks, which has been quite frustrating! Thanks!
You can use Dynamic HTML (DHTML).
The success function you don't redirect instead using jquery to change the content.
Something like this:
success: function(responseText) {
if(responseText == 0) {
alert('Invalid login');
}
else if(responseText == 1) {
// Success
$('#login').parent().append('<p>Welcome back, '+username+'!</p>');
$('#login').remove();
}
else {
alert('Another Invalid login');
}
}
The API Login return:
0 if invalid
1 if valid
use this code,
<div class="user">
<div class="after_login" style="display:none">
<?php
$logged_user = $_SESSION['logged_user'];
print("<p>Welcome back, $logged_user!</p>");?>
</div>
<div class = "before_login">
print('<div class="forms">
<form id="login">
<label>Username <input type="text" name="username" id="username"></label>
<label>Password <input type="text" name="password" id="password"></label>
<input type="submit" class="submit" value="Login" id="login">
<span class="error"></span>
</form>
</div>');
?>
</div>
</div>
in script use like this instead of:
window.location = 'index.php';
use below lines,
$('.after_login').show();
$('.before_login').hide();
You have to change some modification in your javascript code as below :
$(document).ready(function() {
$("#login").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+'&password='+password;
if(username != '' && password != '') {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
dataType: "json",
success: function(responseText) {
if(responseText.status == 'invalid') {
$(".error").html("Invalid login.");
}
else if(responseText.status == 'valid') {
$('.after_login').html('Welcome back,'+responseText.username);
$('.after_login').show();
$('.before_login').hide();
}
else {
alert('Error');
}
}
});
}
return false;
});
In above example, I have added one extra line dataType: "json", So now you have need to send output in json format from your login.php and also some modification done in success.
$response = array();
// $result variable get result from your database
if(count($result) == 0)
{
$response['status'] = 'invalid';
}else{
$response['status'] = 'valid';
$response['username'] = $result['username'];
}
echo json_encode($response);
exit;
So your success become like that below
success: function(responseText) {
if(responseText.status == 'invalid') {
$(".error").html("Invalid login.");
}
else if(responseText.status == 'valid') {
$('.after_login').html('Welcome back,'+responseText.username);
$('.after_login').show();
$('.before_login').hide();
}
else {
alert('Error');
}
In your login.php, change success condition to output username instead of 1. So responseText will have the username on ajax callback.
Remove the final else condition in your ajax success, and do something like this in the success condition
$('.forms').html('<p>Welcome back, ' + responseText + '!</p>');
PHP:
if (isset($_SESSION['logged_user'])) {
$logged_user = $_SESSION['logged_user'];
//Leave out the print(Welcome...) part, it won't do anything because the page won't be refreshed.
}
else{
exit('1');
}
In the Ajax, don't worry about responseText == 0, just stick with ==1:
success: function(responseText) {
if(responseText == "1") {
alert("Nope");
}
else {
$("#successdiv").html("welcome...");
}

Login form using PHP and AJAX

I am simply trying to log in on a popup log in box. I used AJAX to check whether log in is successful or not. If it is successful move to header location otherwise Give an error.
Code look like this:
<script>
$(document).ready(function () {
$('#login').click(function () {
var email = $("#email").val();
var pass = $("#pass").val();
var dataString = 'email=' + email + '&pass=' + pass;
if ($.trim(email).length > 0 && $.trim(pass).length > 0) {
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: dataString,
cache: false,
success: function (data) {
if (data) {
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "index.php";
}
else {
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
Form:
<div class="user_login">
<form action="" method="post">
<label>Email / Username</label>
<input type="email" Placeholder="Email-id" name="email" Required="required" id="email"/>
<br />
<label>Password</label>
<input type="password" Placeholder="Password" name="pass" Required="required" id="pass"/>
<br />
<div class="checkbox">
<input id="remember" type="checkbox" />
<label for="remember">Remember me on this computer</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div class="xyx"><input type="submit" value="Login" name="submitm" id="login"/></div>
<div id="error"></div>
</div>
</form>
Forgot password?
</div>
and php file is separate named as ajaxlogin.php:
include('includes/db.php');
if (isset($_POST['email']) && isset($_POST['pass'])) {
$pass = $_POST['pass'];
$email = $_POST['email'];
$query = "SELECT * FROM login WHERE email='$email' AND BINARY pass=BINARY '$pass'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$_SESSION['user'] = $email;
}
}
Both Script and form are on same page. Output that i am currently getting is Error message Both for right and wrong Username/Password Match. But if i delete "return false;" from script it moves to header location without log in.
try this script,
$(document).ready(function()
{
$('#login').click(function()
{
var email = $("#email").val();
var pass = $("#pass").val();
if ($.trim(email).length > 0 && $.trim(pass).length > 0)
{
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: {email:email,pass:pass},
cache: false,
success: function(data) {
if (data)
{
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
window.location.href = "index.php";
}
else
{
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
Looks like you are not returning any data from ajaxlogin.php
so the success function always takes control to else and throws you an error message on the screen.

How to display error messages Jquery ajax?

I am a student and am using jquery and php to add records to database. Records are being added, but i want to display a message "Record inserted" in the if the the record has been successfully been added and an error message if an error occurs.
This is my html code:
<form id="forn-newsletter" class="form-horizontal" method="POST">
<div class="form-group">
<label id="name_label" class="control-label col-xs-2">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_name" name="news_name" placeholder="Name" onblur="checkName();"/><font color="red" id="name_error"></font>
</div>
</div>
<div class="form-group">
<label id="email_label" class="control-label col-xs-2">Email</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_email" name="news_email" placeholder="Email" onblur="vali()"/><font color="red" id="email_error"></font>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<button id="register-newsletter" type="submit" class="btn btn-primary">Register for Newsletter</button>
</div>
</div>
<div id="dialog"></div>
</form>
This is my registration-newsletter.php
<?php
include('connect.php');
$name=$_POST['name'];
$email=$_POST['email'];
$val=md5($name.$email);
$query = "INSERT INTO newsletter (Id,Name,Email,Val) VALUES('','$name','$email','$val')";
$result=mysql_query($query);
if(!$result){
echo "Some error Occured..Please try later";
}
else{
echo "Your details have been saved. Thank You ";
}
mysql_close($con);
?>
This is my JQuery code
$(document).ready(function(){
$("#register-newsletter").click(function(){
var name=$("#news_name").val();
var email=$("#news_email").val();
var dataString="name="+name+"&email="+email;
var request;
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString
});
//return false;
});
});
Add a span to your html code for displaying error.
<span id="error"></span>
Already you are echoing the message from PHP page to ajax. You can do mysql_affected_rows() to check whether the query updated the table.
$result=mysql_query($query);
if(mysql_affected_rows()>0){ // return the number of records that are inserted
echo "Your details have been saved. Thank You "; // success
}
else{
echo "Some error Occured..Please try later"; // failure
}
exit;
Then you can simply show the echoed message in the span with id error as:
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString,
success:function(response) // response from requested PHP page
{
$('#error').html(response); // set the message as html of span
}
});
$.ajax({
url: 'registration-newsletter.php',
type: 'post',
data: dataString ,
success: function (msg) {
alert(msg);
},
error:function(msg)
{
alert(msg);
}
});
jQuery.ajax({
url: "myfile.php",
type: "POST",
data: dataString,
success:function(response) /* this response is an array which is returning from the myfile.php */
{
$status = response['status'];
if($status == 'success')
{
$('#message').html(response['msg']);
}
else
{
$('#message').html(response['msg']);
}
}
});
The function which you have added success will handle the "text to be append" or "alert to be show". Its quite equal to if condition, If the response came successfully, It will go into the condition.
This is what worked for me for form submit (see those 2 parameters to .then function):
<span id="result">Loading...</span>
<div id="form">
<form>
<input id="personId"> <-- put personID here<br>
<input id="submit" type="submit" value="Generate">
</form>
</div>
<script type="application/javascript">
$(document).ready(function() {
var submit = $('#submit');
var res = $('#result');
$('#form').submit(function() {
submit.prop('disabled', true);
res.text("Sending message...");
$.ajax({
url: '/rest/message',
contentType: "application/json;charset=UTF-8",
method: "POST",
data: JSON.stringify({'personId': $('#personId').val()})
}).then(function(result) { // OK
res.text("Message was generated");
submit.prop('disabled', false);
}, function(reason) { // ERROR
res.css('color', 'red').css('font-weight','Bold');
res.text("An error has occurred: " + reason.responseJSON.message);
submit.prop('disabled', false);
});
return false; // prevent default action
});
});
</script>
error: function(xhr) {
alert(xhr.responseText);
}
You can also get the HTTP status code or the generic message sent by your server (such as "Internal Server Error") in this XHR object if needed. More info : https://api.jquery.com/jQuery.ajax/#jqXHR

success or error message input javascript bootstrap

Is there a way to change my input in order to display a succes or error icon at the input? like : http://getbootstrap.com/css/#forms-control-validation
Much appreciated.
and here's my code :
<script>
$(document).ready(function () {
$('input[name=subdomain]').keyup(subdomain_check);
});
function subdomain_check() {
var subdomain = $('input[name=subdomain]').val();
if (subdomain == "") {
$('input[name=subdomain]');
} else {
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain=' + subdomain,
cache: false,
success: function (response) {
if (response == 1) {
$('input[name=subdomain]').html("The URL already exist!");
} else {
$('input[name=subdomain]').html("The URL is Valid!");
}
}
});
}
}
</script>
The HTML code :
<div class="form-group">
<label class="control-label col-md-3" for="install-element-6">
<span class="required">* </span>subdomain</label>
<div class="col-md-6"> //<----- I want it here
<input type="text" class="form-control input-md col-md-6" name="subdomain" placeholder required id="install-element-6"/> // the method.addClass add it here
</div>
</div>
Much appreciated.
It worked now and all by adding the method parent() to get the element div instead of input
if(response == 1){
$('input[name=subdomain]').parent().removeClass("has-success");
$('input[name=subdomain]').parent().addClass("has-error");
}else{
$('input[name=subdomain]').parent().removeClass("has-error");
$('input[name=subdomain]').parent().addClass("has-success");
}

Categories