jQuery to database - registration form with validation - php

I find this tutorial in 9lessons.com : http://www.9lessons.info/2011/01/gravity-registration-form-with-jquery.html
It's about a registration form with validation.
I want to send data to DB.
// Submit button action
$('#submit').click(function()
{
var email=$("#email").val();
var username=$("#username").val();
var password=$("#password").val();
if(ck_email.test(email) && ck_username.test(username) && ck_password.test(password) )
{
$("#form").show().html("<h1>Thank you!</h1>");
///// if OK
///// Show thanks
//// else
//// Error, try again
}
return false;
});
How can I do ?? I searched in internet in jQuery tutorial and I find much codes ...

This tutorial will walk you the entire process:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
It implements jQuery.post and calls a PHP script that will allow you to process the data.

You will need to use Ajax to submit the data to a backend script (such as PHP) to do the actual database interaction. I'd recommend using POST:
http://api.jquery.com/jQuery.post/

you can use jquery post method
$.post("test.php", $("#testform").serialize());
or for more detail visit this link
jquery form post method

Finally I inserted data form to database... I have a problem.. I forgot to verify if email is available or not !
I added this lines from an other tutorial in email verification to test if email exist in DB or not.
First I send email to check_availability.php
if mail exist an error message appear else, the password fiel must appear ...
Like you see in picture, I verify the existence of an email adress and availibality and unavailability message appear but not correctly ...
$('#email').keyup(function()
{
var email=$(this).val();
if (!ck_email.test(email))
{
$(this).next().show().html("Enter valid email");
}
else
{
//$(this).next().hide();
//$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
$.ajax
({
type: "POST",
url: "user_availability.php",
data: "email="+ email,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
/*$("#email").removeClass('object_error'); // if necessary
$("#email").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');*/
//////////////////
$(this).next().hide();
$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
//////////////
}
else
{
$("#email").removeClass('object_ok'); // if necessary
$("#email").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
The tow first comment lines are the default ines used to show the next field //$("li").next("li.password").slid ...
Like you see I add them in Ok test section ....

Related

Form submission using ajax and page view moderation after the submission

At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.

Jquery keyup Event with AJAX causing incorrect results

I have the following Jquery code that listens to a user typing in a captcha and sends an ajax request on each keyup to see if the correct code has been typed:
$('#joinCaptchaTextBox').keyup(function() {
$.get('scripts/ajax/script.php', {
'join_captcha': '1',
'captcha': $('#joinCaptchaTextBox').val()},
function(data) {
var obj = JSON.parse(data);
if(obj.ajaxResponse.status) {
$('#joinCaptchaNotAcceptable').hide();
$('#joinCaptchaAcceptable').show();
}else{
$('#joinCaptchaAcceptable').hide();
$('#joinCaptchaNotAcceptable').show();
}
});
});
The PHP script on the other end just checks the session and replies:
if($siteCaptcha == $_SESSION['secretword']) {
$this->captchaCompare = TRUE;
}else{
$this->captchaCompare = FALSE;
}
This works fine 95% of the time but I'm finding sometimes it reports the captcha typed is incorrect even though its correct. I think this could be because when typed fast many requests are sent to the server and the order or requests coming back isn't the order sent and therefore (as only one will be correct) a prior one is recieved last and incorrect is displayed.
Is there a better way to do this? Is there a way to ensure the last request sent is recieved last? Is there something I'm missing here. I can give more info.
thankyou
Add a timeout so as to not send a request on every keyup when the user types fast:
$('#joinCaptchaTextBox').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
var data = {
join_captcha: '1',
captcha : $('#joinCaptchaTextBox').val()
};
$.ajax({
url : 'scripts/ajax/script.php',
data: data,
dataType: 'json'
}).done(function(result) {
$('#joinCaptchaNotAcceptable').toggle(!result.ajaxResponse.status);
$('#joinCaptchaAcceptable').toggle(result.ajaxResponse.status);
});
},500)
);
});

How to clear form data so refresh doesn't duplicate data without forwarding?

I created a guestbook, in which users can add entries via an HTML form. After submitting data to the guestbook, some users refresh the page. All browsers I know resubmit the data. afterwards. Is there a way to tell the browser, that the data should not be resubmitted?
I used to have a redirect after sucessfully storig the data to the database. But, now I want to promt some additional information to the user, e.g. "Thanks for your entry entitled '...'.", or "A coy of the entry was sent to your e-Mail-Adress...". I really like to avoid adding all the values to GET-Parameters to be able to use the information after the forwarding.
Is there another way (without a forward!) to prevnt the browser from submitting the data again after the user click on the "refresh" button?
Maybe you could set a session variable with a hash of the data posted and check it each time the page is loaded. If the hash is the same, the data has already been submitted:
<?php
session_start(); //Start the session
$dataHash = md5($_POST['name'].$_POST['comment'].$_POST['whatever']); //Get a hash of the submitted data
if(isset($_SESSION['gbHash']) && $_SESSION['gbHash'] == $dataHash) { //Check if the data has been submitted before
//Do not save the data/show a warning message
} else {
//Save the data/show a thank you message
}
$_SESSION['gbHash'] = $dataHash;
?>
Is there another way (without a forward!) to prevnt the browser from
submitting the data again after the user click on the "refresh"
button?
Yes - Ajax - and you can still you show all your success/failure messages and even validation....
read this - http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Example:
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
Hope this helps.
redirect the user with a custom message attached to the redirect location after POST action performed, for example
header("location: http://www.website.com/thankyou.php?msg=email_sent");
or
header("location: http://www.website.com/thankyou.php?msg=email_not_sent");
or
header("location: http://www.website.com/thankyou.php?success=0");
and then switch GET parameters to show corresponding message type.
or user AJAX POSTING :)

