SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)

    Can not get the parameter of url parameter built using AJAX

    Hi,

    Initially when an AJAX search is run, a list of links (pagination) are created similarly to the code below. Each link contains a single parameter 'f'. 'f' contains the paged number ie
    Code:
    ?f=2
    . When one of the links built by AJAX is selected I can not get the value of 'f'. I need to do this as I'm not returning all search results at once; only the first 10. I need to pass the current paged number to the php file that is AJAX called.

    HTML Code:
    $("body").on("click", "#paged_results a", function(event){
                
                var terms = $('#terms').val();
                var f = $.QueryString["f"];
                console.log('clicked '+ f); //This always shows in the console as 'clicked null'
               $.ajax({
                type: "POST",
                        url: 'elasticsearch.php',
                       data: {
                            term: terms
                            , from_record: f
                      },
                      success: function( data ) {
    
    
                    console.log( data );
                        
                            var term = '<h2>' + data['term'] + '</h2>';
                            var color = '<span style="display: block; width: 200px; height: 20px; background-color: ' + data['color'] + ';" ></span>';
                            var raw_results =  data['results'];
    
    
                            var table = '<table>';
                        var table_header = '<tr>';
                        table_header = table_header + '<th>ID</th>';
                        table_header = table_header + '<th>Abstract</th>';
                        table_header = table_header + '<th>Post</th>';
                        table_header = table_header + '<th>Copyright</th>';
                        table_header = table_header + '<th>Creation Date</th>';
                        table_header = table_header + '<th>Make</th>';
                        table_header = table_header + '<th>Tags</th>';
                        table_header = table_header + '</tr>';
                        var undefined = '<td>--</td>';
                        var table_body = '';
                        var tags = '';
                        for ( var key in raw_results ) {
                            table_body = table_body + '<tr>';
                            table_body = table_body + '<td>' + raw_results[key].id + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].abstract + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].body + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].copyright + '</td>';
                            
                            var date = new Date( raw_results[key].created * 1000 );
                            table_body = table_body + '<td>' + date + '</td>';
    
    
                            if( typeof raw_results[key].make == 'undefined' ) {
                                table_body = table_body + undefined;
                            } else {
                                table_body = table_body + '<td>' + raw_results[key].make + '</td>';
                            }
    
    
                            if( raw_results[key].tags ) {
                                
                                table_body = table_body + '<td>';
                                
                                var count = raw_results[key].tags.length;
                                
                                var i = 1;
                                for( var inner_key in raw_results[key].tags ) {
                                    
                                    if( i < count ) {
                                        tags = tags + raw_results[key].tags[inner_key] + ', ';
                                    } else {
                                        tags = tags + raw_results[key].tags[inner_key];
                                    }
                                    i++;
                                    
                                    
                                    table_body = table_body + tags;
                                    tags = '';
                                    
                                }
                                table_body = table_body + '</td>';    
                            }
                            
                            table_body = table_body + '</tr>';
                        }
                        table = table + table_header + table_body + '</table';
    
    
                        
                        
                    $('#hit_count').html( '<p>about ' + data['count'] +' results </p>');
                        $('#decor').html( color );
                        $('#title').html( term );
    
    
                        // Round down
                        var paging_groups = Math.floor( data['count'] / 10 );
                        var base_url = $(location).attr('href');
                        var f = $.QueryString['f'];
                        if ( typeof f != 'undefined' ) {
                            if ( paging_groups > 10 ) {
                                var paging_links = '<ul id="paged_results" >';
                                for( i = f; i <=10; i++ ) {
                                    paging_links = paging_links + '<li>';
                                    paging_links = paging_links + '<a href="' + base_url + '?f=' + i + '">' + i + ', </a>';
                                    paging_links = paging_links + '</li>';
                                }
                            }
                            paging_links = paging_links + '</ul>';
                            $('#paging').html( paging_links );
                        }
      
                        $('#results').html ( table );
        
                    }
                });
            });
        });
    
    
        /*
        * Search for a specific query string
        * Look for params on the url from ? and also the hash
        * Then check each parameter and split in on the equal sign
        * Using indexOf is the position of the character which represents the key/value
        * Having it split check whether the parameter has a value or not, if it has then store the value of d, if not 
        * just continue
        */
        $.QueryString = (function(a) {
            if (a == "") return {};
            var b = {};
            for (var i = 0; i < a.length; ++i)
            {
                var p=a[i].split('=');
                if (p.length != 2) continue;
                b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
            }
            return b;
        })(window.location.search.substr(1).split('&'))
    You can see that currently the $.QueryString object is used to get the url paramters. This object works fine when one creates url parameters from the get go.

    The links that get build from the first time a user searches are like:
    HTML Code:
    <a href="http://myproj/test-elastic-ajax-call.php#?f=4">4, </a>

    I'm thinking this may have something to do with the links being constructed 'on live'; like the links that could not be clicked until i bound the events using 'on'.

    Your thoughts on why the parameter can not be found even though clicking on the link shows the url + parameter and the click event fires.

    Thanks,
    Steve
    ictus==""

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,402
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    Hi Steve,

    Quote Originally Posted by ServerStorm View Post
    The links that get build from the first time a user searches are like:
    HTML Code:
    <a href="http://myproj/test-elastic-ajax-call.php#?f=4">4, </a>
    The problem with this link is the # character. The browser treats anything that follows as a fragment and doesn't pass it through to the server. If you remove it, f should be correctly passed to the server as part of the query string:
    HTML Code:
    <a href="http://myproj/test-elastic-ajax-call.php?f=4">4,</a>

  3. #3
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    Hi fretburner,

    For some reason I need the # for the
    Code:
     jquery $('a#bn_search').click(function(event)
    event to fire; this is on the search button, ie
    HTML Code:
    <form>
        <input id='terms' type='text'> </input>        
        <a href='#' id='bn_search'>Search</a>   
    </form>
    If i don't have it there then the jquery event does not fire. I also tried this with the
    Code:
     $("body").on("click", "a#bn_search", function(event)
    and also tried using the 'on' event binding on a span like
    Code:
    $("body").on("click", "#bn_search", function(event)
    but the event did not fire in either case?

    The link that is built uses the base url and then appends the url parameter so I could regex replace the '#' before appending the parameter but this seems like I should not have to do this?

    Regards,
    Steve
    Quote Originally Posted by fretburner View Post
    Hi Steve,

    The problem with this link is the # character. The browser treats anything that follows as a fragment and doesn't pass it through to the server. If you remove it, f should be correctly passed to the server as part of the query string:
    HTML Code:
    <a href="http://myproj/test-elastic-ajax-call.php?f=4">4,</a>
    ictus==""

  4. #4
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,402
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    Is the page online somewhere you could link to? Or could you share the code for the whole page? It would be easier to see what's going on.

  5. #5
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    Hi

    Since I posted the question the search widget was sent to me from the front-end team so the search has been changed to:

    HTML Code:
    <form>
         <div class="search" id="header-search">
             <input id='terms' type="text" value="Search" />
             <button class="search-button">Search</button>
        </div>
    </form>
    This doesn't fire the event either. This is just a test page so it is very light on validation so I don't want any reader to think this is polished code, so here is the full page:

    HTML Code:
    <!DOCTYPE HTML>
    <html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){
            
            
            $('.search-button').click(function(event) { 
                var terms = $('#terms').val();
        
                $.ajax({
                    type: "POST",
                    url: 'do-search.php',
                    data: {
                            term: terms       
                    },
                    success: function( data ) {
                        console.log('success');
                
                        console.log( data );
                        
                        var term = '<h2>' + data['term'] + '</h2>';
                        var color = '<span style="display: block; width: 200px; height: 20px; background-color: ' + data['color'] + ';" ></span>';
    
    
                        var raw_results =  data['results'];
    
    
                        var table = '<table>';
                        var table_header = '<tr>';
                        table_header = table_header + '<th>ID</th>';
                        table_header = table_header + '<th>Abstract</th>';
                        table_header = table_header + '<th>Post</th>';
                        table_header = table_header + '<th>Copyright</th>';
                        table_header = table_header + '<th>Creation Date</th>';
                        table_header = table_header + '<th>Make</th>';
                        table_header = table_header + '<th>Tags</th>';
                        table_header = table_header + '</tr>';
                        var undefined = '<td>--</td>';
                        var table_body = '';
                        var tags = '';
                        for ( var key in raw_results ) {
                            table_body = table_body + '<tr>';
                            table_body = table_body + '<td>' + raw_results[key].id + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].abstract + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].body + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].copyright + '</td>';
                            
                            var date = new Date( raw_results[key].created * 1000 );
                            table_body = table_body + '<td>' + date + '</td>';
    
    
                            if( typeof raw_results[key].make == 'undefined' ) {
                                table_body = table_body + undefined;
                            } else {
                                table_body = table_body + '<td>' + raw_results[key].make + '</td>';
                            }
    
    
                            if( raw_results[key].tags ) {
                                
                                table_body = table_body + '<td>';
                                
                                var count = raw_results[key].tags.length;
                                
                                var i = 1;
                                for( var inner_key in raw_results[key].tags ) {
                                    
                                    if( i < count ) {
    
    
                                        tags = tags + raw_results[key].tags[inner_key] + ', ';
                                        
                                    } else {
    
    
                                        tags = tags + raw_results[key].tags[inner_key];
    
    
                                    }
                                    i++;
                                    
                                    
                                    table_body = table_body + tags;
                                    tags = '';
                                    
                                }
                                table_body = table_body + '</td>';    
                            }
                            
                            table_body = table_body + '</tr>';
                        }
                        table = table + table_header + table_body + '</table';
    
    
                        
                        
                    $('#hit_count').html( '<p>about ' + data['count'] +' results </p>');
                        $('#decor').html( color );
                        $('#title').html( term );
    
    
                        // Round down
                        var paging_groups = Math.floor( data['count'] / 10 );
                        var base_url = $(location).attr('href');
                        var f = $.QueryString['f'];
                        if ( typeof f == 'undefined' ) {
                            if ( paging_groups > 10 ) {
                                var paging_links = '<ul id="paged_results">';
                                for( i = 1; i <=10; i++ ) {
                                    paging_links = paging_links + '<li>';
                                    paging_links = paging_links + '<a href="' + base_url + '?f=' + i + '">' + i + ', </a>';
                                    paging_links = paging_links + '</li>';
                                }
                            }
                            paging_links = paging_links + '</ul>';
                            $('#paging').html( paging_links );
                        }
    
    
                        
                        $('#results').html ( table );
                        
                       
                       
                    }
                });
            });
            
            $("body").on("click", "#paged_results a", function(event){
                
                var terms = $('#terms').val();
                var f = $.QueryString["f"];
                var url = this.href;
                
                console.log('clicked '+ f);
                $.ajax({
                    type: "POST",
                    url: 'do-search.php',
                    data: {
                            term: terms
                            , from_record: f
                    },  
                    success: function( data ) {
                        console.log('success');
                
                        console.log( data );
                        
                        var term = '<h2>' + data['term'] + '</h2>';
                        var color = '<span style="display: block; width: 200px; height: 20px; background-color: ' + data['color'] + ';" ></span>';
                        var raw_results =  data['results'];
    
    
                        var table = '<table>';
                        var table_header = '<tr>';
                        table_header = table_header + '<th>ID</th>';
                        table_header = table_header + '<th>Abstract</th>';
                        table_header = table_header + '<th>Post</th>';
                        table_header = table_header + '<th>Copyright</th>';
                        table_header = table_header + '<th>Creation Date</th>';
                        table_header = table_header + '<th>Make</th>';
                        table_header = table_header + '<th>Tags</th>';
                        table_header = table_header + '</tr>';
                        var undefined = '<td>--</td>';
                        var table_body = '';
                        var tags = '';
                        for ( var key in raw_results ) {
                            table_body = table_body + '<tr>';
                            table_body = table_body + '<td>' + raw_results[key].id + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].abstract + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].body + '</td>';
                            table_body = table_body + '<td>' + raw_results[key].copyright + '</td>';
                            
                            var date = new Date( raw_results[key].created * 1000 );
                            table_body = table_body + '<td>' + date + '</td>';
    
    
                            if( typeof raw_results[key].make == 'undefined' ) {
                                table_body = table_body + undefined;
                            } else {
                                table_body = table_body + '<td>' + raw_results[key].make + '</td>';
                            }
    
    
                            if( raw_results[key].tags ) {
                                
                                table_body = table_body + '<td>';
                                
                                var count = raw_results[key].tags.length;
                                
                                var i = 1;
                                for( var inner_key in raw_results[key].tags ) {
                                    
                                    if( i < count ) {
                                        //console.log( 'i: ' + i + ' count: ' + count);
                                        tags = tags + raw_results[key].tags[inner_key] + ', ';
                                        //console.log(tags);
                                        
                                    } else {
                                        //console.log( 'i: ' + i + ' count: ' + count);
                                        tags = tags + raw_results[key].tags[inner_key];
                                        //console.log(tags);
                                    }
                                    i++;
                                    
                                    
                                    table_body = table_body + tags;
                                    tags = '';
                                    
                                }
                                table_body = table_body + '</td>';    
                            }
                            
                            table_body = table_body + '</tr>';
                        }
                        table = table + table_header + table_body + '</table';
    
    
                        
                        
                        $('#hit_count').html( '<p>about ' + data['count'] +' results </p>');
                        $('#decor').html( color );
                        $('#title').html( term );
    
    
                        // Round down
                        var paging_groups = Math.floor( data['count'] / 10 );
                        var base_url = $(location).attr('href');
                        var f = $.QueryString['f'];
                        if ( typeof f != 'undefined' ) {
                            if ( paging_groups > 10 ) {
                                var paging_links = '<ul id="paged_results" >';
                                for( i = f; i <=10; i++ ) {
                                    paging_links = paging_links + '<li>';
                                    paging_links = paging_links + '<a href="' + base_url + '?f=' + i + '">' + i + ', </a>';
                                    paging_links = paging_links + '</li>';
                                }
                            }
                            paging_links = paging_links + '</ul>';
                            $('#paging').html( paging_links );
                        }
    
    
                        
                        $('#results').html ( table );
                        
                       
                       
                    }
                });
            });
        });
    
    
        /*
        * Search for a specific query string
        * Look for params on the url from ? and also the hash
        * Then check each parameter and split in on the equal sign
        * Using indexOf is the position of the character which represents the key/value
        * Having it split check whether the parameter has a value or not, if it has then store the value of d, if not 
        * just continue
        */
        $.QueryString = (function(a) {
            if (a == "") return {};
            var b = {};
            for (var i = 0; i < a.length; ++i)
            {
                var p=a[i].split('=');
                if (p.length != 2) continue;
                b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
            }
            return b;
        })(window.location.search.substr(1).split('&'))
        
        </script>
        <style>
            table { width: 100%; }
            td { border: 1px dotted #666; padding: 5px;}
            .search-button { background-color: yellow; }
        </style>
    </head>
    <body>
        <form>
            <div class="search" id="header-search">
                <input id='terms' type="text" value="Search" />
                <button class="search-button">Search</button>
            </div>
        </form>
        <div id='title'></div>
        <div id='decor'></div>
        <div id='hit_count'></div>
        <div id='results'></div>
        <div id='paging'></div>
    </body>
    </html>
    ictus==""

  6. #6
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,402
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    Hi Steve,

    Try changing this line:
    Code JavaScript:
    var base_url = $(location).attr('href');
    to this:
    Code JavaScript:
    var base_url = location.pathname;

    Getting the pathname will return /test-elastic-ajax-call.php rather than http://myproj/test-elastic-ajax-call.php#, which will avoid your script from building incorrect URLs. Note that you don't need to use jQuery for this, as it's straightforward to do with plain JS.

    The second thing you should do is prevent the default action where you're using click events, here:
    Code JavaScript:
    $('.search-button').click(function(event) {
        event.preventDefault(); // Prevent button from submitting form

    and here:
    Code JavaScript:
    $("body").on("click", "#paged_results a", function(event){
        event.preventDefault();

  7. #7
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    @fretburner ; thank you as using this fixed the problem without even needing to use the '#'. I also did add the prevent default as suggested... Many Regards!

    Steve
    ictus==""


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •