1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Autocomplete function. need some help to modify a little

Discussion in 'PHP' started by Hubert jiang, Apr 21, 2015.

  1. #1
    Hi Guys, Not sure if I can modify this code such that the autocomplete becomes more responsive.
    This is my HTML code:
    <div class='row'><!-- table starts here --->               
                 <div class="col-xs-12 col-sm-8 col-md-8 col-xs-offset-4 col-sm-offset-2 col-md-offset-2">
                     <h3 class="text-center">Populate Mutiple Textbox with single auto-select Request</h3>   
                    <form id='students' method='post' name='students' action='index.php'>
                   
                    <table class="table table-bordered">
                      <tr>
                        <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
                        <th>S. No</th>
                        <th>Country Name</th>
                        <th>Country Number</th>
                        <th>Country Phone code</th>
                        <th>Country code</th>
                      </tr>
                      <tr>
                        <td><input type='checkbox' class='case'/></td>
                        <td><span id='snum'>1.</span></td>
                        <td><input type='text' id='countryname_1' name='countryname[]'/></td>
                        <td><input type='text' id='country_no_1' name='country_no[]'/></td>
                        <td><input type='text' id='phone_code_1' name='phone_code[]'/></td>
                        <td><input type='text' id='country_code_1' name='country_code'/> </td>
                      </tr>
                    </table>
                   
                    <button type="button" class='btn btn-danger delete'>- Delete</button>
                    <button type="button" class='btn btn-success addmore'>+ Add More</button>
                    </form>
                </div>   
             </div><!-- table ends here --->
    HTML:
    This is my JS:
    $('#countryname_1').autocomplete({
        source: function( request, response ) {
            $.ajax({
                url : 'ajax.php',
                dataType: "json",
                data: {
                   name_startsWith: request.term,
                   type: 'country_table',
                   row_num : 1
                },
                 success: function( data ) {
                     response( $.map( data, function( item ) {
                        var code = item.split("|");
                        return {
                            label: code[0],
                            value: code[0],
                            data : item
                        }
                    }));
                }
            });
        },
        autoFocus: true,             
        minLength: 0,
        select: function( event, ui ) {
            var names = ui.item.data.split("|");
            console.log(names[1], names[2], names[3]);                       
            $('#country_no_1').val(names[1]);
            $('#phone_code_1').val(names[2]);
            $('#country_code_1').val(names[3]);
        }                 
    });
    
      $('#country_code_1').autocomplete({
        source: function( request, response ) {
            $.ajax({
                url : 'ajax.php',
                dataType: "json",
                data: {
                   name_startsWith: request.term,
                   type: 'country_code',
                   row_num : 1
                },
                 success: function( data ) {
                     response( $.map( data, function( item ) {
                        var code = item.split("|");
                        return {
                            label: code[3],
                            value: code[3],
                            data : item
                        }
                    }));
                }
            });
        },
        autoFocus: true,             
        minLength: 0,
        select: function( event, ui ) {
            var names = ui.item.data.split("|");                   
            $('#country_no_1').val(names[1]);
            $('#phone_code_1').val(names[2]);
            $('#countryname_1').val(names[0]);
        },
        open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }                 
      });
    
      $('#country_no_1').autocomplete({
        source: function( request, response ) {
            $.ajax({
                url : 'ajax.php',
                dataType: "json",
                data: {
                   name_startsWith: request.term,
                   type: 'country_no',
                   row_num : 1
                },
                 success: function( data ) {
                     response( $.map( data, function( item ) {
                        var code = item.split("|");
                        return {
                            label: code[1],
                            value: code[1],
                            data : item
                        }
                    }));
                }
            });
        },
        autoFocus: true,             
        minLength: 0,
        select: function( event, ui ) {
            var names = ui.item.data.split("|");                   
            $('#country_code_1 ').val(names[3]);
            $('#phone_code_1').val(names[2]);
            $('#countryname_1').val(names[0]);
        },
        open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }                 
      });
    
      $('#phone_code_1').autocomplete({
        source: function( request, response ) {
            $.ajax({
                url : 'ajax.php',
                dataType: "json",
                data: {
                   name_startsWith: request.term,
                   type: 'phone_code',
                   row_num : 1
                },
                 success: function( data ) {
                     response( $.map( data, function( item ) {
                        var code = item.split("|");
                        return {
                            label: code[2],
                            value: code[2],
                            data : item
                        }
                    }));
                }
            });
        },
        autoFocus: true,             
        minLength: 0,
        select: function( event, ui ) {
            var names = ui.item.data.split("|");                   
            $('#country_code_1 ').val(names[3]);
            $('#country_no_1 ').val(names[1]);
            $('#countryname_1').val(names[0]);
        },
        open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }                 
      });
    Code (JavaScript):
    This is my ajax.php:
    <?php
    require_once 'config.php';
    
    if($_GET['type'] == 'country_table'){
        $row_num = $_GET['row_num'];
        $result = mysql_query("SELECT name, numcode, phonecode, iso3 FROM country where name LIKE '".strtoupper($_GET['name_startsWith'])."%'");   
        $data = array();
        while ($row = mysql_fetch_array($result)) {
            $name = $row['name'].'|'.$row['numcode'].'|'.$row['phonecode'].'|'.$row['iso3'].'|'.$row_num;
            array_push($data, $name);   
        }   
        echo json_encode($data);
    }
    
    if($_GET['type'] == 'phone_code'){
        $row_num = $_GET['row_num'];
        $result = mysql_query("SELECT name, numcode, phonecode, iso3 FROM country where phonecode LIKE '".$_GET['name_startsWith']."%'");   
        $data = array();
        while ($row = mysql_fetch_array($result)) {
            $name = $row['name'].'|'.$row['numcode'].'|'.$row['phonecode'].'|'.$row['iso3'].'|'.$row_num;
            array_push($data, $name);   
        }   
        echo json_encode($data);
    }
    
    if($_GET['type'] == 'country_no'){
        $row_num = $_GET['row_num'];
        $result = mysql_query("SELECT name, numcode, phonecode, iso3 FROM country where numcode LIKE '".$_GET['name_startsWith']."%'");   
        $data = array();
        while ($row = mysql_fetch_array($result)) {
            $name = $row['name'].'|'.$row['numcode'].'|'.$row['phonecode'].'|'.$row['iso3'].'|'.$row_num;
            array_push($data, $name);   
        }   
        echo json_encode($data);
    }
    if($_GET['type'] == 'country_code'){
        $row_num = $_GET['row_num'];
        $result = mysql_query("SELECT name, numcode, phonecode, iso3 FROM country where iso3 LIKE '".$_GET['name_startsWith']."%'");   
        $data = array();
        while ($row = mysql_fetch_array($result)) {
            $name = $row['name'].'|'.$row['numcode'].'|'.$row['phonecode'].'|'.$row['iso3'].'|'.$row_num;
            array_push($data, $name);   
        }   
        echo json_encode($data);
    }
    ?>
    PHP:
    Currently, when I enter the country, it will provide suggestions and after u select the country, it will fill up the phone code, country number and country code.

    However, when u delete the country, these details are still there.

    Is there a way where I can modify the code such that as I delete the country name, the other details will be deleted as well?

    Thanks in advance.
     
    Hubert jiang, Apr 21, 2015 IP
  2. stephan2307

    stephan2307 Well-Known Member

    Messages:
    1,277
    Likes Received:
    33
    Best Answers:
    7
    Trophy Points:
    150
    #2
    Small improvement would be if you used a switch instead of if if if if

    Also before improving the speed you should be making the script more secure. You don't do any validation and cleansing and someone could fairly easy inject some not so nice SQL commands.

    And finally the mysql functions are deprecated and will be dropped at some point. I would strongly suggest using the PDO library.
     
    stephan2307, Apr 21, 2015 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #3
    Second thing I thought. First thing I thought was to find a stick to scrape that bootcrap off with.

    Which fixing your next suggestions:

    Would help fix since prepared queries == auto sanitize since you're not blindly sending data in the query.

    Though "dropped at some point"? They were deprecated as of PHP 5.5 and now throw an error; though they do still function the error log can get ugly fast.

    Not that we haven't been told for NINE YEARS to stop using them, and there haven't been GIANT RED WARNING BOXES in the manual for over three years now telling people to stop using them.

    NOT that I'm seeing what any of this code has to do with an "autocomplete". :/

    Really though "responsive" and "table" really don't go on the same page. Tabular data is inherently small screen unfriendly; you may have to strip table formatting off the TD/TH to micro-manage the placement of said elements.
     
    deathshadow, Apr 21, 2015 IP
  4. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #4
    Once I saw tthe use of mysql_query() and an open invitation to an SQL Injection attack I figured it would be a waste to try to help... just crap code. If you didn't write it yourself you should seek a better example. If you did write it yourself you have bigger problems here than performance.
     
    NetStar, Apr 21, 2015 IP
  5. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #5
    NetStar, your post is a waste of time... he asked for help so better point him to the right direction then telling us its a waste of time..
     
    EricBruggema, Apr 26, 2015 IP
  6. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #6
    My post may not have answered his original and only question but it did make a valid point. His code, whether he receives help or not, is VERY vulnerable to SQL injections and is using an old deprecated way to communicate with a database. With that said...I don't see anything of value to the original poster in your contribution. So perhaps you should have added something for him instead of wasting our time.
     
    NetStar, Apr 26, 2015 IP
  7. EricBruggema

    EricBruggema Well-Known Member

    Messages:
    1,740
    Likes Received:
    28
    Best Answers:
    13
    Trophy Points:
    175
    #7
    No your post states something that others already mentioned... i agree, my post is about your post.
    that said, hope the ts will respond, as most doesn't do these days....
     
    EricBruggema, Apr 26, 2015 IP
  8. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #8
    So your post was not needed. As with this one. As with mine now. At least my original post made a point and was on topic. Is there anything else you would like to add which is completely off topic and irrelevant or do you want to contribute?
     
    NetStar, Apr 26, 2015 IP
  9. Hubert jiang

    Hubert jiang Peon

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    1
    #9
    Thanks Guys for the feedback, I will be looking for a better and newer example.
     
    Hubert jiang, Apr 27, 2015 IP
  10. freelanceDeveloper

    freelanceDeveloper Member

    Messages:
    59
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    43
    #10
    something like ?

    $(.btn-danger).click(function(){
    $('#phone_code_1').val("");
    });
    Code (markup):
    edit : if it's a multiple form, you can try using closest() to get the id of the fields sitting next to the delete buttons (sorry, I'm talking a lot but actually I did not investigate this deeply, just providing some input that might help after a quick overview of the description )
     
    Last edited: May 5, 2015
    freelanceDeveloper, May 5, 2015 IP