PHP and JQuery Button trigger not working

Im currently new to PHP and JQuery after having using ASP.Net and C Sharp for the 2 years. I have this major problem in which i require some assistance in.
I have a HTML <input type="submit" id="btnWL" value="Add to Wishlist"> button. Basically when this button is pressed a table called 'wishlist' in the database is checked to see if the current product is already in a wishlist. If no the button will trigger a database save else it will return a JQuery alert pop up error message.
I having difficulty in passing 2 PHP variables: $_SESSION["username"] and $_GET["ProductId"] into this JQuery method:
<script type="text/javascript">
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php");
});
});
</script>
As you can see this JQuery method must pass those values to an external PHP File which checks for an already exsisting record in the 'wishist' table with those details.
<?php
$WishlistDAL = new WishlistDAL();
$result = $WishlistDAL->get_ProductInWishlistById($_GET["ProductId"]);
if (isset($_POST["isPostBack"])) {
if (isset($_SESSION["username"])) {
if (isset($_GET["btnWL"])) {
//Check if ProductId is in Cart
if (mssql_num_rows($result)>0)
{
//Return an error
//Sumhow this has to trigger an alert box in the above JQuery method
}
else
{
//Write in Wishlist Table
$WishlistDAL->insert_ProductInWishlist($_GET["ProductId"], $_SESSION["username"]);
}
}
}
else
{
//Return Error
}
}
?>
Another problem I have is then displaying an alert box using the same JQuery method for any errors that where generated in the php file.
Any Ideas how I can implement this logic? Thanks in advance.
Your "$.post()" call isn't passing any parameters, and has no callback for interpreting the results:
$.post('addToWishlist.php', { username: something, password: something }, function (response) {
});
The "something" and "something" would probably come from your input fields, so:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
});
Now the callback function would interpret the response from the server:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
if (response === "FAIL") {
alert("fail");
}
else {
// ... whatever ...
}
});
Exactly what that does depends on your server code; that "FAIL" response is something I just made up as an example of course.
jQuery accepts an callback:
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php", {'isPostBack':1}, function(res){
if (res.match(/err/i)){
alert(res);
}
});
});
});
Then, in the php, just (echo('Error adding record')) for this jquery to see there's an error string in the response and pop up the error message.
Other methods would be to use json, or http status codes and $.ajaxError(function(){ alert('error adding'); });.
from what i can tell so far is you'll only need to pass in the product id in and you can do this by appending your $.post call with the value; this will pass to your php script as a query string variable. i'm not sure which php script you posted, but if you're sending your data with jquery, it's using post and not get, so you may need to make an adjustment there and the session data should be available regardless, since it's the same session.
again this is without seeing all the code and since some of it isn't labeled, it's hard to determine. another thing, i like to use $.ajax for most actions like this, you have a lot more room to define and structure, as well as create one generic ajax function to call the methods and post data, as well as make a response callback. here's the documentation for you to look into $.ajax
i hope this helps.

Is there a way to check if a user is logged in using JQuery?

I want to be able to display a message if a user is not logged in if they try rating a user by clicking a rating. Is there a way to add it to my JQuery code below or can I pass it to my PHP script?
I'm using PHP
Here is the JQuery code.
$('#rate li a').click(function(){
$.ajax({
type: "GET",
url: "http://localhost/update.php",
data: "rating="+$(this).text()+"&do=rate",
cache: false,
async: false,
success: function(result) {
// remove #ratelinks element to prevent another rate
$("#rate").remove();
// get rating after click
getRating();
getRatingAvg();
getRatingText2();
getRatingText();
},
error: function(result) {
alert("some error occured, please try again later");
}
});
just check it if one is login in your update.php script. If not login, echo something like "error".
then in your success handler,
success: function(result) {
if (!$.trim(result)==='error') {
// remove #ratelinks element to prevent another rate
$("#rate").remove();
// get rating after click
getRating();
getRatingAvg();
getRatingText2();
getRatingText();
} else {
// not login, do something...
alert('login first please...');
}
},
Send something back to jQuery as the result and check it, before you perform your other steps.
jQuery alone cannot test reliably if the user is logged in, but your request to PHP could send an answer if theuser was logged in or not. This answer can be checked and then display an error (or not).
Use your update.php script to send back a codified response that includes an acknowledgement of whether the user is logged in; I am assuming the script echoes some value which is then received as the result variable in your jquery snippet.
if(result.loggedin == "1"){ //Assuming your output is a JSON object
}else{
}
In Wordpress you can easily check with below code:
if(jQuery('body').hasClass('logged-in')) {
// add your jquery code
}

Categories