$_POST without refreshing - javascript

I got an associative array which I use to generate images. From these images I want to select two or more pictures to get one random.
My code works but I got two questions:
How can I improve my code?
And how can I use json or something else that my site doesn't refresh after submit?
<style>
.check {
opacity: 0.5;
color: #996;
}
</style>
<script>
function getRandomInt( min, max )
{
return Math.floor( Math.random() * (max - min + 1) ) + min;
}
function debug()
{
console.log( $( "img.check" )[0] );
}
$( document ).ready( function()
{
$( "form" ).submit( function()
{
var images = $( "img.check" );
if( images.length > 0 )
{
$( "input[name=images]" ).attr( "value", $( images[getRandomInt( 0, images.length )] ).data( "id" ) );
return true;
}
else
{
alert( 'Kein Bild ausgewählt.' );
return false;
}
} );
$( 'form img' ).click( function()
{
$( this ).toggleClass( 'check' );
} );
} );
</script>
</head>
<body>
<?php
$random = [
'Key1' => 'https://static.pexels.com/photos/4952/sky-beach-vacation-summer.jpeg',
'Key2' => 'https://static.pexels.com/photos/1852/dawn-landscape-mountains-nature.jpg',
'Key3' => 'https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg',
'Key4' => 'https://static.pexels.com/photos/12567/photo-1444703686981-a3abbc4d4fe3.jpeg',
'Key5' => 'https://static.pexels.com/photos/2757/books-magazines-building-school.jpg',
];
?>
<form method="post">
<input type="hidden" name="images">
<?php
foreach ($random as $key => $val)
{
echo '<h1>$key</h1>';
echo '<img src="'.$val.'" width="100px" height="100px" data-id="'.$key.'"">';
}
?>
<button type="submit" name="submit" class="btn btn-default">Submit</button>
</form>
<?php
if (isset($_POST['images']))
{
echo '<img src="' . $random[$_POST['images']] . '" />';
}
?>

You can use ajax that returns your associate array into a json format.
example
use jquery for this
$.post('yourphpscript.php', function(data) {
data // this is your associated array
}, 'JSON');

Use code like this if you just want to refresh your div
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Generate random number</title>
</head>
<body>
<div id="div1" style="border:solid 1px red; width: 100px;"></div>
<br /><br />
<div id="div2" style="border:solid 1px green; width: 100px;">
<button type="button" id="btn_click" /> click me!</button>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$("#btn_click").click(function(){
$('#div1').html(10 + Math.floor(Math.random()*91));
});
$("#btn_click").trigger("click");
</script>
</body>
</html>

Use AJAX with POST method for send data and image using mimeType: "multipart/form-data"
AJAX script code:
<script>
$.ajax({
type:"POST",
url:"ajax_filename.php",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success:function(result)
{
$('#image_div').attr('src','image_file_path.png'); // Change the image to submited image.
}
});
</script>

ajax is used for prevent page loading ,so you need to change your form submit function a little bit and input hidden no need if you use ajax
$( document ).ready( function()
{
$( "form" ).submit( function()
{
var images = $( "img.check" );
if( images.length > 0 )
{
images = $(images[getRandomInt( 0, images.length)]).data( "id" );
$.ajax({
type : "POST", //set method
url : "", //link to current page (can go other link if u want)
data: "images=" + images, // post data
success : function(r){
$('body').html(r); // replace current page with new data
}
})
return true;
}
else
{
alert( 'Kein Bild ausgewählt.' );
return false;
}
} );
$( 'form img' ).click( function()
{
$( this ).toggleClass( 'check' );
} );
});
input type hidden will no need longer if you used like above ....

Related

jQuery Autocomplete, pass parameters into database

