Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5

Thread: Ajax search

  1. #1
    brk
    brk is offline
    New to the CF scene
    Join Date
    Mar 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Ajax search

    Hello,

    I want to implement a search function on my website which would retrieve results from my DB.

    I would want to add two search inputs and I would want to get results after the second input is filled.

    Here is an example of what I am talking about:
    Check http://fany.ro
    In the upper part, right side, you can see two fields Localitatea de plecare and Localitatea de Sosire. Fill Localitatea de plecare with Oradea and fill Localitatea de sosire with Sacuieni. After you fill the second field you are redirected automatically to the results page, without clicking on anything.

    There are two .js files for Localitatea de plecare and Localitatea de sosire. However I am not sure how to make the connections with the DB... Help would be appreciated.

    Here are the two .js files I am talking about

    this is for Plecari

    Code:
    var departureRequest;var departureResult=null;var dstDepartureObj=null;var departureSelectedValue=null;var departureIndex=-1;var departureOk=false;var departureInput=null;var departureSrollVisible=false;var thread=null;function departureIn(){document.getElementById('la').value='';departureInput=document.getElementById('dela');if(departureInput.value!=''){if(thread!=null)
    clearTimeout(thread);thread=setTimeout('doDepartureRequest()',300);}}
    function departureOut(){clearTimeout(thread);hideDepartures();}
    function departureKeyUp(key){departureInput=document.getElementById('dela');if(departureInput.value==''){clearTimeout(thread);hideDepartures();return;}
    if((key==9)||(key==13)||(key==38)||(key==40)||(key==16))
    return true;if(thread!=null)
    clearTimeout(thread);thread=setTimeout('doDepartureRequest()',300);}
    function departureKeyDown(key){departureInput=document.getElementById('dela');dstDepartureObj=document.getElementById('plecari')
    if(departureInput.value==''){clearTimeout(thread);hideDepartures();}
    if((key==9)&&(departureSelectedValue!=null)&&(departureOk)){departureInput.value=departureSelectedValue;hideDepartures();}
    if((key==13)&&(departureSelectedValue!=null)&&(departureOk)){departureInput.value=departureSelectedValue;hideDepartures();}
    if(!departureSrollVisible)
    return true;if(key==38){if(departureIndex>0){departureIndex--;showDepartures();buildDepartureTable();}
    return true;}
    if(key==40){if(departureIndex<departureResult.departures.length-1){departureIndex++;showDepartures();buildDepartureTable();}
    return true;}}
    function doDepartureRequest(){if(departureInput.value=='')
    return;try{if(window.XMLHttpRequest)
    departureRequest=new XMLHttpRequest();else
    if(window.ActiveXObject)
    departureRequest=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){return false;}
    departureRequest.onreadystatechange=waitDepartureResponse;departureRequest.open('GET','getplecari.php?'+departureInput.name+'='+replaceDiacritics(townMatch(departureInput.value)),true);departureRequest.send('');return true;}
    function waitDepartureResponse(){if(departureRequest.readyState==4){if(departureRequest.status==200){departureResult=eval('('+departureRequest.responseText+')');if(departureResult.departures.length==0){departureResult.departures[0]='Localitate invalidă!'
    departureOk=false;}
    else{departureOk=true;}
    departureIndex=0;if(!((departureInput.value=='')||((replaceDiacritics(townMatch(departureInput.value.toLowerCase()))==replaceDiacritics(departureResult.departures[0].toLowerCase()))&&(departureResult.departures.length==1)))){showDepartures();buildDepartureTable();}
    if((replaceDiacritics(townMatch(departureInput.value.toLowerCase()))==replaceDiacritics(departureResult.departures[0].toLowerCase()))&&(departureResult.departures.length==1))
    hideDepartures();}}}
    function showDepartures(){if(dstDepartureObj==null)
    return;dstDepartureObj.style.top='57px';dstDepartureObj.style.left=$('#dela').offset().left+'px';dstDepartureObj.style.visibility='visible';dstDepartureObj.style.display='inline';departureSrollVisible=true;}
    function hideDepartures(){if(dstDepartureObj==null)
    return;while(dstDepartureObj.rows.length>0)
    dstDepartureObj.deleteRow(0);dstDepartureObj.style.visibility='hidden';dstDepartureObj.style.display='none';departureSrollVisible=false;departureSelectedValue=null;}
    function selectDepartureTableItem(){var color;if(departureOk)
    color='#14a143';else
    color='red';for(var i=0;i<dstDepartureObj.rows.length;i++){var row=dstDepartureObj.rows[i];var cell=row.cells[0];if(i==departureIndex){cell.style.color='white';cell.style.backgroundColor=color;departureSelectedValue=departureResult.departures[i];}
    else{cell.style.color='#666666';cell.style.backgroundColor='white';}}}
    function getDepartureTableItemIndex(cell){for(var i=0;i<dstDepartureObj.rows.length;i++){var row=dstDepartureObj.rows[i];if(row.cells[0]==cell)
    return i;}}
    function buildDepartureTable(){while(dstDepartureObj.rows.length>0)
    dstDepartureObj.deleteRow(0);for(var i=0;i<departureResult.departures.length;i++){var row=dstDepartureObj.insertRow(i);var cell=row.insertCell(0);cell.innerHTML=departureResult.departures[i];cell.onmousemove=function(){departureIndex=getDepartureTableItemIndex(this);selectDepartureTableItem();}
    cell.onmousedown=function(){departureIndex=getDepartureTableItemIndex(this);selectDepartureTableItem();if(departureOk)
    departureInput.value=departureSelectedValue;hideDepartures();}}
    selectDepartureTableItem();}// JavaScript Document
    and (this is for Sosiri)

    Code:
    var arrivalRequest;
    var arrivalResult = null;
    var dstArrivalObj = null;
    var arrivalIndex = -1;
    var arrivalSelectedValue = null;
    var arrivalOk = false;
    var arrivalInput = null;
    var arrivalSrollVisible = false;
    
    var finalDeparture = null;
    var finalArrival = null;
    
    var finalRequest;
    
    function arrivalIn() {
        dstArrivalObj = document.getElementById('plecari');
        clearTimeout(thread);
        hideDepartures();
    
        // daca e scris ceva in inputul de sosiri in momentul in care ia focusul lansam thread-ul
        arrivalInput = document.getElementById('la');
        if (arrivalInput.value != '') {
            if (thread != null)
              clearTimeout(thread);
            thread = setTimeout('doArrivalRequest()', 300);
        }
    
    }
    function arrivalOut() {
        clearTimeout(thread);
        hideArrivals();
    }
    
    function arivalKeyUp(key) {
        hideDepartures();
        arrivalInput = document.getElementById('la');
        if (arrivalInput.value == '') {// daca e vid anulam call-ul si ascundem meniul
            clearTimeout(thread);
            hideArrivals();
            return;
        }
    
        if ((key == 9) || (key == 13) || (key == 38) || (key == 40) || (key == 16))
        // tab, enter, sageata sus, sageata jos, shift
          return true;
        if (thread != null)
          clearTimeout(thread);
        thread = setTimeout('doArrivalRequest()', 300);
    }
    
    function arrivalKeyDown(key) {
        hideDepartures();
        arrivalInput = document.getElementById('la');
        dstArrivalObj = document.getElementById('sosiri');
    
        if (arrivalInput.value == '') {// daca e vid anulam call-ul si ascundem meniul
            clearTimeout(thread);
            hideArrivals();
        }
        
        if ((key == 9) && (arrivalSelectedValue != null) && (arrivalOk)) {
                arrivalInput.value = arrivalSelectedValue;
                hideArrivals();
                finish();
        }
    
        if ((key == 13) && (arrivalSelectedValue != null) && (arrivalOk)) {
                arrivalInput.value = arrivalSelectedValue;
                hideArrivals();
                finish();
        }
    
        // daca meniul nu este vizibil nu tinem cont de sageata sus si sageata jos
        if (! arrivalSrollVisible)
            return true;
    
    
        if (key == 38) {
            if (arrivalIndex > 0) {
                arrivalIndex--;
                showArrivals();
                buildArrivalTable();
            }
            return true;
        }
    
        if (key == 40) {
            if (arrivalIndex < arrivalResult.arrivals.length - 1) {
                arrivalIndex++;
                showArrivals();
                buildArrivalTable();
            }
            return true;
        }
    }
    
    function doArrivalRequest() {
    
      if (arrivalInput.value == '') // daca e vid nu face call-ul
        return;
    
      departureInput = document.getElementById('dela');
    
      try {
        if (window.XMLHttpRequest)
            arrivalRequest = new XMLHttpRequest();
        else
            if (window.ActiveXObject)
              arrivalRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
          return false;
      }
    
    
      arrivalRequest.onreadystatechange = waitArrivalResponse;
      arrivalRequest.open('GET', 'getsosiri.php?' + departureInput.name + '=' + replaceDiacritics(townMatch(departureInput.value)) + '&' + arrivalInput.name + '=' + replaceDiacritics(townMatch(arrivalInput.value)), true);
      arrivalRequest.send('');
      return true;
    }
    
    function waitArrivalResponse() {
      if (arrivalRequest.readyState == 4) {
        if (arrivalRequest.status == 200) {
            arrivalResult = eval('(' + arrivalRequest.responseText + ')');
    
            if (arrivalResult.arrivals.length == 0) {
                arrivalResult.arrivals[0] = 'Nici o cursă găsită!'
                arrivalOk = false;
            }
            else {
                arrivalOk = true;
            }
            arrivalIndex = 0;
            if (!((arrivalInput.value == '') || ((replaceDiacritics(townMatch(arrivalInput.value.toLowerCase())) == replaceDiacritics(arrivalResult.arrivals[0].toLowerCase())) && (arrivalResult.arrivals.length == 1)))) {
                showArrivals();
                buildArrivalTable();
            }
            // un singur raspuns, match perfect pe user input
            if ((replaceDiacritics(townMatch(arrivalInput.value.toLowerCase())) == replaceDiacritics(arrivalResult.arrivals[0].toLowerCase())) && (arrivalResult.arrivals.length == 1)) {
                hideArrivals();
                finish();
            }
    
        }
      }
    }
    
    function showArrivals() {
        if (dstArrivalObj == null)
            return;
        dstArrivalObj.style.top = '81px';
        dstArrivalObj.style.left = $('#la').offset().left + 'px';
        dstArrivalObj.style.visibility = 'visible';
        dstArrivalObj.style.display = 'inline';
        arrivalSrollVisible = true;
    }
    
    function hideArrivals() {
        if (dstArrivalObj == null)
            return;
        while (dstArrivalObj.rows.length > 0)
            dstArrivalObj.deleteRow(0);    
        dstArrivalObj.style.visibility = 'hidden';
        dstArrivalObj.style.display = 'none';
        arrivalSrollVisible = false;
        arrivalSelectedValue = null;
    }
    
    function selectArrivalTableItem() {
        var color;
        if (arrivalOk)
          color = '#14a143';
        else
          color = 'red';
        for (var i = 0; i < dstArrivalObj.rows.length; i++) {
            var row = dstArrivalObj.rows[i];
            var cell = row.cells[0];
            if (i == arrivalIndex) {
                cell.style.color = 'white';
                cell.style.backgroundColor = color;
                arrivalSelectedValue = arrivalResult.arrivals[i];
            }
            else {
                cell.style.color = '#666666';
                cell.style.backgroundColor = 'white';
            }
        }
    }
    
    function getArrivalTableItemIndex(cell) {
        for (var i = 0; i < dstArrivalObj.rows.length; i++) {
            var row = dstArrivalObj.rows[i];
            if (row.cells[0] == cell)
                return i;
        }
    }
    
    function buildArrivalTable() {
        while (dstArrivalObj.rows.length > 0)
            dstArrivalObj.deleteRow(0);
    
        if (arrivalResult == null)
          return;
    
        for (var i = 0; i < arrivalResult.arrivals.length; i++) {
            var row = dstArrivalObj.insertRow(i);
            var cell = row.insertCell(0);
            cell.innerHTML = arrivalResult.arrivals[i];
            cell.onmousemove = function() {
                arrivalIndex = getArrivalTableItemIndex(this);
                selectArrivalTableItem();
            }
            cell.onmousedown = function() {
                arrivalIndex = getArrivalTableItemIndex(this);
                selectArrivalTableItem();
                if (arrivalOk) {
                     arrivalInput.value = arrivalSelectedValue;
                     finish();
                }
                hideArrivals();
            }
        }
        selectArrivalTableItem();    
    }
    
    function finish() {
        try {
            if (window.XMLHttpRequest)
                finalRequest = new XMLHttpRequest();
            else
                if (window.ActiveXObject)
                    finalRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          return false;
        }
    
        finalDeparture = townNameFormat(townMatch(replaceDiacritics(departureInput.value)));
        finalArrival = townNameFormat(townMatch(replaceDiacritics(arrivalInput.value)));
        finalRequest.onreadystatechange = doFinalRequest;    
        finalRequest.open('GET', 'autocare.php?nmp=1&dela=' + finalDeparture  + '&la=' +  finalArrival, true);
        finalRequest.send('');
        
        return true;
    }
    
    function doFinalRequest() {
        if (finalRequest.readyState == 4) {
          if (finalRequest.status == 200) {
            var content = document.getElementById('content');
            content.innerHTML = finalRequest.responseText;
            document.title = 'Orarul curselor FANY de la ' + finalDeparture +  ' la ' + finalArrival;
              
            var urlDeparture = finalDeparture.replace(/-/g, ' ');
            var urlArrival = finalArrival.replace(/-/g, ' ');
            var ajax_url = '/autocare-' + urlDeparture + '-' + urlArrival;
            var pageTracker = _gat._getTracker('UA-9627298-1');
            pageTracker._trackPageview(ajax_url);
    
            // +1 code
            var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
            po.src = 'https://apis.google.com/js/plusone.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
          }
        }
    }

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,189
    Thanks
    10
    Thanked 569 Times in 550 Posts
    you need to use a server-side technology (php, asp, etc) to query the db and return the results as text upon a url that JS can grab using ajax.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #3
    brk
    brk is offline
    New to the CF scene
    Join Date
    Mar 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks for your response. Do you know any tutorials for the thing I want to do? Would be helpful...

  • #4
    Banned
    Join Date
    Mar 2013
    Posts
    139
    Thanks
    0
    Thanked 9 Times in 9 Posts
    Quote Originally Posted by brk View Post
    After you fill the second field you are redirected automatically to the results page, without clicking on anything.
    In this case, you need AJAX.

    Here is a good tutorial to get you started.

    Add an onchange event handler to your 2nd input to send the AJAX to the server which will then get and return the requested data to your results page.

  • Users who have thanked knightCoder for this post:

    brk (03-31-2013)

  • #5
    brk
    brk is offline
    New to the CF scene
    Join Date
    Mar 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Many thanks for this. I will follow the tutorial and I will be back :-)


  •  

    Tags for this Thread

    Posting Permissions

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