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 7 of 7
  1. #1
    New Coder
    Join Date
    Jul 2012
    Location
    Boston
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Pure JavaScript AJAX Search with JSON

    I'm basically brand new to JS but I have been working on this script all week and can't get the JS to work...

    Please help me understand why my text input does not POST its value to parser.php. The PHP file has been tested and gathers/echoes JSON data perfectly from any search input with a post action. I cannot get this JS function to send my searchquery data to my parser.php. I'm sure its a basic issue.

    Code:
    function ajax_call(){
        var results = document.getElementById("results");
        var sr = document.getElementById("searchquery").value;
        var params = "searchquery="+sr;
    
        var hr = new XMLHttpRequest();
        hr.open("POST", "parser.php", true);
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
        hr.onreadystatechange = function() {
    	    if(hr.readyState == 4 && hr.results == 200) {
    		    var return_data = hr.responseText;
    			document.getElementById("results").innerHTML = return_data;
    	    }
        }
        // Send the data to PHP now... and wait for response to update the results div
        hr.send(params); 
        document.getElementById("results").innerHTML = "processing...";
    }
    The HTML:

    Code:
    <form>
    	<input name="searchquery" type="text" id="searchquery" size="40" maxlength="" placeholder="<?php if (isset($_POST['searchquery'])){echo $_POST['searchquery'];} ?>" size=50 speech x-webkit-speech>
    	<input name="button" type="submit" id="searchbut" onClick="javascript:ajax_call();">
    </form>
    The PHP

    Code:
    $searchquery = $_POST['searchquery'];
    
    mainquery($searchquery);
    
    function mainquery($query){
    
    	$PDO = new PDO("mysql:host=localhost;dbname=searchdb", "root", "");
    
    	$sql = 'SELECT *
    			FROM results
    			WHERE title LIKE :searchquery
    			ORDER BY date DESC';
    
    	$datas = $PDO->prepare($sql);
    	$datas->execute(array(':searchquery' => $query . '%'));
    
    	$resultset = $datas->fetchALL(PDO::FETCH_OBJ);
    	$results = json_encode($resultset);
    // return $results;
    echo $results;
    }
    Last edited by Webenvelopment; 06-01-2013 at 12:31 AM.

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,175
    Thanks
    23
    Thanked 601 Times in 600 Posts
    I tried to mark all my changes in the ajax call function:
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function ajax_call(){
    	var sr = document.getElementById("searchquery").value;
    	var params = "searchquery="+sr;
    
    	var hr = new XMLHttpRequest();
    
    	hr.onreadystatechange = function() {
    		if(hr.readyState == 4 && hr.status == 200) {
    			var return_data = hr.responseText;
    			document.getElementById("searchquery").value = return_data;
    		}
    	}
    
    	hr.open("POST", "parser.php", true);
    	hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	// Send the data to PHP now... and wait for response to update the results div
    	hr.send(params);
    	document.getElementById("searchquery").value = "processing...";
    }
    </script>
    </head>
    <body>
    <form>
    	<input name="searchquery" type="text" id="searchquery" size="40" maxlength="" placeholder="Enter Query" size=50 speech x-webkit-speech>
    	<input name="button" type="button" id="searchbut" onClick="javascript:ajax_call();">
    </form>
    </body>
    </html>
    Your php is sending back a lot of stuff -- probably cause I don't have your DB. So you'll have to check that yourself
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #3
    New Coder
    Join Date
    Jul 2012
    Location
    Boston
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Thank you!

    Your advice made the script call to the PHP file. My code was a bit off but nonetheless I could figure it out once I had your fixes, so thank you. The only problem now is that the form field input[text] refreshes the page on enter and submits blank when the enter key is pressed and only sends the search query data when the button triggers "onclick".

    What would you do to get the field to submit also?
    I'm playing around with the onkeyup code below but could use some advice...

    Code:
    onkeyup="if (event.keyCode == 13) document.getElementById('searchbut').click()"
    Ah my first JavaScript!

    UPDATE:
    Code:
    <form onsubmit="return false;">
    <input name="searchquery" type="text" id="searchquery" onkeyup="if (event.keyCode == 13) document.getElementById('searchbut').click()">
    <input name="searchbut" type="button" id="searchbut" value="Search" onclick="searchFunc();">
    </form>
    Combining both of these JS's did the trick... Now the enter button when typing within the form submits the data to my AJAX function as does clicking the actual button.
    I'm guessing that onsubmit="return false;" kills the default submission method? (which is the enter button)
    Last edited by Webenvelopment; 06-02-2013 at 03:00 AM.

  • #4
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,175
    Thanks
    23
    Thanked 601 Times in 600 Posts
    I don't understand
    The only problem now is that the form field input[text] refreshes the page on enter
    by 'enter' do you mean the 'enter key'? OR clicking into the input field to type? Neither one causes a refresh for me.

    If you want to have the 'enter key' run your ajax you have to put a listener in your JS to monitor for this.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #5
    New Coder
    Join Date
    Jul 2012
    Location
    Boston
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Yes, sorry if I wasn't specific. Enter button pressed while typing within the field was creating a page refresh... Strange that you didn't replicate it...

    Here was my solution:
    Code:
    onkeyup="if (event.keyCode == 13) document.getElementById('searchbut').click()"
    like this:
    Code:
    <input name="searchquery" type="text" id="searchquery" autocomplete="true" onkeyup="if (event.keyCode == 13) document.getElementById('searchbut').click()" >
    <input name="searchbut" type="button" id="searchbut" value="Search" onclick="searchFunc();">
    I will look around to understand listeners due to your advice. Thanks!

  • #6
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts
    Quote Originally Posted by Webenvelopment View Post
    Enter button pressed while typing within the field was creating a page refresh...
    It was because you were having a button of type "Submit" within your FORM.

    Its the default functionality available in HTML FORM having a "button type=submi t" to be submitted when ENTER KEY pressed.

    It didn't replicated because the button type was changed to "button".

    No need to handle the keyup event.

  • #7
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,175
    Thanks
    23
    Thanked 601 Times in 600 Posts
    Sorry I didn't get back sooner Webenvelopment. Try this see if you can live with it. Added thing highlighted.

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function runScript(e) {
    	if (e.keyCode == 13) {
    	ajax_call();
        }
    }
    
    function ajax_call(){alert('here');die;
    	var sr = document.getElementById("searchquery").value;
    	var params = "searchquery="+sr;
    
    	var hr = new XMLHttpRequest();
    
    	hr.onreadystatechange = function() {
    		if(hr.readyState == 4 && hr.status == 200) {
    			var return_data = hr.responseText;
    			document.getElementById("searchquery").value = return_data;
    		}
    	}
    
    	hr.open("POST", "parser.php", true);
    	hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    	// Send the data to PHP now... and wait for response to update the results div
    	hr.send(params);
    	document.getElementById("searchquery").value = "processing...";
    }
    </script>
    </head>
    <body>
    <form>
    	<input name="searchquery" type="text" id="searchquery" size="40" maxlength="" placeholder="Enter Query" onkeypress="return runScript(event)">
    	<input name="button" type="button" id="searchbut" onClick="javascript:ajax_call();">
    </form>
    </body>
    </html>
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."


  •  

    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
    •