jQuery form, exist checking - javascript

So i am creating a simple form that checks whether or not the value that the user is inputting exists or not in my DB using jQuery. Everything up until now is working so far however i find myself stuck at this next part.
To easily explain i will just show an example of what i am trying to achieve.
For this example i will be "weeden"
weeden has an ID of 255 in the company table of my database.
If the user types in "weeden" into the client field
To the right of the client field (on the web form), the text "weeden is unavailable" will appear
what i would like to have happen instead is this: "ID 255 is unavailable"
Here is the relevant code.
HTML FORM
<form action="addrecord.php" method="post" autocomplete="off"/>
<div class="form-field">
<label for="client">Client: </label>
<input type="text" name="client" id="client" class="check-exists" data-type="client" placeholder="#">
<span class="check-exists-feedback" data-type="client"></span>
</div>
jQuery Function
$.fn.existsChecker = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function(){
var self = $(this),
selfType = self.data('type'),
selfValue,
feedback = $('.check-exists-feedback[data-type=' + selfType + ']');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()){
selfValue = self.val();
if(selfValue.length >= 1){
$.ajax({
url: 'check.php',
type: 'get',
dataType: 'json',
data: {
type: selfType,
value: selfValue
},
success: function(data){
if(data.exists !== undefined){
if (data.exists === true){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is available');
}
}
},
error: function(){
}
});
}
}
}, 1000);
}
});
});
};
Check.php
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,
array('client')
)
){
switch($type){
case 'client':
$check = $db->prepare("
SELECT COUNT(*) AS count
FROM company
WHERE name = :value
");
break;
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
Any help/suggestions would be greatly appreciated. I consider myself a beginner, this is my first time working on a web project.
Just to clarify ahead of time, there are many other input fields on the same webform such as: email, date, first, last, etc.
I hope my question was clear enough. Thank you

You have to change your Query to something like this:
$check = $db->prepare("
SELECT id, COUNT(*) AS count
FROM company
WHERE name = :value
");
I assume that your primary key field on the company-table is named id.
And finally store the id in the output-Array
$result = $check->fetchObject();
$output['exists'] = $result->count ? true: false;
$output['id'] = $result->id;
Then you can output the id like so:
if (data.exists === true){
feedback.text('ID ' + data.id + ' is unavailable');
}

You can handle everything in query
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,array('client'))){
switch($type){
case 'client':
$check = $db->prepare("
SELECT (CASE WHEN(COUNT(id)>0) THEN id ELSE FALSE END) AS count
FROM company WHERE name = :value ");
break;
}
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
}
In Ajax success
if(data.exists !== undefined){
if (!data.exists){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is already taken.');
}
}

Related

How come Ajax response is different?

I can't find the reason why my ajax response is different when I console.log the response. Any ideas?
Page1 is used in account update form while page2 is used in registration form.
page1.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page1.php',
data:{ 'email': email, 'email_login': email_login },
success:function(response){
//some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupEmail()).done(function(a1){
console.log(a1);
if(a1[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email and email_login is a js var where I store userinput in, I used valid_email to check if email is valid
page1.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$email_login = trim_strip_data($_POST["email_login"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1 && $email !== $email_login){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
page2.js:
function ajaxCheckDupEmail(){
if(valid_email === true){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'email': email },
success:function(response){
// some code
}
});
}else{
//other code
}
}
function ajaxCheckDupUsername(){
if(username !== ""){
return $.ajax({
type:'POST',
url:'ajax/page2.php',
data:{ 'username': username },
success:function(response){
// some code
}
});
}else{
//other code
}
}
$.when(ajaxCheckDupUsername(), ajaxCheckDupEmail()).done(function(a1, a2){
console.log(a1);
console.log(a2);
if(a1[0] === 'false' && a2[0] === 'false'){
//submitting form
//some code
}
});
NOTE: email is a js var where I store userinput in, I used valid_email to check if email is valid
page2.php:
if(isset($_POST["email"]) && !empty($_POST["email"])){
$email = trim_strip_data($_POST["email"]);
$prep_data_email = $db->prepare("SELECT email FROM user WHERE email = :email");
$prep_data_email->execute(array(":email" => $email));
$row_count = $prep_data_email->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
if(isset($_POST["username"]) && !empty($_POST["username"])){
$username = trim_strip_data($_POST["username"]);
$prep_data_username = $db->prepare("SELECT username FROM users WHERE username = :username");
$prep_data_username->execute(array(":username" => $username));
$row_count = $prep_data_username->rowCount();
if($row_count === 1){
echo "true";
}else{
echo "false";
}
}
NOTE: trim_strip_data() is a custom function to trim white spaces although I don't think it is necessary in this case
The problem is I get 2 different response results (depending on result true/false).
In page1.js I get:
true
In page2.js I get:
true,success,[object Object]
true,success,[object Object]
It looks like I get an response object in page2.js but why I don't get one in page1.js?
https://api.jquery.com/jquery.when/#jQuery-when-deferreds
You are dealing with promises, and a promise always returns a promise.
So I would double check page1 isn't returning the object too.
E.g. open dev tools and run the following;
$.when().done(function( x ) { alert('done')});
you will see it returns an object, this is the promise.
but for
true,success,[object Object]
I don't see where success is coming from, are you missing some code?
On a side note...
if(valid_email === true)
is the same as
if(valid_email)
sorry, it was just bugging me.

Trigger a php script using ajax - how and where to program this?

Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});

AJAX insert in MySQL delay - non inserting

I'm programming kind of pool application -
I have about 50 divs - 1 shown, 49 hidden. In every div there is a form with radiobuttons and after user clicks on radiobutton, JS calls AJAX - PHP request and inserts answer into MySQL. After success, next div is shown and so on...
Everything works fine, until i answer faster - about 3 question/second.
Then some answers stop being stored. For exmaple answers 1,2,4,6,7,10 are stored. 3,5,8,9 are missing...
How could i avoid it? It's really important to have consictency in answers.
Here is my JS
$('input[type=radio]').click(function () {
$.ajax({
url: 'assets/ajax/save_answer.php',
data: {action: 'save_answer', question: currentQuestion, answer: $('input[name=answer-' + currentQuestion + ']:checked').val(), answer_pattern: 'agree-disagree', seconds: currentTime},
type: 'post',
dataType: 'json',
success: function (output) {
if (output.success) {
$('.loading img').css("display", "none");
$('#' + currentQuestion).remove();
currentQuestion += currentQuestion;
$('#' + currentQuestion).show();
} else {
alert("Answer wasn't stored");
$('.loading img').css("display", "none");
}
},
error: function () {
alert("Answer wasn't stored");
$('.loading img').css("display", "none");
}
});
PHP function
if (isset($_POST['action']) && $_POST['action'] == "save_answer") {
$resp = new stdClass();
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$user = $purifier->purify($_SESSION['user_id']);
$projekt = $purifier->purify($_SESSION['projekt_id']);
$otazka = $purifier->purify($_POST['question']);
$odpoved = $purifier->purify($_POST['answer']);
$answer_pattern = $purifier->purify($_POST['answer_pattern']);
$seconds = $purifier->purify($_POST['seconds']);
if(check_answer($answer_pattern, $odpoved)){
$stmt = $db->prepare("SELECT * FROM odpovedi WHERE uzivatel = :uzivatel AND projekt = :projekt AND otazka = :otazka");
$stmt->bindParam(':uzivatel', $user);
$stmt->bindParam(':projekt', $projekt);
$stmt->bindParam(':otazka', $otazka);
$stmt->execute();
$answers_count = count($stmt->fetchAll());
if ($answers_count != 1) {
$stmt = $db->prepare("INSERT INTO odpovedi (uzivatel, projekt, otazka, odpoved, seconds) VALUES (:uzivatel, :projekt, :otazka, :odpoved, :seconds) ");
$stmt->bindParam(':uzivatel', $user);
$stmt->bindParam(':projekt', $projekt);
$stmt->bindParam(':otazka', $otazka);
$stmt->bindParam(':odpoved', $odpoved);
$stmt->bindParam(':seconds', $seconds);
$stmt->execute();
$stmt = $db->prepare("SELECT * FROM odpovedi WHERE uzivatel = :uzivatel AND projekt = :projekt AND otazka = :otazka");
$stmt->bindParam(':uzivatel', $user);
$stmt->bindParam(':projekt', $projekt);
$stmt->bindParam(':otazka', $otazka);
$stmt->execute();
$answer_inserted = count($stmt->fetchAll());
if ($answer_inserted < 1) {
$resp->success = false;
} else {
$resp->success = true;
}
}else{
$resp->success = true;
}
}else{
$resp->success = false;
}
}
print json_encode($resp);
At least alert should be shown, right? But it is not...
Thank you,
Tomáš
Change your alert to
alert('Answer wasn\'t stored');
or,
alert("Answer wasn't stored");
Try option async: false in ajax options.
http://api.jquery.com/jquery.ajax/
As the option name says make asynchronous false, i.e it will wait for ajax to complete before showing next div/element(whatever is in your success).
Well, I've found solution by myself.
I didn't disable radiobutons when one of them was clicked. Because of that - another AJAX function was called and interrupted the previous one.
Now when I disable buttons after click and enable them after ajax succeed is everything fine.
Thank you for your help.

Posting a JSON string with multiple values to ext js panel

I am working on an element of an application I am developing. I have a small web app dedicated to keep track of clients for a business. Currently my capability is pretty limited. I store the note along with other attributes in the clients table. I decided to try and make it a bit better by adding a note table and updating an ext js panel with the notes.
Everything works if I only have one note in my notes query.
Otherwise I receive this error.
SyntaxError: invalid property id
..._date":"2013-10-08","note_body":"abcd"},{"username":"rcox","bdev_firstname":"Tre...
This is the PHP I am using.
case 'note':
$userid = $_REQUEST['clientID'];
$query = $dbh->prepare("SELECT a.username, b.bdev_firstname, b.bdev_lastname, n.note_date, n.note_body FROM admin a, bdevs b, clients c, notes n WHERE c.clientID=".$userid.";");
$query->execute();
while($cli = $query->fetch()) {
$json = '{"username":"'.$cli['username'].'","bdev_firstname":"'.$cli['bdev_firstname'].'","bdev_lastname":"'.$cli['bdev_lastname'].'","note_date":"'.$cli['note_date'].'","note_body":"'.$cli['note_body'].'"},';
$note .= $json;
}
$note = trim($note, ',');
echo '{success: true, data:'.$note.'}';
break;
This is my ext js function.
function getNote(){
var selectedNote = userGrid.getSelectionModel().getSelected();
Ext.Ajax.request({
url: 'inc/template.php',
params: {list: 'note',
clientID: selectedNote.get('clientID')
},
method: 'POST',
success: function(f,a){
var jsonData = Ext.util.JSON.decode(f.responseText);
if(jsonData.success == true)
{
var username = jsonData.data.username;
var bdev_firstname = jsonData.data.bdev_firstname;
var bdev_lastname = jsonData.data.bdev_lastname;
var note_date = jsonData.data.note_date;
var note_body = jsonData.data.note_body;
RightPanel.update('<b>Admin:</b> ' + username + '<br/><b>Buissiness Dev Rep:</b> ' + bdev_firstname + bdev_lastname + '<br/><b>Note Date:</b> ' + note_date + ' <br/>----------<br/> ' + note_body);
}
else
{
RightPanel.update('Access Denied');
}
},
failure: function(f,a){
Ext.Msg.alert("Error", "Access Denied");
}
});
}
This has been answered below. For more troubleshooting on this topic you can visit my question on Sencha Forums. http://www.sencha.com/forum/showthread.php?273478-MOVED-POST-Posting-a-JSON-array-with-multiple-values-to-ext-js-panel&p=1002545#post1002545
What's the point of using json if you actually don't use it.
case 'note':
$userid = $_REQUEST['clientID'];
$query = $dbh->prepare("SELECT a.username, b.bdev_firstname, b.bdev_lastname, n.note_date, n.note_body FROM admin a, bdevs b, clients c, notes n WHERE c.clientID = ?");
$query->execute(array($userid));
$response = json_encode(array('success'=> true, data => $query->fetchAll(PDO::FETCH_ASSOC)));
echo $response;
break;
And then ext.js part where your error lies - if data is an array, you need to iterate over it, before you can access associative fields, right?
if(jsonData.success == true)
{
var i, item;
for( i = 0; i < jsonData.data.length; i++; ) {
item = jsonData.data[i];
RightPanel.update('<b>Admin:</b> ' + item.username + '<br/><b>Buissiness Dev Rep:</b> ' + item.bdev_firstname+" "+item.bdev_lastname + '<br/><b>Note Date:</b> ' + item.note_date + ' <br/>----------<br/> ' + item.note_body);
}
}

AJax + PHP + MYSQL Newsletter subscriber

Currently I am able to add a new email address to my newsletter table, however I am struggling with the AJAX part of the query, ie. the validation.
Below is my Signup.php file:
<?php
require_once('required/init.php');
require_once('required/settings.php');
require_once('required/database.php');
require_once('required/class.phpmailer.php');
require_once('required/globals.php');
$email = trim($_REQUEST["email"]);
// Check if subscriber exists
$SQL= "select email from tblnewsletter where email='".$email."'";
$result = mysql_query($SQL);
if(!$result) {die('Problem in SQL: '.$SQL);} //just checking if there was a problem with your query
if (mysql_num_rows($result)==1) { // he was subscribed already
echo 'You are subscribed.'; // Change the message if you want.
}
else { // does not exist ==> add to the table
$SQL2= "INSERT into tblnewsletter (email) VALUES ('".$email."')";
mysql_query($SQL2);
echo 'Thank you for subscribing'; // Change the message if you want.
}
?>
and here is my Javascript:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#nlsubmit').on('click', function() {
signup();
return false;
});
});
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function signup()
{
var emailentered = $("#email").val();
var email = trim(emailentered);
//EMAIL VALIDATION
var goodEmail = email.match(/\b(^(\S+#).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
var apos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
lastpos = email.length - 1;
var badEmail = (apos < 1 || dotpos - apos < 2 || lastpos - dotpos < 2);
if (email == "" || !goodEmail || badEmail)
{
//Email address fails
$('myResponse').style.display = 'inline';
$('myResponse').style.color = 'red';
alert('Please enter a valid email');
$('email').focus();
return false;
}
else
{
email = encodeURIComponent(email);
//Email address succeeds
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
}
}
function showResponse(req) {
$("loading").hide();
$("myResponse").innerHTML = req.responseText;
$("myResponse").style.display = "inline";
$("myResponse").style.color = "blue";
$("submit").show();
$("email").invoke('clear');
}
function showException(req) {
$("myResponse").innerHTML = req.responseText;
alert("An error occured while talking to the server. Please try again.");
$("loading", "myResponse").invoke('hide');
$("submit").show();
$("email").invoke('clear');
}
</script>
The form that is calling all this is as follows:
<form method="post" name="subform" id="subform" action="">
<input type="text" id="email" name="email" value="">
<input type="submit" id="nlsubmit" name="submit" value="Sign up">
<div id="myResponse" style="display:none;"></div>
<div id="loading" style="display:none;"><img src="/images/wait.gif" alt=""></div>
</form>
Like I said the newsletter table is updated great, though I'm needing the user to be notified on the same page if they are already present, if the email is invalid etc.
In your function:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
'result' refers to whatever was echoed on signup.php, so if result=="You are subscribed." that means that the email address already exists in the database, otherwise if result=="Thank you for subscribing" the email address is new to the database and the new user subscribed. So the function should look something like this:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
if(result=="You are subscribed.")
{
// notify user that email address already exists
}
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});

Categories