Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

.click(function [PHP] [JavaScript]

Newbie Spellweaver
Joined
Aug 11, 2014
Messages
7
Reaction score
0
Hello,

So i have been struggling for a while and i dont really think i can get this to work on my own, so here is a cry for help.

I've been busy with trying to make a search bar that will display the name and when you click on the desired result you get to that (dynamic) page.

What i've got working so far with alot of copy and paste and tutorials from the internet is..
The search bar actually see the name's in the database. You can click on it but then the trouble begins.

It will redirect you to item.php?id= how to put the 'id' in there that is combined to the name you searched for. i'll first post some code, and then explain what i think i need to do but cant figure out.

There is a input text field on the html page thats all fine with the id=keyword

if (!isset($_GET['keyword'])) {
die();
}


$keyword = $_GET['keyword'];
$data = searchForKeyword($keyword);
echo json_encode($data);


function searchForKeyword($keyword) {
$db = getDbConnection();
$stmt = $db->prepare("SELECT name, id FROM `items` WHERE name LIKE ? ORDER BY name");

$keyword = $keyword . '%';
$stmt->bindParam(1, $keyword, PDO::pARAM_STR, 100);


$isQueryOk = $stmt->execute();

$results = array();

if ($isQueryOk) {
$results = $stmt->fetchAll(PDO::FETCH_COLUMN);
} else {
trigger_error('Error executing statement.', E_USER_ERROR);
}


$db = null;


return $results;
}

And then we have the .js

var MIN_LENGTH = 3;


$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "auto-complete.php", { keyword: keyword } )
.done(function( data ) {
$('#results').html('');
var results = jQuery.parseJSON(data);
$(results).each(function(key, value) {
$('#results').append('<div class="item">' + value + '</div>');
})


$('.item').click(function() { window.location = "../item.php?id=";
var text = $(this).html();
$('#keyword').val(text);

})


});
} else {
$('#results').html('');
}
});


$("#keyword").blur(function(){
$("#results").fadeOut(500);
})
.focus(function() {
$("#results").show();
});


});

Column 0 = id - INT AI
Column 1 = name - VACHAR

First what i think i need to do but also cant figure out is give the id a variable so i can ask for that in my javascript?

And then i need to add here
$('.item').click(function() { window.location = "../item.php?id=" + $('#keyword').val($id);
Or something like that? sorry for any typo's its kinda late and this is kinda driving me crazy.


Be aware this is one of my first times using any sort of code in this case php etc.. I'd love to know what im doing wrong but keep it polite, since i know this maybe can be done better by a 7 year old. Also there are a few lines that i dont understand yet, even not a bit. But im working on that.
 
CPP/C#/PHP/ASM
Joined
Apr 7, 2009
Messages
452
Reaction score
189
well.. here is a working example (easy to understand..) , use it as referance :

index.php
PHP:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" /> 
</head>
<body> 

    <form action='' method='post'>
        <p><label>Country:</label><input type='text' name='country' value='' class='auto'></p>
    </form>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>    
<script type="text/javascript">
$(function() {
    
    //autocomplete
    $(".auto").autocomplete({
        source: "search.php",
        minLength: 1
    });                

});
</script>
</body>
</html>


search.php
PHP:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'username');
define('DB_PASSWORD', 'password');
define('DB_NAME', 'database name');


if (isset($_GET['term'])){
    $return_arr = array();

    try {
        $conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $conn->prepare('SELECT country FROM countries WHERE country LIKE :term');
        $stmt->execute(array('term' => '%'.$_GET['term'].'%'));
        
        while($row = $stmt->fetch()) {
            $return_arr[] =  $row['country'];
        }

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }


    /* Toss back results as json encoded array. */
    echo json_encode($return_arr);
}


?>
 
Last edited:
Watching from above
Legend
Joined
Apr 9, 2004
Messages
3,828
Reaction score
752
Code:
$('.item').click(function() {
   window.location = "../item.php?id=";
   var text = $(this).html();
If the text var contains the selected text, you already have everything you need. Just concatenate it to the string you're setting as the new window.location

If however you need the id instead, you could for example save the id on the same element that holds each name string, into an attribute like data-id. You can then look it up in the click handler instead of the shown text.

Now this isn't a structure I'd use at all but it'll work for the code given.
 
Joined
Jun 8, 2007
Messages
1,985
Reaction score
490
Could this be resolved using simple HTML?
Code:
<form id="itemSelectForm"[B] method="get" action="../item.php"[/B]>
<input type="text" [B]name="id"[/B]>
<button>Search</button>
</form>
When the user clicks the search button, the form will submit to '../item.php?id=<text from the input>'. If your autocomplete already populates that input with the appropriate text, and you already have a way to handle $_GET['id'] in '../item.php', then this code is done, right?

Edit:
If you want the form to submit once an item is selected, then in your code for the autocomplete, submit the form. Give the form an ID attribute of, 'itemSelectForm' (for example), and use $('#itemSelectForm').submit() *after the 'id' input is populated with the appropriate value.

Code:
$('.item').click(function() {
    $([B]'#itemSelectForm [name="id"]'[/B]).val($(this).text());
    [B]$('#itemSelectForm').submit();[/B]
});

This code works better with JavaScript enabled, and works as expected (no auto-complete) when JavaScript is disabled. Then again, that was a good practice when targeting Windows '95 xD
 
Last edited:
Back
Top