Hlleo, please help me in figuring this our from an example i took this and is working fine,
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
{key: "1",value: "NAME 1"},{key: "2",value: "NAME 2"},{key: "3",value: "NAME 3"},{key: "4",value: "NAME 4"},{key: "5",value: "NAME 5"}
];
$( "#project-name" ).autocomplete({
minLength: 0,
source: availableTags,
focus: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
return false;
},
select: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
$( "#project-id" ).val( ui.item.key );
return false;
}
});
});
</script>
<form action="search" method="post" >
<input id="project-name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
but for me i need it from database so i called the source as url and passed data to it as parameters like this
but in here only the console part works but the input is not populated,
What i want is to populate the input with label value(header Id) and store the id(task_summary_id) came along with it in another hidden input field when the item is selected from the list
So i did this to the original code
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
// var output = '';
// $('#project-name').keyup(function(){
// var query = $(this).val();
// if(query != '')
// {
// console.log(query);
// $.ajax({
// url:"autoCompleteNew.php",
// method:"POST",
// data:{query:query,cl:4},
// success:function(data)
// {
// console.log(data);
// output = data;
//
//
//
//
// }
// });
// }
// });
$("#project_name").autocomplete({
//var output = '';
source: function(request, response) {
console.log(request.term);
$.ajax({
url: 'autoCompleteNew.php',
method:"POST",
data: {
query : request.term,
cl : 4
},
success: function(data) {
//response(data);
// output = data;
console.log(data); //here i am getting the correct log
// var parsed = JSON.parse(data);
},
// console.log(output);
});
},
focus: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// nothing here nothing in autocomplete
return false;
},
select: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// but nothing here
$( "#project-id" ).val( ui.item.key );
return false;
}
});
// $( "#project_name" ).autocomplete({
// minLength: 2,
// source: 'autoCompleteNew.php',
// data:{query:'gb',cl:4},
// focus: function( event, ui ) {
// $( "#project_name" ).val( ui.item.value );
// return false;
// },
// select: function( event, ui ) {
// $( "#project-name" ).val( ui.item.value );
// $( "#project-id" ).val( ui.item.key );
//
// return false;
// }
// });
// var availableTags = [
// {key: "1",value: "Mukund"},{key: "2",value: "Nandu"},{key: "3",value: "Dimble"},{key: "4",value: "Alisha"},{key: "5",value: "Parvathy"}
// ];
});
</script>
<form action="search" method="post" >
<input id="project_name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
please help me in figuring this out
my php code
$usr = $_POST['term'];
$cl = $_POST['cl'];
//$usr = 'm';
$output = '';
$usr = strtolower($usr);
//$retVar = array();
$db_handle = new DBController();
$query = "select task_summary_id as 'key',task_header_id as 'value' from gb_task_summary where LCASE(task_header_id) like '$usr%' and task_header_client_id = $cl";
//echo $query;
$i=0;
// $output = '<ul class="list-unstyled" id ="listUl">';
$results = $db_handle->runQuery($query);
if(!empty($results))
{
$retVar=$results;
}
else
{
$retVar = 'N';
}
// foreach ($retVar as $key => $value) {
// $output .= '<li id ="listLI">'.$value["task_header_id"].'</li>';
// $output .='<ul id ="listUl">';
// $output .= '<dd class="unselectable" id ="listDD">'.$value["task_header_name"].'</dd>';
// $output .='</ul>';
//
// }
//
// $output .= '</ul>';
echo json_encode($retVar);
my json response for '1111'
[{"key":"499","value":"1111"},{"key":"500","value":"1134"},{"key":"501","value":"1195"},{"key":"502","value":"1211"},{"key":"503","value":"1197"},{"key":"504","value":"1085"},{"key":"505","value":"1193"},{"key":"506","value":"1090"},{"key":"507","value":"1076"},{"key":"508","value":"1196"},{"key":"543","value":"1471"},{"key":"544","value":"1472"},{"key":"566","value":"1111"},{"key":"569","value":"1111"},{"key":"570","value":"1111"},{"key":"571","value":"1111"},{"key":"577","value":"1111"},{"key":"584","value":"1475"},{"key":"585","value":"1454"},{"key":"586","value":"1476"},{"key":"587","value":"1705"},{"key":"588","value":"1541"},{"key":"589","value":"1707"},{"key":"590","value":"1722"},{"key":"591","value":"1721"},{"key":"592","value":"1720"},{"key":"593","value":"1719"},{"key":"594","value":"1718"},{"key":"595","value":"1717"},{"key":"596","value":"1711"},{"key":"597","value":"1710"},{"key":"598","value":"1709"},{"key":"599","value":"1701"},{"key":"600","value":"1704"},{"key":"601","value":"1751"},{"key":"602","value":"1746"},{"key":"603","value":"1784"},{"key":"604","value":"1736"},{"key":"622","value":"1755"},{"key":"623","value":"1769"},{"key":"624","value":"1796"},{"key":"625","value":"1797"},{"key":"626","value":"1803"},{"key":"647","value":"1789"},{"key":"648","value":"1811"},{"key":"649","value":"1813"},{"key":"650","value":"1820"},{"key":"651","value":"1825"},{"key":"652","value":"1828"},{"key":"658","value":"1836"},{"key":"659","value":"1839"},{"key":"660","value":"1847"},{"key":"661","value":"1706"},{"key":"673","value":"1869"},{"key":"674","value":"1872"},{"key":"686","value":"1899"},{"key":"687","value":"1901"},{"key":"691","value":"1907"},{"key":"692","value":"1908"},{"key":"693","value":"1917"},{"key":"701","value":"1803"},{"key":"702","value":"1807"},{"key":"703","value":"1879"},{"key":"704","value":"1880"},{"key":"705","value":"1881"},{"key":"706","value":"1810"},{"key":"707","value":"1858"},{"key":"708","value":"1902"},{"key":"709","value":"1918"},{"key":"710","value":"1893"},{"key":"730","value":"1952"},{"key":"734","value":"1954"},{"key":"735","value":"1958"},{"key":"736","value":"1954"},{"key":"737","value":"1959"},{"key":"746","value":"1958"},{"key":"749","value":"1990"},{"key":"750","value":"1993"},{"key":"751","value":"1997"},{"key":"754","value":"1976"},{"key":"776","value":"1998"},{"key":"785","value":"1948"},{"key":"894","value":"1705"},{"key":"1008","value":"1111"},{"key":"1031","value":"1976"},{"key":"1375","value":"1111"},{"key":"1556","value":"1976"},{"key":"1819","value":"1624"},{"key":"1838","value":"1111"}]

