Database slice the last two characters of the password (?!) - php

I have a very frustrating problem. I have a client which send a registration form to the server. The handler is a php file.
The problem is the following: the client send the form data to the php, the php store it in the mysql database. But if I try to give a name which is contains a space - I don't know why - in the database the the password's length is reduced by two.
I searched long hours, but found nothing. I'm on the edge of madness, so I would like to ask you to help me to find the problem.
Here is the registration form:
<!-- REGISTRATION -->
<div data-role="page" id="regScreen">
<div data-role="content">
<div class="profileCircle">
<img src="img/iskola.jpg" />
</div>
<div class="space"></div>
<form action="" method="post" id="regForm" name="regForm">
<input type="text" name="nev" id="regName" placeholder="Teljes név" data-mini="true"/>
<input type="email" name="mail" id="regEmail" placeholder="Email cím" data-mini="true"/>
<input type="password" name="jelszo" id="regPassword" placeholder="Jelszó" data-mini="true"/>
<input type="submit" data-inline="true" data-mini="true" value="Regisztráció" name="rendben" id="rendben" />
</form>
</div>
<a href="#loginScreen"><div class="circle leftBottom c1">
<img src="img/ikonok/vissza.png" />
</div></a>
</div>
This is the script which should handle the registration on the client side:
function registration(){
var name = $('#regForm #regName').val();
var email = $('#regForm #regEmail').val();
var password = $('#regForm #regPassword').val();
if((password == "" || password == null) || (email == "" || email == null)){
navigator.notification.alert("Nem töltött ki minden adatot!", function(){}, "Figyelem!");
}else{
$.ajax({
url: host + "regisztracio.php",
type: 'post',
dataType: 'json',
data: {rendben:'ok', nev: name, mail: email, jelszo: password},
success: function(data){
if(data.ok){
navigator.notification.alert('Sikeresen regisztrált!\nMostmár be tud jelentkezni a saját felhasználónevével!',function(){
$.mobile.changePage("#loginScreen");
},'Üdvözöljük!');
}else{
navigator.notification.alert(data.uzenet,function(){},'Figyelem!');
if(data.help){
navigator.notification.confirm('Kívánja, hogy új jelszót küldjünk erre az email címre?',function(){
console.log(button);
}, 'Segíthetünk?', 'Igen, Nem');
}
}
},
error: function(err){
console.log('jajj');
navigator.notification.alert(err.message,function(){},'Hiba!');
}
});
}
}
And finally here is the php code:
<?php
if (isset($_POST['rendben'])) {
require("mysql.php");
$nev = $_POST['nev'];
$mail = $_POST['mail'];
$jelszo = $_POST['jelszo'];
if (empty($_POST['nev']) OR empty($_POST['mail']) OR empty($_POST['jelszo'])) {
$string = array("ok" => false, "uzenet" => "Nem töltött ki minden adatot!");
echo json_encode($string);
}else{
$sql = "SELECT *
FROM felhasznalok
WHERE mail = '{$mail}'";
$eredmeny = mysql_query($sql);
if (mysql_num_rows($eredmeny) == 0) {
$sql = "INSERT INTO felhasznalok
(nev, mail, jelszo, kep)
VALUES
('{$nev}', '{$mail}', '{$jelszo}', '{$kep}')";
mysql_query($sql);
$string = array("ok" => true);
echo json_encode($string);
}else{
$string = array("ok" => false, "help" => true, "uzenet" => "Ezzel az email címmel már regisztráltak, lehet, hogy elfelejtette a jelszavát?");
echo json_encode($string);
}
}
}?>
If you need I will upload a picture from the database table.
I hope you can help me.

Please forgive not a full answer as such but the formatting is better than a comment:
As others have already suggested:
Echo your sql statement. This is what is being stored in the db after all. This will show you whether your problem lies before or after the data is stored in the db.
var_dump($_POST) if your sql is good as this checks the code in between the receipt of data and its storage in the DB - you can see what your script actually sends.
escape your text to prevent 'sql injection' - Always escape the text because you never know when you are going to change your client page and it is safer that way. Your case is a prime example of why you never trust data from the client.
FWIIW, I suspect that the problem lies in the javascript. One problem with the use of libraries like jquery is that they actually don't make easy stuff easier. They make it more complex. A bit like a slide rule though, once learned, they make some complicated stuff no harder than the easy stuff. There is a code-portability benefit too.
Even so, IMHO, for a simple ajax call, you're actually better off using pure JS, certainly as a beginner. w3schools.com has an excellent AJAX tutorial and code examples.
mysql_* extensions are deprecated. You would be wise to learn mysqli_ (which is nearly identical) or PDO.

My guess is that you are having troubles with jQuery.param encoding of spaces (+, one character, instead of %20, three characters).
You can try manually replacing the ' ' with '%20' in the password field (note: you probably have the same problem in all fields, only you haven't noticed it yet) using the .beforeSend setting:
url: host + "regisztracio.php",
type: 'post',
dataType: 'json',
data: {rendben:'ok', nev: name, mail: email, jelszo: password},
beforeSend: function (req, data) {
data.jelszo = data.jelszo.replace(/\+/g, "%20");
},
success: function(data){
...
Also (but this is unrelated), on the PHP side, notice that you can simplify a bit your code to encode the answer in one place only:
$string = array("ok" => false);
// Ez ad némi biztonságot
$fields = array('nev','mail','jelszo');
foreach($fields as $field)
{
if (empty($_POST[$field]))
$string['uzenet'] = "Nem töltött ki minden adatot: ${field}!";
else
${$field} = mysql_real_escape_string($_POST[$field]);
}
if (!isset($string['uzenet']) {
$sql = "SELECT *
FROM felhasznalok
WHERE mail = '{$mail}'";
$eredmeny = mysql_query($sql);
if (mysql_num_rows($eredmeny) == 0) {
$sql = "INSERT INTO felhasznalok
(nev, mail, jelszo, kep)
VALUES
('{$nev}', '{$mail}', '{$jelszo}', '{$kep}')";
if (false === mysql_query($sql))
$string['uzenet'] = 'Volt egy adatbázis hiba!';
else
$string['ok'] = true;
}else{
$string['help'] = true;
$string['uzenet'] = 'Ezzel az email címmel már regisztráltak, lehet, hogy elfelejtette a jelszavát?';
}
}
die(json_encode($string)); // No more output after this.

Related

AngularJS : How can I get the value of my placeholder if no new value is specified

Im making a form in order to let the user update some of his personal info , but I would like to keep some placeholder values (actual and verified values - or already submitted values) if no new value is specified when submitting the form. I don't want the user to have to re fill all fields just to update one specific field... Is that possible, and safe by proceeding like that (xss?)
I tried something for purpose but doubt it would work. (beside this, the server just went down for maintenance I guess so I can't test it right now) Thats my php code for the request :
//get params
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if (isset($request->email)) {
$email = $request->email;
}
else $email = vm.email; // app side value... of course it won't work, only for you to see what I wish to do !
$telephone = $request->telephone;
echo 'telephone<br/>'.$telephone;
$adresse = $request->adresse;
echo 'adresse<br/>'.$adresse;
$email = $request->email;
echo 'email<br/>'.$email;
// Vérification des identifiants
try {
$req = $pdo->prepare('INSERT INTO users (telephone, adresse, email) VALUES (:telephone, :adresse, :email) ON DUPLICATE KEY UPDATE email= :email, telephone = :telephone, adresse = :adresse');
$req->execute(array(
'telephone' => $telephone,
'adresse' =>$adresse,
'email' => $email
));
echo '<br>';
print_r($req->errorInfo());
echo '<br>updated!';
}
catch(PDOException $e)
{
echo 'Erreur : ' . $e->getMessage();
}
?>
Angular Controller code :
// Controller profil
.controller('profilCtrl', function (user, $http, $state) {
var vm = this;
vm.user = user.getUserConnected();
vm.update = update;
function update(){
var data = {telephone: this.telephone, adresse: this.adresse, email: this.email}
$http({
method: 'POST',
url: 'http://mytpm.reaco.work/update.php',
data: data,
headers: {'Content-Type': 'application/json'}
})
.then(function(response){
vm.data = response.data;
vm.status = response.statusText;
console.log('STATUS ' + vm.status);
console.log('data ' + vm.data);
$state.go('profil');
}, function(error) {
vm.data = response.data;
vm.status = response.statusText;
vm.errorMessage = 'ERROR';
})
};
console.log(vm.user.prenom);
})
My form :
<form name="form" ng-submit="vm.update()" novalidate>
<label class="item item-input noborder">
<span class="input-label"><strong>Email:</strong></span>
<input type="email" name="email" ng-model="vm.email" placeholder="{{vm.user.email}}">
</label>
<label class="item item-input noborder">
<span class="input-label"><strong>Téléphone:</strong></span>
<input type="number" name="telephone" ng-model="vm.telephone" placeholder="{{vm.user.telephone}}">
</label>
<label class="item item-input noborder">
<span class="input-label"><strong>Adresse:</strong></span>
<input type="text" name="adresse" ng-model="vm.adresse" placeholder="{{vm.user.adresse}}">
</label>
<div class="item noborder">
<button class="button button-block button-positive" type="submit">Mettre à jour mes informations</button>
</div>
</div>
</form>
Any help is welcome ! Im not sure if Im going in the right direction...
I think you need to show your angular code. But generally you can Use binding in placeholder.
in your controller define initial data which is your form data.
var vm = this;
vm.myData = {
email : 'test#test.com', //default value is test#test.com
x : null, //x has no default value
y : null, //y has no default value
age : 25 //default value is 25
}
Then use it in your html
<input placeholder = "{{vm.myData.email}}" ng-model="{{vm.myData.email}}"/>
Ok I've got it ! It was dead simple actually... I was using for example vm.telephone as my placeholder and ng.model and it was actually displayed as a standard placeholder with grey characters and a smaller typo. I actually need to use vm.user.number (since Im using a user.service, can't go too deep into explanations here without it being complicated) as my placeholder to actually display the placeholder as input text ! Like this : ng-model="vm.user.telephone" placeholder="{{vm.user.telephone}} And now my data is displayed and interpreted as real data so when I click on submit only the data I modified is actually sent to my DB. (Also, Im setting all my variables to null by default in my DB for the update to work).

My AJAX query isnt validating properly

New to web design here. I have a login form that validates and works perfectly in php but when I try and validate using ajax it doesn't work. When i run the page it says it is a success no matter the input into the form. I have tried for days trying to get it to validate in many different methods. If there is a better way please let me know!
php here and is on same page as login form
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
} else {
echo json_encode('false');
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: "POST",
url: "header.php",
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
});
});
<form id="login_form" form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
<label class="login_form_labels"> Email:</label>
<input type="email" id="email" class="login_input" name="email"><br><br>
<label class="login_form_labels"> Password:</label>
<input type="password" id="password" class="login_input" name="password"><br>
<div id="stay_log">
Stay logged in.
<input type="checkbox" name="stayLoggedIn" value=1 id="checkbox_1">
</div>
<input class="login_form_btn" name="login" value="Submit" type="Submit" id="login_submit">
<button class="login_form_btn" type="button">Forget your Password?</button>
</form>
Please help!
set dataType as Json in your ajax as like given below
$.ajax({
type: "POST",
url: "header.php",
dataType: json,
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
Try this...
I think you need to require pure JSON response from server side and handle it in your ajax success method.
In your PHP code.
$response=array();
if (!empty($_POST)) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
$response['type']="success";
$response['message']="Login done successfully";
} else {
$response['type']="error";
$response['message']="Incorrect Email or Password!!!";
}
}
else
{
$response['type']="error";
$response['message']="invalid post request";
}
ob_clean();
echo json_encode($response);
die();
In above way from server you can response in only json format.
In you ajax call javascript code
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: 'post',
url: $('#login_form').attr("action"),
data: form,
dataType:'json'
success:function (response){
if(response.type=="success")
{
alert(response.message);
// write code for handle your success login;
}
else
{
alert(response.message);
// write code for handle your failure login;
}
},
error: function(response){
alert('Nope');
}
});
});
});
You have to handle JSON response from server side in your ajax success response
In jQuery/AJAX, the HTTP response code termines whether it is a success or not. So if the login failed, you should set a header in PHP indicating this failure.
if (.. login has failed .. ) {
// HTTP 401 = 'Unauthorized'.
http_response_code(401);
}
By doing this, you won't even have to process the resulting JSON, only maybe to get additional info. But the basic result will tell you enough: if the success callback was called, logging in was successful. If error was called, it was not successful for whatever reason.
This sets out your basic flow, and after that you could parse the result message to see any details of what's going on (internal server error, user unknown, password doesn't match, etc).
See List of HTTP response codes, for a list of alternatives and this question for an argumentation about using 401.
First use alert(response) to find out the response you are getting. It should be true or false.
success:function (response){
if(response === "true")
{
alert("hi");
}
else
{
alert("nope");
}
},

