Retrieving AJAX value from a different Javascript function - javascript

In this simplified example of a larger web app, consider a simplistic registration form with fields: username, firstname, lastname and a Register button type="button".
<form action="" method="post" id="cns_form">
<table id="companyTable"><tr>
<td width="200">
First name*:<br />
<input type="text" id="first_name" name="first_name">
</td>
<td width="200">
Last name*:<br />
<input type="text" id="last_name" name="last_name">
</td>
</tr></table>
<input type="button" value="Register" id="register" >
</form>
<div id="alert" title="Alert"></div>
When the username field is completed, jQuery fires an ajax search of a database to see if that username already exists. This same search is also triggered when one clicks Register (for reasons removed from this simplified example).
PROBLEM: Everything works great when leaving the username field. However, after clicking Register, I don't know how to retrieve the result of the AJAX search and stop the form from submitting if the username already exists. I've tried all kinds of different things, but have returned the code to this state so it is easiest for the reader to assist.
For example, I tried integrating the suggested solution from this question, but I was unsuccessful applying it to my situation... I tried setting async:false inside the ajax function... I also tried calling the checkUsername(uname) from inside the checkForm function, but that didn't work either. A little help?
jQuery document.ready:
$(function(){
$('#username').blur(function() {
var uname = $.trim($(this).val());
checkUsername(uname);
}); //END BLUR username
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkUsername(uname);
checkForm();
});
}); //END document.ready
AJAX Call:
function checkUsername(uname) {
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
}
checkForm Function:
function checkForm() {
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
}

