I'm working on a registration form for my website and it is only working in Firefox (with some issues), but in Chrome it does not work at all.
For example, if I correctly fill out the form in Firefox and submit, the PHP page still loads instead of sending that content to my registration form via my ajax call. However in Chrome, the form doesn't appear to submit at all.
In fact, in Chrome the variable data is set to the $num value in my PHP script, which is then displayed in #modal-body.
Question: How can I get this to work in all browsers and why is my event.preventdefault() not working correctly for Firefox??
Here is my registration form submission code:
$('#register-form').submit(function() {
$('#register-form > .input-group').removeClass('has-error');
$('#register-form .form-required').each(function() {
if ($(this).val().trim() == "") {
empty = true;
$(this).parent().addClass('has-error');
errors = "<strong>You have not filled out the login form correctly.</strong>";
}
else {
$(this).parent().removeClass('has-error');
$(this).parent().addClass('has-success');
}
});
// All fields populated, process the form
if (!empty) {
$('.progress').fadeIn(800);
$('#modal-body').parent().removeClass("has-error");
var formData = {
'username' : $('input[name=usernameReg]').val(),
'email' : $('input[name=email]').val(),
'password' : $('input[name=passwordReg]').val()
};
// Process the form
$.ajax({
type : 'POST',
url : 'db.php',
data : formData,
dataType : 'json',
encode : true,
success : function(data) {
if (data) {
// Fade the resulting message in
setTimeout(function() {
$(".progress").fadeOut(1000);
$("#modal-body").fadeIn(1000);
$("#modal-body").html(data);
}, 1000);
// Fade the resulting message out
setTimeout(function() {
$("#modal-body").fadeOut(2000);
}, 3000);
}
else {
$('#modal-body').addClass('has-error');
$('#modal-body').html(data);
}
}
});
}
// There were empty fields on the form
else {
$('#modal-body').html(errors);
}
event.preventDefault();
});
Here is my PHP code that handles processing of the form and checking to make sure that the account does not already exist, then that it is created in the database:
$hashed = md5($salt.$_POST['passwordReg']);
$email = $_POST['email'];
// Check if account already exists
$username = strtolower($_POST['usernameReg']);
$statement = $conn->prepare($selects['username']);
$statement->bind_param('ss', $hashed, $username);
if ($statement->execute()) {
//$statement->bind_result($results);
$num;
while($statement->fetch()){
$num++;
}
$statement->free_result();
}
else {
trigger_error('Error executing MySQL query: ' . $statement->error);
}
$statement = null;
// If num > 0, account exists.
// printf($num) only present for debugging purposes
printf($num);
if ($num < 1) {
$statement = $conn->prepare("INSERT INTO `User` (username, email, password) VALUES(?,?,?)");
$statement->bind_param('sss', $username, $email, $hashed);
if ($statement->execute()) {
echo json_encode('You have registered successfully');
}
else {
echo json_encode('Sorry, registration failed. Please try again later.');
}
}
else {
echo json_encode('Sorry, registration failed. Please verify that you do not already have an account.');
}
break;
Pass the event into the callback
$('#register-form').submit(function(e) {
// your code...
e.preventDefault();
}
Related
I have a function to resend the activation email.
When user try to login and user is not activated then a message show up with a link (you can see below).
It doesn't work at all. Can't even reach the js function if i'm correct.
What can be the problem? Please help me out.
Link that call the function:
Aktiváló e-mail újraküldése
JS code:
$(document).on('click', '#resend_activation', function()
{
var email = $(this).attr('email');
$("#success_msgforword").hide();
$(".errors").hide();
$.ajax({
type: "GET",
url: base_url + "aktivalo-ujrakuldes?email="+email,
dataType: "json",
success: function(data)
{
if(data==0)
{
$(".errors").html('Error! You are logged in!').show();
}
else if(data==1)
{
$(".errors").html('');
$(".success_msgforword").html('Success, you wil receive an email from us shortly.').show();
}
}
});
});
Controller that puts the caller link:
if (isset($errors['user_banned'])) { /* banned user */
$this->_show_message('error', $this->lang->line('auth_message_banned').' <br/><br/>Indok: '.$errors['user_banned']);
} elseif (isset($errors['not_activated'])) { /* not activated user */
$test = 'A felhasználói fiók nincs aktiválva! <br/>Aktiváló e-mail újraküldése';
$json = array(
'errors' => $test
);
} else { /* fail */
foreach ($errors as $k => $v){ $test = $this->lang->line($v);}
$json = array(
'errors' => $test
);
}
I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}
So I'm making an Ajax call which will first check to see if that post ID has already been voted on.
Currently I'm just working on the PHP to first get the post id's, if it is empty set it or if it is not empty to append the ID.
Question here: Except when I use the implode or explode method it does not seem to make a call back to the javascript. Although if I was to refresh the page it does register the vote.
This is the PHP file. For user Id I've just set it to my admin id to start with.
function my_user_vote() {
$user_id = 1;
$pageVoted = $_REQUEST["post_id"];
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
if (empty($currentPosts)) {
// Empty create single array
$postsVotedOn[] = $pageVoted;
} else {
$postsVotedOn = explode('|', $currentPosts);
$postsVotedOn[] = $pageVoted;
}
$boo = implode("|", $pageVoted);
update_user_meta( $user_id, 'pages_voted_on', $boo);
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
This is the javascript.
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery(".vote_counter").html("Votes: " + response.vote_count);
jQuery(".voteUpButton").html('<div class="button btnGreen">Thank you!</div>');
alert("Cooommmon");
console.log(response.vote_count);
}
else {
alert("Your vote could not be added")
}
}
})
})
})
I just did a quick test with your code, and found a couple of issues that throw errors:
1. This line:
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
should be
$currentPosts = get_user_meta($user_id, 'pages_voted_on', true);
2. And I believe this line:
$boo = implode("|", $pageVoted);
should be
$boo = implode("|", $postsVotedOn);
Explanation:
Without the true argument get_user_meta returns an array. And you can't explode an array.
http://codex.wordpress.org/Function_Reference/get_user_meta
$pageVoted is the id of the page to add, while $postsVotedOn is the actual list you want it appended to.
I have to validate my form which does a scheduling. I used ajax and php to do a query and search that time - that was choosen in a select - in the database. If there's one row saved, it returns 1 (or false), if doesn't, returns 0 (or true). Anyway, in the function callback, even it's true, the validate error appears, as if it had a real error. Printing the value, we see the value, but i dont know why it shows the error. I've tried everything, and nowhere i found the answer for this.
The js file: alteraDiv.js
jQuery.validator.addMethod('confereDia', function(value){
alert("entrou no método");
if (conf(value) == '0'){
alert("entrou no if");
return true;
}else{
alert("entrou no else");
return false;
}
});
var verifica;
function setVerifica(x){
verifica = x;
}
function conf(value){
$.ajax({
async: false,
url: 'confereDia.php?horarioInicial='+value,
dataType: 'text',
success: function(data) {
alert("entrou no success");
setVerifica(data);
alert("value:"+value);
return verifica;
},
error: function(data){
alert("ERROR. Dados: " + data);
}
});
}
The php file: confereDia.php
$horarioInicial = $_GET["horarioInicial"];
$query = "SELECT idAgendamento FROM agendamento WHERE horarioInicial = '$horarioInicial'";
$results = mysql_query($query);
if (mysql_num_rows($results) == 0) {
echo '0'; //good to register
} else {
echo '1'; //already registered
}
There are more codes in the files, but i think these are necessary for you understand and help me.. THANK YOU!!!
Hi I wonder whether someone may be able to help me please.
I've put together this page which has working 'client' and 'server' side validation.
What I'm now trying to do is add a page refresh and 'scroll to top', once the page has passed validation.
To the script used in the first link I've added the following code to try and invoke this functionality:
setTimeout(function() {
$('body').fadeOut(400, function() {
location.reload();
setTimeout(function() {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
The problem I'm having, is that irrespective of whether the the form passes validation, the page refreshes as can be seen in this page. So the full JavaScript code looks like this:
Post Update - Through working with #rahul, I've now have a working solution as below. NB I only needed to change the JavaScript code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#addlocation").validationEngine();
$("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').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 = $('#saverecordresponse');
//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)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
});
});
}
});
}
//prevent form from submitting
return false;
});
});
</script>
and this is a cut down version (I've deleted most of the validation rules for preview purposes) the PHP code which works in conjunction with the JavaScript and saves the record to a MySQL database.
<?php
//sanitize data
$userid = mysql_real_escape_string($_POST['userid']);
$locationname = mysql_real_escape_string($_POST['locationname']);
$returnedaddress = mysql_real_escape_string($_POST['returnedaddress']);
if(empty($locationname)){
$status = "error";
$message = "You need to enter a name for this location!";
}
else{
$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");
if($query){ //if insert is successful
$status = "success";
$message = "Location Saved!";
}
else { //if insert fails
$status = "error";
$message = "I'm sorry, there has been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
I must admit, I'm not sure where the problem lies, but I'm the first to admit I'm a little new to JavaScript and jQuery.
I just wondered whether someone may be able to look at this please and let me know where I'm going wrong, or even perhaps suggest a better alternative to make the page refresh once the form passes validation.
you can easily get it done using return false
check if validation not passed return false
if(Yourvalidation!=true)
{
return false;
}
after this section
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
check value of klass like this
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)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
else
{
return false; //use return false in else condition
}
});
});
You can check the client and server side validation by using this
if(Page_ClientValidate())
return true;
else
return false;