PHP variable from external file?

*EDIT / FINISHED SOLUTION / WORKING CODE
So, this is what a friend of mine helped me come up with.
Here is the part I use in my K2 "items.php" file:
<div class="fb-comments" data-href="<?php echo JURI::current(); ?>" data-num-posts="8" notify="true" data-width="580"></div>
<input id="authname" style="display: none;" type="text" value="<?php echo $this->item->author->name; ?>" />
<input id="authmail" style="display: none;" type="text" value="<?php echo $this->item->author->email; ?>" />
<input id="link" style="display: none;" type="text" value="<?php echo JURI::current(); ?>" />
<script>
window.fbAsyncInit = function() {
FB.Event.subscribe('comment.create', function (response) {
var commentQuery = FB.Data.query("SELECT text, fromid FROM comment WHERE post_fbid='" + response.commentID +
"' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url='" + response.href + "')");
var userQuery = FB.Data.query("SELECT name FROM user WHERE uid in (select fromid from {0})", commentQuery);
FB.Data.waitOn([commentQuery, userQuery], function () {
var commentRow = commentQuery.value[0];
var userRow = userQuery.value[0];
console.log(userRow.name + " (id: " + commentRow.fromid + ") posted the comment: " + commentRow.text);
trackcomments(response['commentID'], response['href'], 'create', commentRow.text, userRow.name, commentRow.fromid);
});
});
};
function trackcomments(_commentid, _address, _action, _commentMessage, _userName, _userId) {
var authname = document.getElementById('authname').value;
var authmail = document.getElementById('authmail').value;
var link = document.getElementById('link').value;
$.ajax({
type: 'POST',
url: 'http://mydomain.com/dostuff.php',
data: {'commentMessage': _commentMessage, 'userName': _userName, 'authname': authname, 'authmail': authmail, 'link': link},
cache: false
});
};
</script>
And this is the do_stuff.php:
<?php
//Handle some weird letters and stuff
setlocale(LC_TIME, 'swedish');
//creating an $author variable and populating it from $_POST
$author = $_POST['authname'];
$authoremail = $_POST['authmail'];
$link = $_POST['link'];
$commentMessage = $_POST['commentMessage'];
$userName = $_POST['userName'];
$date = strftime('%A %e %b %Y %H.%M', time());
//getting author email
$to = $authoremail;
//subject of email
$subject = "New comment posted on mydmomain.com";
//email content
$message = "On $date $userName wrote\n\n$commentMessage\n\non your entry $link#comments\n\nUse the above link to answer on the comment.";
//who the mail is from
$from = "admin#mydomain.com";
//header
$headers = "From:" . $from;
//send the email
mail($to,$subject,$message,$headers);
?>
Turns out, there was a simple reason it wasn't working... JavaScript doesn't seem to handle PHP!
So the "do_stuff.php" (earlier named sendmail.php) was never executed with the echo JURI::base();.
Even then though. The var = $this->item... was also trying to get data from PHP variables which wasn't working. So, to combat that the values of those variables where put in hidden input forms to retrieve them thru getObjectById.
Like my friend stated, don't know if this is the most elegant or sophisticated solution... but it does the trick and fills it's purpose.
However, if someone has a better more "correct" way of achieving this, I'm all ears :)
Thank you #jack for your help! And anyone else contributing to this subject in the future.
- ORIGINAL POST -
Still learning about PHP and Joomla and K2. Been sitting upp for days now trying to figure out how I can have specific authors receive emails when comments are made using fb:comments.
So far so good...
FB.event.subscribe comment.create acting without action from user
Now, the only thing missing is the referens to the variable "$item->author->name". Since this is usable in the original file (item.php) where I'm calling for the sendmail.php
<script>
window.fbAsyncInit = function() {
/* All the events registered */
FB.Event.subscribe('comment.create', function (response) {
$.get('<?php echo JURI::base(); ?>sendmail.php');
});
};
</script>
and this is the "sendmail.php" file
<?php
if ($item->author->name == "Firstname1 Lastname1"){
$to = "author1#mydomain.com";
}else if ($item->author->name == "Firstname2 Lastname2"){
$to = "author2#mydomain.com";
};
$subject = "New comment";
$message = "A new comments has been made.";
$from = "admin#mydomain.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
I don't know how I can get the $item->author->name to work. Since I need to make sure that it somehow checks to see what the name is (since it's showing on the generated page I have to be able to use it somehow) to specify which email to send TO.
I have no idea if this has already been asked, but I don't even know what to search for to get me started here. I can't imagine that this would be to difficult to solve (if you only know what you need to change). :)
You can try passing the author name as a parameter in your ajax call. Something along these lines:
FB.Event.subscribe('comment.create', function (response) {
var name = $item->author->name;
$.get('<?php echo JURI::base(); ?>sendmail.php'), new {'authorName': name};
});
Then in your sendmail script you should be able to access the passed authorName parameter...
if (authorName == "Firstname1 Lastname1"){...
You could also use $.post to send the parameter to the sendmail script.
Note: This is untested and from memory, but hopefully it will point you in the right direction. It's also been a while since I last worked with Joomla, and there is likely a better Joomla-specific way to accomplish this.
EDIT: here's an example of using POST to pass the variable to the sendmail script:
FB.Event.subscribe('comment.create', function (response) {
var name = $item->author->name;
$.ajax({
type: "POST",
url:'<?php echo JURI::base(); ?>sendmail.php'),
data: authorName,
cache: false,
});
});
...and in your sendmail.php file:
<?php
//creating an $author variable and populating it from $_POST
$author = $_POST['authorName'];
if ($author == "Firstname1 Lastname1"){
$to = "author1#mydomain.com";
}else if ($author == "Firstname2 Lastname2"){
$to = "author2#mydomain.com";
};
$subject = "New comment";
$message = "A new comments has been made.";
$from = "admin#mydomain.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
Again this is untested, but should give you an idea. Since you're using Joomla you should also look into Joomla's com_mailto component, it may or may not be easier. You can search for further info with "pass parameter to external PHP script via ajax" or something along those lines.
Also, here's a reference for jQuery ajax

Converting PHP/MySQL Request into jQuery AJAX Request

I am kicking myself in the arse here because i can't for the life of me figure it out...this is supposed to be a quick and dirty project, but, I decided i want to try something new, and I have little to no experience with the AJAX methods in jQuery...I spent quite literally 5 days trying to learn and understand how to appropriately implement the AJAX calls, but to know avail...I learned some basic stuff, but not what i need to execute the code below.
Again, I am wondering how to go about converting this standard request to AJAX using jQuery...
here is my form & php
HTML:
<form action="categories.php?action=newCategory" method="post">
<input name="category" type="text" />
<input name="submit" type="submit" value="Add Categories"/>
</form>
PHP:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['category'])) {
if ($_GET['action'] == 'newCategory') {
$categories = $_POST['category'];
$query = "SELECT * FROM categories WHERE category ='$categories' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
echo '<script>alert("The Following Catergories Already Exist: ' . $categories . '")</script>';
} else {
// Simply cleans any spaces
$clean = str_replace(' ', '', $categories);
// Makes it possible to add multiple categories delimited by a comma
$array = explode(",", $clean);
foreach ($array as &$newCategory) {
mysql_query("INSERT INTO categories (category) VALUES ('$newCategory')");
}
echo "<script>alert('The following Categories have been added successfully: " . $categories . "')</script>";
}
}
} else {
echo "<script>alert('Please Enter at Least One Category.')</script>";
}
}
?>
here's the proper syntax for making the call in the background and not submitting the form, but still sending/retrieving results.
$(function(){
$('form').submit(function(e){
e.preventDefault(); // stop default form submission
$.ajax({
url: 'categories.php',
data: 'action=newCategory',
success: function(data){
//here we have the results returned from the PHP file as 'data'
//you can update your form, append the object, do whatever you want with it
//example:
alert(data);
}
});
});
});
Also:
I would not do this ->
echo "<script>alert('Please Enter at Least One Category.')</script>";
Just do echo 'Please Enter at Least One Category.';
If you need to create an error system, you can do things like,
echo "Error 1001: <!> Please enter at least One Category!';
Then in your Ajax callback for 'success', we can split the returned object in <!>. Example to follow:
success: function(data){
if($(data+':contains("<!>")'){
var errMsg = $(data).split('<!>');
alert(errMsg[0]+' : '+errMsg[1]);
//above would output - Error 1001 : Please enter at least One Category!;
}
}

"Uncaught SyntaxError: Unexpected token <" in jquery.js. Email signup form with AJAX

I'm trying to build a simple email signup, and I came across this tutorial which seemed to be exactly what I wanted to do (http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/). I don't have much programming knowledge, so this was my best bet at getting something up and running. I followed the tutorial, but unfortunately, I'm having some problems with it.
My problem is when I try to submit an email address, I get Uncaught SyntaxError: Unexpected token < in jquery.js, on line 565.
When I expand the error in Dev Tools, it shows:
jQuery.extend.parseJSON jquery.js:565
$.ajax.success common.js:36
jQuery.Callbacks.fire jquery.js:1046
jQuery.Callbacks.self.fireWith jquery.js:1164
done jquery.js:7399
jQuery.ajaxTransport.send.callback jquery.js:8180
As I said, I'm a rookie with this, so I greatly appreciate any help. I've been researching for a while, but haven't found any issue the same as mine. Some were similar, but I couldn't fix the issue with any of the solutions I came across.
This is the form code:
<form id="newsletter-signup" action="?action=signup" method="post">
<fieldset>
<label for="signup-email">Sign up for email offers, news & events:</label>
<input type="text" name="signup-email" id="signup-email" />
<input type="submit" id="signup-button" value="Sign Me Up!" />
<p id="signup-response"></p>
</fieldset>
</form>
This is the signup JS:
/* SIGNUP */
$('#newsletter-signup').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
And this is the PHP:
<?php
//email signup ajax call
if($_GET['action'] == 'signup'){
mysql_connect('host','user','password');
mysql_select_db('table');
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if(mysql_num_rows($existingSignup) < 1){
$date = date('Y-m-d');
$time = date('H:i:s');
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
Thanks!
UPDATE: Shad - I inserted that code right after 'success:function(data){' Is that correct? After doing that, when trying to submit an email address, I get this in the console, pointing to the line with the newly added code:
Failed:
SyntaxError
arguments: Array[1]
get message: function getter() { [native code] }
get stack: function getter() { [native code] }
set message: function setter() { [native code] }
set stack: function setter() { [native code] }
type: "unexpected_token"
__proto__: Error
<br />
<b>Warning</b>: mysql_num_rows(): supplied argument is not a valid MySQL result resource in <b>/homepages/37/d403623864/htdocs/_php/launch_notify.php</b> on line <b>22</b><br />
{"status":"error","message":"Ooops, Theres been a technical error!"}
Screenshot of Dev Tools with that error. Let me know if you need to see any of the lines expanded or anything: http://i.stack.imgur.com/IwnBr.png
UPDATE #2: Using the code provided by satoshi, I think I made a little progress on figuring out the issue, but I still haven't solved it. I think I narrowed it down to a MySQL connection issue. I tried this code:
<?php
mysql_connect("[DB]","[USER]","[PASS]")
or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("signups")
or die(mysql_error());
echo "Connected to Database";
?>
And the response I get is:
Connected to MySQL
Access denied for user '[USER]'#'%' to database 'signups'
I've tried a bunch of things, but can't figure it out. My host is 1&1, and I created the table through there using PHPMyAdmin. I've tried different tables, all get the same issue. Here's a screenshot showing the table in PHPMyAdmin: http://i.stack.imgur.com/Oe0Fm.png
Thanks again for all the help so far everyone. I appreciate it.
Your PHP file is warning you because $existingSignup is not a valid resource. This is because your SQL query is invalid. For this reason, because PHP is outputting something unexpected, the page doesn't return a valid JSON response.
Please verify that your mysql_query(...) call returns a valid resource before calling mysql_num_rows(...), like this:
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if($existingSignup !== FALSE)
{
if(mysql_num_rows($existingSignup) < 1){
// ...
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
else {
$status = "error";
$message = mysql_error();
}
Edit: please note that the query is syntactically correct, I guess you face the problem because you didn't set up the DB table correctly.

Categories