jQuery: keyup event - ajax return validation - php

I'll start with what I'm trying to do.
I've created a "Forgotten Password" system where the user enters their email address and (if correct) they will be sent an email with a reset link.
There is a small section of ajax in the form page which detects if the email entered is in the database. If the email does exist in the database the form changes color to green and the submit button is enabled. If the email is not detected the form stays red and the submit button is disabled.
The issue is that when typing the email address, the keyup event seems to happen when the user has entered one more character than the correct email (basically if hello#123.com was in my database, they would have to enter hello#123.com1 for submit to be enabled)
Here is my JSFiddle with everything apart from the ajax working.
Here is an example of the ajax file itself:
<?php
session_start();
$Email = $_POST['email'];
//Parse ini file containing database information
$databaseInfo = parse_ini_file("optiMizeWebReport.ini", true);
global $con;
//Connect to database
$con = #mysqli_connect($databaseInfo['optiMizeDatabaseConnection'] ['WebServer'],$databaseInfo['optiMizeDatabaseConnection']['Username'], $databaseInfo['optiMizeDatabaseConnection']['Password'], $databaseInfo['optiMizeDatabaseConnection']['DBName']);
//Check connection and output error if invalid
if(!$con)
{
die('Connect Error ('. mysqli_connect_errno() .') '.mysqli_connect_error());
}
//Execute query
$result = mysqli_query($con, "SELECT COUNT(*) FROM login WHERE Email='$Email'")
or die("Error: ".mysqli_error($con));
//Initialize
$emailMatch = array();
//Extract
while($emailMatch[] = mysqli_fetch_array($result))
print_r($emailMatch[0][0]);
?>
If there is any other information i can give that will help please let me know. Thanks.
EDIT:
As there still seems to be no quick fix/answer I've made a short video showing exactly what happens. You can see it here: https://www.youtube.com/watch?v=P-2Gz5b4ek8

Ajax requests are asynchronous! In your case when you check if(databaseCheck != 1) the value of databaseCheck is previous ajax's response. Thats why you have to type 1 extra character to get last result.
$('input').bind("keyup", function() {
$.ajax({
type: "POST",
url: "ForgotPasswordAjax.php",
data: {email: $('#email').val()},
success: function(output){
console.log(output);
notification(output);
}
});
});
function notification(databaseCheck) {
if (databaseCheck != 1) {
....
} else {
....
}
}
on success part call a function like this, it will ensure that these codes will run after ajax success.
It will solve your current issue but you have to prevent simultaneous ajax calls. We have no idea which request return first, if first request response last js will set notification with that response. So you have to add a processing flag to prevent it.

i have updated the JsFiddle.
Here i have included keydown and focus into
$('#email').bind("keyup keydown change focus blur", function() {
and change below line
$('input').bind("keydown", function() {

jQuery has another event called input.
$('#email').bind("input", function() {
updated jsFiddle

Related

Combine JQuery/PHP to log clicks into database?

The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston"
success: function(data){
alert('done');
});

Why does this registration form ajax mysql insert work in chrome and safari but not firefox?

I am setting up a user registration page. It works in Chrome and Safari, but not Firefox (latest Mac versions). I am working locally on MAMP.
Expected Output:
Ajax request is sent after submit button click.
If username is available, user, password, email are inserted into mysql table. Success: hidden div "You are registered" appears.
Else, hidden div "Username unavailable appears"
Real Output:
Output is as expected in Chrome and Safari.
In Firefox, nothing is inserted in the table. No hidden divs show up, instead, the entire webpage reloads.
Why is the code below producing these different results?
Javascript
$(function() {
$("#registersubmit").click(function() {
var dataString = $("#registerclick").serialize();
if (registerclick.user.value == "")
{
$('.error').show();
registerclick.user.focus();
return (false);
}
else
{
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
success: function(reg) {
if (!reg)
{
$('.userexists').hide();
$('.error').hide();
$('.success').fadeOut(200).show();
}
else
{
$('.userexists').show();
}
}
});
}
return false;
});
});
PHP for MYSQL Insert
$user = ($_POST['user']);
$email = ($_POST['email']);
$time = time();
$password = ($_POST['password']);
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
include("config.php");
$sql = "INSERT INTO users (username, password, email,timestamp) VALUES ('".mysql_real_escape_string($user)."','".mysql_real_escape_string($password)."', '".mysql_real_escape_string($email)."', '$time')";
$result = mysql_query($sql);
if (!$result)
{
die(mysql_error());
}
}
Assume that password encryption and mysql escape precautions have been made.
The problem was with
if (registerclick.user.value == "")
Firefox apparently can't handle this for reasons I don't know. So I replaced it with
if (document.registerclick.user.value.length == "")
and it now works!
Since problems lies in client part only, you need to inspect client code.
Install firebug for firefox and debug what is broken in FF.
I may give you one idea just from the top of my head, though. In latest Firefoxes (from 7th or 8th version) elements with some id are not automatically exposed into global variables with the same name.
I bet, you didn't declared registerclick variable by yourself.
Therefore you need either to declare this variable:
var registerclick = $('#registerclick').get(0);
or replace registerclick in your code with forms.registerclick or somewhat... anyway, I hope, you get the idea.
PS: He-he, read comments. Anyway, I'll leave my answer.

Sending variable to PHP through jQuery and back

I am trying to create a kind of request where registered members see posts of other registered members. They might choose to connect with them before they can be able to comment on the post. What I want is to use jQuery to send the request to PHP which in turn inserts into the database with a status connection requested. When the member sees the request he can then choose to accept or reject that request. If he accepts it, the status will change to you are connected with this member.
Please I know that there are similar questions like this but not exactly as mine, somebody should please help.
'cont_email' is email of member sending request
'email_cont' is email receiving the request
'status' is the status of the connection
'counter' is request increment
This is my HTML part:
<input name="connect" type="button" value="Connect with <?php echo"$mem_com[name]";?>" class="intag2" onclick="connt()"/>
The PHP part is working ok. My only problem is sending the request through jQuery to PHP and back to jQuery which now displays the status of the connection based on members activity.
Updated answer:
Put this content into the file the user's will see (I assume thet the get parameters will be passed to this page when the user lands on them?):
<input id="connectButton" name="connect" type="button" value="<?php echo $status;?>" class="intag2" />
<script type="text/javascript">
var email_cont = '<?=$_GET[email_cont]?>';
var cont_email = '<?=$_GET[email]?>';
$('#connectButton').click(function() { // add a click event to the button (no need for onclick)
var counter = 0;
$.ajax({
url: 'requests.php?cont_email='+cont_email+'&email_cont='+email_cont+'&counter='+counter,
success: function( data ) {
$('#connectButton').val(data); // set the button value to the new status.
$('#connectButton').unbind('click'); //stop the user clicking the button loads of times.
}
});
});
</script>
Then put this in a file called requests.php:
<?php
$email_cont = $_GET['email_cont'];
$cont_email = $_GET['cont_email'];
$counter = $_GET['counter'];
$status = "Connection Sent!";
$insert = mysql_query("INSERT INTO request VALUES ('','$cont_email','$email_cont','$status', '$counter', NOW())");
$result = mysql_query($query);
if(!result){
//If it fails to run the SQL return an error.
echo "Connection Failed!";
}else{
//If all goes well, return the status
echo $status;
}
?>
Not tested, but should do what you are looking for.

Refresh value from MySQL db on php page after clicking a submit button

So all i need to do is refresh a variable displayed on a php page which is stored in a MySQL db. This value is an int which is subtracted by 1 everytime the submit button from a form is clicked. As i've opted to use AJAX to post the form the page isn't being refreshed, therefore the value isn't being updated along with the form submission.
$qry = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
while($row = mysql_fetch_array($qry)) {
if ($row['codes_remaining'] ==1 )
{
echo "You have ".$row['codes_remaining'].' code remaining';
}
else {
echo "You have ".$row['codes_remaining'].' codes remaining';
}
}
So this code just displays how many "codes" a person has left. I need this value to be refreshed once the submit button has been clicked from the form on the same page.
I'm using the following JavaScript to not refresh the page.
$("#form-submit").click(function(e) {
e.preventDefault();
$.ajax({
cache: true,
type: 'POST',
url: 'process-register.php',
data: $("#form-register").serialize(),
success: function(response) {
$("#output-div").html(response);
}
});
});
Thanks,
LS
If you'd like to update the value, do it like this (jQuery is easiest):
$(".submit").click(function(event) {
event.preventDefault();
$(this).load('file.php',function(val){
$('#output').text(val);
});
});
And in file.php:
<?php
connect_to_db();
$returned = get_info_from_db();
echo $returned;
?>
The jQuery will grab the info on file.php and put it into #output.
Maybe It's just me, but why not use jQuery .load function?
$("#form-submit").click(function(e) {
e.preventDefault();
$(this).load('process-register.php');
});
Maybe not ethical nor the correct way of doing this but everytime you click on #form-submit, it loads that file and therefore processes it everytime. Also note that if you load a file that uses MySQL connection yes has no mysql_connect or mysql_select_db configured, it obviously won't work. I've had that for quite some times.
In your 'success', you could possibly just throw in
$("#WhereYouWantTheOutput").load("process-register.php");
That way whenever your submit succeeds, it'll also load the output for you. Just replace #WhereYouWantTheOutput with the name of where you want the output placed.

Check in ajax/jquery a form beform submit ( check the value whether it is in database)

ajax is not yet sothin i master.
I have two forms field
code :
name :
and the submit button like :
<form><input type=text name=code><input type =text name=name/></form>
I would like in php/jquery to check if the code the user fill exist in a table of my db.
If it does not exits, when the user leave the textfield to fill the next one, i would like to print a message like: this code is not in the db and then clean the fied. Until the user provide a valide code.
If your php service returns true or false for validation.
and the placeholder for the error is a label called
then an example (in jQuery) would be
$(document).ready(function() {
$("form").submit(function(e) {
var code = $("input[name='code']");
var error = $("#error");
e.preventDefault();
var form = this;
$.getJSON('urlToPhp',
{ code: code.val() },
function(valid) {
if (!valid) {
error.text(code.val() + ' is not found try another code...');
code.val('');
} else {
form.submit();
}
}
);
});
});
I've created a simple example at http://jsfiddle.net/nickywaites/e4rhf/ that will show you have to create a jQuery ajax post request.
I'm not too familiar with php so that part of it I'll have to leave aside although you can use something along the lines of $_POST["Name"].
Here is php example that I googled http://php4every1.com/tutorials/jquery-ajax-tutorial/ that might be better for you.

Categories