Unable to use ajax with a radio box

I have and html file which has an input field and a radio box, I want upon the selection of the radio box to query a database using the value of the input field but I am getting always:
Uncaught TypeError: Cannot call method 'replace' of undefined

My Html code:
<!doctype html>
<html lang="en">
<head>
        <meta charset="utf-8">
        <title>Create User</title>
        <link rel="stylesheet" href="js/themes/base/jquery.ui.all.css">
        <link rel="stylesheet" href="css/validate.css">
        <script src="js/jquery-1.9.1.js"></script>
        <script src="js/jquery-1.10.1.min.js"></script>
        <script>
        $(document).ready(function() {
                $( "#tabs" ).tabs();
                  $('#locemailexistY').click(function() {
                           checkemail (); //if email exists
                  });
        });
                      function checkemail()
                    {
                    var checkname= $("#username").val();
                    var availname=remove_whitespaces(checkname);
                    if(availname!=''){
                        $('.check').show();
                        $('.check').fadeIn(400).html('<img src="images/loading.gif" /> ');

                        var String = 'username='+ availname;

                        $.ajax({
                            type: "POST",
                            url: "php locemail_check.php",
                            data: String,
                            cache: false,
                            success: function(result){
                                var result=remove_whitespaces(result);
                                if(result==''){
                                    $('.check').html('<img src="images/checked.gif" /> This Username has local email');
                                    $(".check").removeClass("red");
                                    $('.check').addClass("green");
                                }else{
                                    $('.check').html('<img src="images/unchecked.gif" /> This Username has no local email');
                                    $(".check").removeClass("green");
                                    $('.check').addClass("red")
                                }
                            }
                        });
                    }else{
                        $('.check').html('');

                    }
                }
               function remove_whitespaces(str){
                var str=str.replace(/^\s+|\s+$/,'');
                return str;
                }
                }
        </script>
</head>
<body>
<form action="" name="createuser" id="check" method="POST">
<input type="text" name="username" maxlength="10" size="10" />
<input type="radio" name="locemailexist" id="locemailexistY" value="y" /> Yes
<input type="radio" name="locemailexist" id="locemailexistN" value="n" checked> No
    <input type="submit" id="lcheck" value="Check">
</form>
</body>
</html>

