Solved

Unable to use ajax with a radio box

Posted on 2013-12-22
14
420 Views
Last Modified: 2013-12-23
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.
0
Comment
Question by:Ashraf Hassanein
  • 5
  • 4
  • 3
  • +2
14 Comments
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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();
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
in your question, use the Code button to wrap your code inside a code box
0
 
LVL 2

Assisted Solution

by:goubun
goubun earned 100 total points
Comment Utility
Maybe you can change the function like:


function remove_whitespaces(str){
                var res=str.replace(/^\s+|\s+$/,'');
                return res;
                }
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
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

0
 

Author Comment

by:Ashraf Hassanein
Comment Utility
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?
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
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

?
0
 

Author Comment

by:Ashraf Hassanein
Comment Utility
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, .
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 82

Expert Comment

by:leakim971
Comment Utility
I see : $( "#tabs" ).tabs();
But I don't jQuery-ui script included in your code
0
 

Author Comment

by:Ashraf Hassanein
Comment Utility
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
0
 

Author Comment

by:Ashraf Hassanein
Comment Utility
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
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 400 total points
Comment Utility
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
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Just tested it.  You do not need the hidden radio button.  Also, sorry about butchering the spelling of your name :-)
0
 

Author Comment

by:Ashraf Hassanein
Comment Utility
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);
                                }
                               }
                              }
                           });
                  });
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Great - glad you got it working.  Thanks for the points and thanks for using EE, ~Ray
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

jQuery is a JavaScript library that greatly simplifies JavaScript programming. AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a…
OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now