One both rejoices and weeps when answering his own question, but here goes. The solution was to send the checkUsername() function as an input param to the checkForm() function, and to make the checkUserName() function return a value that we could check inside checkForm().
Therefore, we must modify the $('#register').click function thusly:
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkForm(checkUsername(uname)); //<===========================
});
THEN the checkUsername() function, thus:
function checkUsername(uname) {
var returnVal = 0; //<=================================
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
returnVal = 0; //<============================
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
return returnVal; //<==============================
}
AND the checkform() function thus:
function checkForm(exists) { //<============================
alert('sub checkForm(). value of exists: ' + exists);
if (exists==9) { //<================================
$( '#alert' ).html( 'That username is already in use' + existing +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
}else{ //<==========================================
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
} //<===================================================
}
Thanks and kudos to Felix Kling for this helpful post.

Might put return false in the function call in the HTML form markup.
<form>
<bunchOfElements />
<button onclick="checkUserName(); return false">Check Name </button>
</form>
Also, you might bind the function to the button's click event using
$(document).ready(function(){
$("#buttonID").bind('click', function(){
//do your thing
checkForm();
});
});

Put a return false at the end of your #register button click function, right below checkForm(). The button is continuing to fire the form submit. when you have that handled by your javascript function.

Related

Inserting Row into Database using HTML/PHP/AJAX

I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so I would definitely think that it is just a matter of being able to get the values to be read.
So my question is how can I get it to read the value and successfully enter it into the database.
HTML of Add button:
<td><button class="create-user" id="insertButton">Add Group</button></td>
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
JavaScript:
// ----- Dialog Box for adding a row -----
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+sku_group );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
EDIT
My html table:
<table id="skuTable" cellspacing="5" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th class="skuRow">SKU Group</th>
<th class="skuRow">Group ID</th>
<th class="skuRow">Edit</th>
<th class="skuRow">Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($sql_table) as $rows) { ?>
<tr>
<td class="sku_group" id="sku_group-<?php echo intval ($rows['SKU Group'])?>"><?php echo $rows['SKU Group']?></td>
<td class="group_id" align="center" id="group_id-<?php echo intval ($rows['Group_ID'])?>"><?php echo $rows['Group_ID']?></td>
<td><button type="button" class="edit" name="edit">Edit</button></td>
<td><button type="button" class="delete" onclick="deleteRow(this)">Delete</button></td>
</tr>
<?php
}
?>
</tbody>
</table>
Your value does not good
Try to change
var value = $(this).val();
To
var value = $(this).find('input[type=text]').val();
Try changing your $.each function to $tr.each. I think you should provide something for it to iterate over. Here is the link to .each() documentation..
If you want to iterate over all 's you have to add td to jquery call.
My fix would look like this:
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone(); //get all td of sku-table
var dict = {};
$tr.each(function(){
var type = $(this).attr('id'); // get value of current tr
var value = $(this).html(); // get html content inside of tr
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$('#group').val(dict['SKU Group']); // set value of the input field

Adding Row Using PHP/JavaScript/AJAX to Database

I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value that was entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(type + " : " + value); and it returns sku_group-0 : in the logs. I also do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so it definitely looks like it is just a matter of being able to get the values to be read so they can then be processed in the insert-group.php script.
So my question is how can I get it to read the value in the JavaScript so that it can be successfully entered into the database?
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
HTML of Add button:
<button class="create-user" id="insertButton">Add Group</button>
JavaScript:
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone();
var dict = {};
var errors = "";
$tr.each(function(){
var type = $(this).attr('id');
var value = $(this).html();
console.log(type + " : " + value);
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
REPLACE
"data: dict"
WITH
data:{ 'SKU_Group' : $('#group').val() }
AND
REPLACE
"$SKU_Group = $_POST['SKU Group'];"
WITH
$SKU_Group = $_POST['SKU_Group'];
You should get your input value with:
$('#group').val()

jQuery AJAX not returning false

I want my program below to return false if the employee ID exists. My PHP file echoes true if the employee ID exists and it is returned to the AJAX function.
$.post("connect_ajax_php.php",
{type: "checkId", val: val, field: "emp_id", table: "employee"})
.done(function(data, succ){
data = $.trim(data);
if( succ =="success" && data=="true" ){
$( errContId ).html( val+" already exist" );
$( id ).css( {"border":"1px solid red"} );
$('#'+sucImg).html("<img src='images/background/error.png'>");
return false;
}else{
$( errContId ).html("");
$( id ).css( {"border":"1px solid #ccc"} );
$('#'+sucImg).html("<img src='images/background/success.png'>");
}
});
If you are using the ajax call as a validation step you will manually submit the form in the ajax callback. Then move the return false to the click handler rather than call it from the ajax response handler.
<form id="myform" action="/url" method="post">
...
<button id="submitbtn" type="submit">Submit</button>
</form>
$("#submitbtn").on("click", function(event) {
$.ajax({
url: "connect_ajax_php.php",
method: "post",
data: {type: "checkId", val: val, field: "emp_id", table: "employee"}
})
.done(function(result) {
if (result == "true") {
// id exists
}
else {
$("#myform").submit();
}
});
return false; // prevent standard form submission
});

ajax custom dialog box upon success

I've coded a custom dialog/modal box as follows:
<div id="somedialog" class="dialog">
<div class="dialog__overlay"></div>
<div class="dialog__content">
<h2><strong>Howdy</strong>, I'm a dialog box</h2><
div><button class="action" data-dialog-close>Close</button></div>
</div>
</div>
It is currently triggered by a button with the javascript code as follows:
<script src="js/classie.js"></script>
<script src="js/dialogFx.js"></script>
<script>
(function() {
var dlgtrigger = document.querySelector( '[data-dialog]' ),
somedialog = document.getElementById( dlgtrigger.getAttribute( 'data-dialog' ) ),
dlg = new DialogFx( somedialog );
dlgtrigger.addEventListener( 'click', dlg.toggle.bind(dlg) );
})();
</script>
…where our trigger button has the data-attribute data-dialog="somedialog".
However, now I want to call this custom dialog only when my AJAX returns successful and pass in the message from AJAX into the dialog's <h2> text. How do I actually do that?
ajax call:
<script>
$(document).on("click", "#submit", function(){
var $self = $(this);
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var request = $.ajax({
url: "login.php",
type: "POST",
data: { username: username, password: password},
beforeSend: function(){
$self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
if( data == 'user' )
{
window.location.href = "filter.php";
} else if(data=='company'){
window.location.href = "filter.php";
}else {
alert("Wrong Username or Password!");
window.location.href = "indexwithlogin.php";
<insert the dialog box here>
}
});
});
</script>
From your first code block you're calling the dialog box using this line:
dlgtrigger.addEventListener( 'click', dlg.toggle.bind(dlg) );
...so it is simply the matter of calling it when a success/done response is obtained from the AJAX call. I have made some changes to your script:
Use the jqXHR deferred object .done() instead of .success(). The latter has been deprecated in favour of .done(), and the same for .error(), which is succeeded by .fail().
Convert native JS code into jQuery for the dialog box variable declaration, for consistency — although it's completely ok to use native JS, there is a lack of consistency here
Remove the window redirection by commenting it out, because it defeats the purpose of displaying the dialog box, no?
Here is the revised JS:
$(document).on("click", "#submit", function(){
var $self = $(this);
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var request = $.ajax({
url: "login.php",
type: "POST",
data: { username: username, password: password},
beforeSend: function(){
$self.html("Loading please wait...");
}
});
// When successful
// Use deferred object .done()
request.done(function(data) {
if(data=='user') {
window.location.href = "filter.php";
} else if(data=='company') {
window.location.href = "filter.php";
} else {
alert("Wrong Username or Password!");
// Call dialogue box
var dlgtrigger = $('[data-dialog]'),
somedialog = $(dlgtrigger).attr('data-dialog'),
dlg = new DialogFx( somedialog );
dlg.toggle.bind(dlg);
//window.location.href = "indexwithlogin.php";
}
});
});
use
dlg.toggle.bind(dlg)() inside success function
instead of
dlg.toggle.bind(dlg)

jQuery serialize function with multiple values

I try to use jQuery to post multiple values to PHP page, and then use that values as a single values.
I start with code from Jquery site :
<form ><br>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
<br>
<br>
</form>
<p><tt id="results"></tt></p>
<script>
function showValues() {
var str = $( "form" ).serialize();
$( "#results" ).text( str );
}
$( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
$( "select" ).on( "change", showValues );
showValues();
</script>
Result is: multiple=Multiple&multiple=Multiple2, and that is fine.
Now mycproblem is how to post these values to test.php page, and then to use unique values, like this :
$multiple=[first value]
$multiple2=[second value]
etc...
Change your multiple to multiple[] in your form. This will submit your values as multiple[]=1st value, multiple[]=2nd value and more.
jQuery,
$('form').on('submit', function(e)
{
e.preventDefault();
formData=$('form').serialize();
$.ajax(
{
type: "POST",
url: "test.php",
data: formData,
success: function(data)
{
alert("Form submitted");
},
error: function()
{
alert("Error in form submission");
}
});
});
At the PHP end,
$multiple=$_POST['multiple']; // Get the array input
Now proceed with the values respectively,
foreach($multiple as $key => $value)
{
echo "value number $key is $value"; // This will print as value number 0 is 1st value, value number 1 is 2nd value and more.
}
You have to post the form to test.php using AJAX. Try this -
$("form").on('submit', function(ev){
ev.preventDefault();
var form = $(this);
var action = 'test.php';
var data = $(this).serialize();
$.post(action, data)
.done(function(response){
if(response.success == false)
{
// If failed
}
else
{
// If successfully submitted
}
});
});
And on the other side (test.php), you'll get an array of your multiple values like this,
$multiple1 = $_POST['multiple']['0'];
$multiple2 = $_POST['multiple']['1'];

Categories

Resources