My locemail_check.php is:
<?php
require_once(dirname(__FILE__).'/email_db.php');
if(isset($_POST['username']) && !empty($_POST['username'])){
      $username=$_POST['username'];
      $query="select user from mailbox where username='".$username.""" ;
      $res=pg_exec($con, $query);
      $count= pg_num_rows($res);
      $HTML='';
      if($count > 0){
        $HTML='Username is there';
      }else{
        $HTML='Create user first';
      }
      echo $HTML;
}
?>

Open in new window



I have tested the php script and it is working pretty well.
Ashraf HassaneinAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
replace :
<input type="text" name="username" maxlength="10" size="10" />
by :
<input type="text" name="username" id="username" maxlength="10" size="10" />

because you're using the ID jQuery selector : #
$("#username").val();

OR replace :
$("#username").val();
by :
$(":text[name=username]").val();
leakim971PluritechnicianCommented:
in your question, use the Code button to wrap your code inside a code box
goubunCommented:
Maybe you can change the function like:


function remove_whitespaces(str){
                var res=str.replace(/^\s+|\s+$/,'');
                return res;
                }
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Dave BaldwinFixer of ProblemsCommented:
These two lines are different versions of the same code.  You should only be using one of them.
        <script src="js/jquery-1.9.1.js"></script>
        <script src="js/jquery-1.10.1.min.js"></script>

Open in new window

Ashraf HassaneinAuthor Commented:
I have modified the html to look:

<!doctype html>
<html lang="en">
<head>
        <meta charset="utf-8">
        <title>Create User</title>
        <link rel="stylesheet" href="js/themes/base/jquery.ui.all.css">
        <link rel="stylesheet" href="css/validate.css">
        <script src="js/jquery-1.10.1.min.js"></script>
        <script>
        $(document).ready(function() {
                $( "#tabs" ).tabs();
                  $('#locemailexistY').click(function() {
                           checkemail (); //if email exists
                  });
        });
                      function checkemail()
                    {
                    var checkname= $("#username").val();
                    var availname=remove_whitespaces(checkname);
                    if(availname!=''){
                        $('.checklocalemail').show();
                        $('.checklocalemail').fadeIn(400).html('<img src="images/loading.gif" /> ');

                        var String = availname;

                        $.ajax({
                            type: "POST",
                            url: "php locemail_check.php",
                            data: String,
                            cache: false,
                            success: function(result){
                                var result=remove_whitespaces(result);
                                if(result==''){
                                    $('.checklocalemail').html('<img src="images/checked.gif" /> This Username has local email');
                                    $(".checklocalemail").removeClass("red");
                                    $('.checklocalemail').addClass("green");
                                }else{
                                    $('.checklocalemail').html('<img src="images/unchecked.gif" /> This Username has no local email');
                                    $(".check").removeClass("green");
                                    $('.check').addClass("red")
                                }
                            }
                        });
                    }else{
                        $('.check').html('');

                    }
                }
               function remove_whitespaces(str){
                var stringReceived='';
                        if (str != '' ){
                        stringReceived=stringReceived.replace(/^\s+|\s+$/,'');
                        }
                }
                }
        </script>
</head>
<body>
<form action="" name="createuser" id="check" method="POST">
<div id="tabs">
        <ul>
                <li><a href="#tabs-1">Username</a></li>
                <li><a href="#tabs-2">Check</a></li>
         </ul>
        <div id="tabs-1">
                <p>
         <input type="text" name="username" maxlength="10" size="10" />
               </p></div>
       <div id="tabs-2">
                <p>

<input type="radio" name="locemailexist" id="locemailexistY" value="y" /> Yes
<input type="radio" name="locemailexist" id="locemailexistN" value="n" checked> No
            <span id="checklocalemail" class="checklocalemail"  ></span>
                   </p>
                   </div>
    <input type="submit" id="lcheck" value="Check">
     
</form>
</body>
</html>

I have added the following at the end of css/validate.css:
.yellow{background-color:yellow;}
.white{background-color:#FFF;}
.green{color:green;}
.red{color:red;}

Now I do not have the error of replace anymore but I still cannot see any result on the screen.
I want as well to do the following based upon the text comming back from the php to:
set the checked radio, and change the backgorund of the input type username, is that possible?
leakim971PluritechnicianCommented:
You forget to use the Code button to wrap your code.

Why don't you apply the answer here : http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28323972.html#a39734711

?
Ashraf HassaneinAuthor Commented:
But the answer of this question is not applicable on this case because in the earlier question I wantes to make all my checks client side but now I want to get back to the server get some info, I tested the Php part (server side) and it is working pretty well the problem in the client I want to display this result on the fly and change the radio button and the input box based on the output back from the server and I am not sure if that is possible with ajax as no much explanation,  can you 0lease guide me in thst? why I am not able to display the results from the server in the screen? I did not get your point regarding wrapping the button, .
leakim971PluritechnicianCommented:
I see : $( "#tabs" ).tabs();
But I don't jQuery-ui script included in your code
Ashraf HassaneinAuthor Commented:
Ooops sorry for the typo it is there in the code and I can see the tab is working properly,  I feel I have a mistake in mapping the output from the server to the display but I do not know where is it
Ashraf HassaneinAuthor Commented:
Ooops sorry for the typo it is there in the code and I can see the tab is working properly,  I feel I have a mistake in mapping the output from the server to the display but I do not know where is it
Ray PaseurCommented:
This is a teaching example showing the essential moving parts.  It sends both the contents of a text box and the value of a radio button to a background script via an AJAX request.  The background script returns a string that is used to populate a <div> on the page.
http://www.laprbass.com/RAY_temp_ashraf_hassanien.php

Here is the AJAX background script.
<?php // RAY_temp_ashraf_hassanien_ajax.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28324192.html


// RETURN THE ARGUMENTS FROM THE GET-METHOD REQUEST
$s = !empty($_GET['s']) ? $_GET['s'] : '[omitted]';
$t = !empty($_GET['t']) ? $_GET['t'] : '[omitted]';
echo "AJAX REQUEST CONTAINED s: $s AND t: $t";

Open in new window

And here is the client-facing script that uses jQuery to make the AJAX request.
<?php // RAY_temp_ashraf_hassanien.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28324192.html


// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>Dependent Radio Buttons with jQuery / AJAX</title>

<script>
$(document).ready(function(){
    $("#color").hide();
    $("#sigxs .sigx").change(function(){
        mysigx = $('input[name="sigx"]:checked', '#sigxs').val();
        mytext = $("#text").val();
        $.get("RAY_temp_ashraf_hassanien_ajax.php", {s:mysigx, t:mytext}, function(response){
            $("#color").html(response);
            $("#color").show('slow');
        });
    });
});
</script>

</head>
<body>
<form action="RAY_EE_dependent_dropdown_action.php">
Text: <input id="text" />
<br>

Signals
<div id="sigxs">
<input class="sigx" type="radio" name="sigx" value="" checked style="display:none;" />
<input class="sigx" type="radio" name="sigx" value="y" />yes
<input class="sigx" type="radio" name="sigx" value="n" />no
</div>
<br>

<div id="color" style="display:none;" /></select>
<br>

</form>

</body>
</html>
HTML5;

// RENDER THE WEB PAGE
echo $htm;

Open in new window

I am not sure you need the hidden radio button.  You might try testing without that element.  Hope this helps, ~Ray

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
Just tested it.  You do not need the hidden radio button.  Also, sorry about butchering the spelling of your name :-)
Ashraf HassaneinAuthor Commented:
Hi Ray thank you so much this example was extremely helpful, I manipulated a bit, and here is my ajax function and it is working:
                  $('#locemailexistY').click(function() {
                       $("#checklocalemail").hide();
                        username = $('#username').val();
                        username=username.replace(/^\s+|\s+$/,'');
                         $.post("locemail_check.php", {username:username}, function(response){
                            if(response=='Create local email first'){
                               $("#checklocalemail").html(response);
                               $("#checklocalemail").hide();
                               $("#checklocalemail").removeClass("green");
                               $("#checklocalemail").addClass("red");
                               $("#checklocalemail").show('slow');
                               $("#username").css("background-color","yellow");
                               $("input:radio[name='locemailexist'][value='n']").prop('checked', true);
                                } else {
                               if(response=='Username has local email'){
                               $("#checklocalemail").html(response);
                               $("#checklocalemail").hide();
                               $("#checklocalemail").removeClass("red");
                               $("#checklocalemail").addClass("green");
                               $("#checklocalemail").show('slow');
                               $("#username").css("background-color","#00CC00");
                                 }
                                  else {
                               if (response=='Please enter a username'){
                               $("#checklocalemail").html(response);
                               $("#checklocalemail").hide();
                               $("#checklocalemail").removeClass("green");
                               $("#checklocalemail").addClass("red");
                               $("#checklocalemail").show('slow');
                               $("#username").css("background-color","yellow");
                               $("input:radio[name='locemailexist'][value='n']").prop('checked', true);
                                }
                               }
                              }
                           });
                  });
Ray PaseurCommented:
Great - glad you got it working.  Thanks for the points and thanks for using EE, ~Ray
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.