i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.
Related
I'm working on a webpage in which, when the user checks a checkbox, calling a PHP function to query the table if the user exists. If so, it then displays the button to go to next page.
So far I've tried this. I am sure that my php is working fine I checked my result variable returns 0 when user exists, but for some reason it is not executing the if statement.
$(document).ready(function() {
$('#submit').hide();
$('#mobiletask').change(function(){
if($('#mobiletask').attr('checked'))
{
check_availability();
// $( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
});
//function to check username availability
function check_availability(){
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == 0) {
//show that the username is NOT available
$('#submit').show();
}
});
}
checkusername.php
$username = mysql_real_escape_string($_POST['username']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('select studentId from smartphone_scores where studentId = "'. $username .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
Based on the response you are getting:
<html><body>1</body></html>
What you have to do is to work on your PHP file and make sure to remove any HTML in it.
Try this:
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == '1'){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == '0') {
//show that the username is NOT available
$('#submit').show();
}
});
$(document).ready(function()
{
$('#submit').hide();
$('#mobiletask').on('change',function() {
if($('#mobiletask').attr('checked'))
{
check_availability();
//$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
function check_availability()
{
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.ajax({
url: 'check_username.php',
type: 'POST',
async: false,
data: {'name':'username','value':username},
success: function(result)
{
alert(result);
//if the result is 1
if(result == '1')
{
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}else if(result == '0')
{
//show that the username is NOT available
$('#submit').show();
}
}, error: function(error)
{
alert(error);
}
});
}
});
** Remove the alerts when done with testing the code. **
I have been stuck with this problem for days already. I used Ajax group of web development techniques to call the php file from the server. It appears that the success method was not called. Here is my code:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#email", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://prefoparty.com/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["email"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace(main.html);
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter email and password");
}
return false;
}
In php, I used a typical MySQL call and as I run this file from Google Chrome browser. It returned the JSON correctly. Here is my php:
<?php
require_once('includes/configinc.php');
$link = mysql_connect(DB_HOSTNAME, DB_USERNAME,DB_PASSWORD) or die("Could not connect to host.");
mysql_select_db(DB_DATABASE, $link) or die("Could not find database.");
$uname = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM User_Profile WHERE Email = '$uname' AND Password = 'md5($password)'";
$result=mysql_query($sql);
$num_row = mysql_num_rows($sql);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
?>
Please check my code and point out where I did wrong.
Thank you all in advance :)
Adding
header("access-control-allow-origin: *")
to the Top of your PHP page will solve your problem of accessing cross domain request
i created a sencha touch application,in my controller i used the ajax code as
if (condition is true){
Ext.Ajax.request({
url: 'http://localhost/../abc.php?action=check',
params: valuesUser,
method: 'POST',
success: function(response){
var text = response.responseText;
console.log(response.responseText);
if(response.responseText == 'exists')
{
//Ext.Msg.alert('Success', text);
Ext.getCmp('loginform').destroy();
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
}
else{
Ext.Msg.alert('Success',text);
}
}
failure : function(response) {
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
}
});
}
else{
Ext.Msg.alert('Error', 'All the fields are necessary');
}
my abc.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('RegisterForm',$con);
if($_REQUEST["action"]== "check"){
$query = "SELECT name FROM userdetails WHERE name ='" . $_POST['userName'] . "' ";
$queryresult = mysql_query($query);
$count = mysql_num_rows($queryresult);
if($count == 1)
{
echo('values are in the db');
}
else
{
echo("values aren't in the db");
}
}
?
if contion is true in the controller code it goes to abc.php and checks name exists in the db are or n't.if name exist then it should open another view ,otherwise it should display alert msg as values aren't in the db.but by using the above code ,im navigating to another view in both cases (values are in db,values aren't in the db).can anyone help me to do this. thanks in advance...
You need to put condition in your sencha code based on the returned value from PHP. Something like:
if(response.responseText == 'exists')
Ext.Viewport.setActiveItem(Ext.create('RegisterForm.view.Main'));
else
Ext.Msg.alert('Success', text);
Moreover do
echo 'exists';
instead of
echo('values are in the db');
Summary: This is a basic, stand alone web form. Just html form, with a JQuery included for the functions.
I have a form that checks email and username for uniqueness and validity (of email). I'm using a JQuery onChange event to call each function, which is an Ajax call to a php file.
The JQuery for the username check is as follows:
$("#username").change(function() {
var username = $("#username").val();
var msgbox_username = $("#username_status");
var dataString = "username="+ username;
$("#username_status").html('<img src="images/loader.gif">Checking Availability.');
if (username != "" && username.length >= 6){
$.ajax({
Type: "POST",
url: "functions/check_username.php",
data: dataString,
success: function(msg_username) {
$("#username_status").ajaxComplete(function (event, request) {
if (msg_username == 'Username Ok') {
$("#username").removeClass("red").addClass("green");
msgbox_username.html('<font color="Green">Available</font>');
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html(msg_username);
}
});
}
});
return false;
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html('<font color="Red">Username of 6 or more characters is required</font>');
}
});
The check_username.php file is as follows:
<?php
$username = $_GET["username"];
include_once("../includes/connect.php");
$query = "SELECT username
FROM sss_users
WHERE username = '$username'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0 && strlen($username) >= 6) {
echo '<font color="#cc0000"><strong>' . $username . '</strong> is already in use. </font>';
} else {
echo 'Username Ok';
}
?>
Continuing with the pattern, the email JQuery:
$("#email").change(function() {
var email = $("#email").val();
var msgbox_email = $("#email_status");
var dataString = "email="+ email;
$("#email_status").html('<img src="images/loader.gif">Checking Availability.');
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){
$("#email").removeClass("green").addClass("red");
msgbox_email.html('<font color="Red">Valid Email Required</font>');
} else {
$.ajax({
Type: "POST",
url: "functions/check_email.php",
data: dataString,
success: function(msg_email) {
$("#email_status").ajaxComplete(function (event, request) {
if (msg_email == 'Email Ok') {
$("#email").removeClass("red").addClass("green");
msgbox_email.html('<font color="Green">Available</font>');
} else {
$("#email").removeClass("green").addClass("red");
msgbox_email.html(msg_email);
}
});
}
});
return false;
}
});
And the email PHP:
<?php
$email = $_GET["email"];
include_once("../includes/connect.php");
$query = "SELECT email
FROM sss_users
WHERE email = '$email'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0) {
echo '<font color="#cc0000"><strong>' . $email . '</strong> is already in use. </font>';
} else {
echo 'Email Ok';
}
?>
They each work seperately, but if I put an invalid username in the box and then put a valid email, somehow the check_username.php file is called and no matter what is in the box (valid or not) it thinks it's a valid username.
An example is:
All functions are called on the OnChange Event
1) type in the username asdfasdf (which is available)
2) Delete the username asdfasdf from the text box (this works correctly, displaying a username must have at least 6 characters)
3) type in any valid email
Result: the valid email works correctly, but the username field (which is blank) recalls what was there before (asdfasdf) and says it is a valid username (even though the field is still blank.)
Hope this makes sense. Any suggestions?
SOLUTION
As noted below, the .ajaxComplete() was calling all functions with that tag. Therefore, when I made the following changes it worked:
$("#username_status").ajaxComplete(function (event, request) { ... code here ... });
changed to:
$("#username_status").ajaxComplete(function (event, request, settings) { ... code and new if statement ... });
And then I wrapped
if(settings.url == 'functions/check_username.php') {}
around the validation code. This process was done for both the username and email validation.
http://api.jquery.com/ajaxComplete/
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
Maybe both handlers are being fired.
I'm trying to prevent duplicate entires in my DB for a newsletter submissions form. I'm successfully preventing the duplicate entries, but I haven't been able to revise my the jQuery to print the error. I've included the PHP just incase I'm missing something there... Any help would be appreciated!
jQuery:
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
success: function() {
$('#newsletterForm').html("<div id='success-message'></div>");
$('#success-message').html("<p><strong>Thank you.</strong> <br/>You've been added to our list and will hear from us soon!</p>");
},
error: function() {
$('#newsletterForm').html("<div id='success-message'></div>");
$('#success-message').html("<p><strong>That email already exists.</strong> <br/>Please enter another email address.</p>");
}
});
}
PHP:
if(isset($_POST['submit'])) {
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
if(!isset($hasError)) {
$con = mysql_connect("xxx.xxx.xxx.xxx","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$query = "SELECT COUNT(id) AS mycount FROM newsletter WHERE email = '$email'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if($row['mycount'] == 0) {
$query = "INSERT INTO newsletter (email,dt) VALUES ('$email',NOW())";
mysql_query($query) or die ("Error writing to database");
} else {
echo "I'm sorry our database already contains that email address. Please use a new email address to continue.";
}
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
}
}
The error only gets called if your AJAX request fails (such as a 404).
Inside your success: function() { } you'll need to determine if what your PHP script returned was a success message, or error message. The easiest way to do this is with JSON instead of plain text.
To do this, in your PHP instead of echoing a string, do..
echo json_encode(array('result'=>'success','response'=>'Everything worked');
or..
echo json_encode(array('result'=>'error','response'=>'Already exists');
Then in your ajax, set the dataType to 'json' and in your success function, you can then access the JSON as an object.
Instead of echoing out the messages, why can't you just print out a JSON representation of what happened? This will allow you to directly manipulate the object in JavaScript.
Remember: jQuery is not a language.