How to store Javascript value in php variable shown in alert

How to pass javascript variable to php variable my code is- I want to store alert value in php variable.
<script type="text/javascript" >
$(document).ready( function() {
$( '#container' ).html( '<ul class="filetree start"><li class="wait">' + 'Generating Tree...' + '<li></ul>' );
getfilelist( $('#container') , 'Sample' );
function getfilelist( cont, root ) {
$( cont ).addClass( 'wait' );
$.post( 'Foldertree.php', { dir: root }, function( data ) {
$( cont ).find( '.start' ).html( '' );
$( cont ).removeClass( 'wait' ).append( data );
if( 'Sample' == root )
$( cont ).find('UL:hidden').show();
else
$( cont ).find('UL:hidden').slideDown({ duration: 500, easing: null });
});
}
$( '#container' ).on('click', 'LI A', function() {
var entry = $(this).parent();
if( entry.hasClass('folder') ) {
if( entry.hasClass('collapsed') ) {
entry.find('UL').remove();
getfilelist( entry, escape( $(this).attr('rel') ));
entry.removeClass('collapsed').addClass('expanded');
window.alert($(this).attr('rel'))
$( '#selected_file1' ).text( "Folder: " + $(this).attr( 'rel' ));
<?php
?>
}
else {
entry.find('UL').slideUp({ duration: 500, easing: null });
entry.removeClass('expanded').addClass('collapsed');
}
} else {
$( '#selected_file' ).text( "File: " + $(this).attr( 'rel' ));
}
return false;
});
});
</script>
There is difference between Javascript and PHP, PHP is a server-side script language while Javascript is a client-side script language. See https://www.sqa.org.uk/e-learning/ClientSide01CD/page_18.htm
Use the advantage of AJAX instead for your problem

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()

Creating textarea and buttons dynamically

