Solved

Unable to use ajax with a radio box

Posted on 2013-12-22
14
430 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 3
  • +2
14 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 39735289
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
ID: 39735291
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
ID: 39735302
Maybe you can change the function like:


function remove_whitespaces(str){
                var res=str.replace(/^\s+|\s+$/,'');
                return res;
                }
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39735321
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
ID: 39735598
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
ID: 39735856
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
ID: 39735921
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
 
LVL 82

Expert Comment

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

Author Comment

by:Ashraf Hassanein
ID: 39735950
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
ID: 39736117
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 110

Accepted Solution

by:
Ray Paseur earned 400 total points
ID: 39736372
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 110

Expert Comment

by:Ray Paseur
ID: 39736406
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
ID: 39737003
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 110

Expert Comment

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

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

690 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