I know this would be difficult to understand but please give a try. Have a look at the screenshot.
The small input box's name is murl
.
add()
is used to submit the form. if murl
is empty the form has to be submitted directly, if its not empty the murl
entry has to be checked against the database if it exists. if it doesn't exist add()
is called.
The problem is the button
has to be clicked twice to trigger the function.
The code on the button is:
<button type="button" value="My button value" onclick="javascript: niju();" name="microsubmit" id="microsubmit">button</button>
the JavaScript which that button calls is:
function niju()
{
var flag=1;
var micro=document.getElementById('murl').value;
$('#microsubmit').click(function()
{
if(micro=="")
{
add();
}
else
{
//remove all the class add the messagebox classes and start fading
$("#msgbox")
.removeClass()
.addClass('messagebox')
.text('Checking...')
.fadeIn("slow");
//check the username exists or not from ajax
$.post("<?php echo SITE_ROOT;?>inc/user_availability.php",
{ murl: $("input:murl").val() },
function(data)
{
if(data=='no') //if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this)
.html('This User name Already exists')
.addClass('messageboxerror')
.fadeTo(900,1);
flag=0;
});
}
else
{
$("#msgbox")
//start fading the messagebox
.fadeTo(200,0.1,function()
{
//add message and change the class of the box and start fading
$(this)
.html('Username available to register')
.addClass('messageboxok')
.fadeTo(900,1);
flag=1;
add();
});
}
});
}
});
if(micro=="" && flag==1)
{
add();
}
}
Screenshot:
Move your flag out of the function niju.
It has to be clicked twice because you are defining
#microsubmit
'sclick
event inside the function. So the first time you click you bind the event handler, and the 2nd time the event handler is in place and gets fired. I haven't gone over the logic behind what you're trying to accomplish but my guess is that if you move the event binder outside the function and make sure all your variables are in the right scopes then it'll work.The first time you load the page, the click handler is not hooked to the button, is only until you click the button the first time that you are calling the niju() and hooking the click event. You need to do something like
and remove the onclick from the button declaration