I am facing issues with creating a dynamic textarea and 'Add' and 'Edit' buttons for every new paragraph.
DEMO of what I have managed so far:
The 'Add' button is for creating new paragraphs. The user should see a textarea where they enter the content for new paragraph. The first time they click 'Add' button, the text on the button will change to 'Save', the second time they click 'Save' it should append the paragraph to the div and assign it a unique id, which will be used to reference it with the new 'Add' and 'Edit' buttons.
The 'Edit' button is for editing the paragraph from which the 'Edit' button was clicked. To make the paragraph editable I'm using jquery editable (jeditable). Below are appropriate links to jeditable plugin:
plugin documentation
jeditable live demo
All the paragraph load from the back-end. Using PHP to load paragraphs:
<div class="paragraphs">
<?php
foreach($notes['children'] as $overview) :
if ($overview['type'] == 'Paragraph') :
?>
<div id="block1">
<p class='edit1'><?php echo $overview['content']; ?></p>
<p>
<?php if (isset($subject) && $subject==true) : ?>
<div id="para1">
<p><textarea cols="40" rows="2" id="textarea1"></textarea></p>
<button id="add1" class="add1 success tiny">Add</button>
<button id="startEdit1" class="canEdit1 tiny">Edit</button>
</div>
<?php endif; ?>
</p>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
The 'Add' and 'Edit' button functionality:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/teachers/js/jquery.jeditable.min.js"></script>
<script>
var $subject_id = "<?php echo $subject_id ?>";
var $teacher_id = "<?php echo $teacher_id ?>";
// Define our elements
var $lock = false;
//Make the elements editable
function makeThingsEditable() {
$editables.editable({
emptyMessage : '<em>Please write something...</em>',
callback : function( data ) {
$info.hide();
$info.eq(0).show();
}
});
}
function ajaxRequest(data, method_url, request_type) {
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('HTTP/1.1', '200');
}
});
var eurl = "<?php echo base_url(); ?>edit_flow/" + method_url;
var params = 'inputJson=' + data;
var post = $.ajax({
type: request_type,
url: eurl,
data: params,
success: function(result) {
console.log('result: '+result);
console.log('data: '+params);
},
async: false
});
//alert(post.responseText);
return post.responseText;
console.log(post.responseText);
}
// Edit paragraph button
// Button that toggles the editable feature
var i = 1;
var $editables = $('.edit'+i);
$('.canEdit'+i).click(function() {
if( $editables.is(':editable') ) {
//need to call save action here and pass in updated JSON
if ($(this).text() == 'Save changes')
{
var text = $(".edit"+i).text();
// ajax request
var datum = '{"subject_id":'+$subject_id+',"teacher_id":'+$teacher_id+',"editedContent":"'+text+'"}';
ajaxRequest(datum, 'editNotes', 'POST'); // POST request on editNotes
ajaxRequest(datum, 'loadNotes', 'GET'); // GET request on loadNotes
// jquery request
$.get( "<?php echo base_url(); ?>edit_flow/loadNotes", function( data ) {
var data = '{"subject_id":'+$subject_id+', "teacher_id":'+$teacher_id+', "editedContent":"'+text+'"}';
//console.log(data);
alert( data );
});
}
$editables.editable('destroy');
this.innerHTML = 'Edit';
i++;
} else {
makeThingsEditable();
this.innerHTML = 'Save changes';
// TODO h4kl0rd: make $editables selectable
}
});
// Add paragraph button
i = 1;
$('#textarea'+i).hide();
$('#add'+i).click(function(){
if ( $(this).text() == "Add" ) {
$('#textarea'+i).show();
$(this).text('Save');
$('#textarea'+i).focus(function() {
this.select();
});
}
else if ( $(this).text() == "Save" ) {
if ($('#textarea'+i).val() == ''){
alert('Enter something...');
} else {
$(this).text("Add");
$('#textarea'+i).hide();
var overview = $('#textarea'+i).val();
i++;
$('.paragraphs').append('<div id="block'+i+'"><p class="edit'+i+'">'+overview+'</p><div id="para'+i+'"><p><textarea cols="40" rows="2" id="textarea'+i+'"></textarea></p><button id="add'+i+'" class="add'+i+' success tiny">Add</button><button id="startEdit'+i+'" class="canEdit'+i+' tiny">Edit</button></div></div>');
}
}
});
</script>
Any help is appreciated.
change these:
$('.canEdit'+i).click(function() {
$('#add'+i).click(function(){
to these:
$(document).on('click', '.canEdit'+i, function() {
$(document).on('click', '#add'+i, function() {
What seemed to me is your buttons are dynamic and they can't take direct event binding. So instead you have to delegate the event to the closest static parent which is $('.paragraphs') or to $(document) itself because it is always available.
So if you are using closest static parent then you have to put your event handlers inside doc ready and if you are using $(document) then its not needed.
$(function(){
var i = 1;
var $editables = $('.edit'+i);
$('.paragraphs').on('click', '.canEdit'+i, function() {
// all your edit stuff
});
$('.paragraphs').on('click', '#add'+i, function() {
// all your addstuff
});
});

Retrieving AJAX value from a different Javascript function

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.

Categories

Resources