in my project I have a problem with recive a data from database and send it to script.
main script file
<link rel="stylesheet" href="css/jquery-ui.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
...
<input type="text" class="form-control" name="startstation" placeholder="Stacja poczÄ…tkowa">
...
$( "input[name=startstation]" ).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'station.php',
dataType: "json",
data: {
q: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.name,
value: item.id
}
}));
}
});
},
minLength: 2
});
station.php
<?php
$connection = mysql_connect("localhost", "kilometry", "kilometry"); // Establishing Connection with Server..
$db = mysql_select_db("kilometry", $connection); // Selecting Database
//Fetching Values from URL
$q=$_GET["q"];
$sql="SELECT id, name FROM stations WHERE name LIKE '".$q."%' ORDER BY priority DESC";
$result = mysql_query($sql);
$options = array();
while ($row_id = mysql_fetch_array($result)) {
// more structure in data allows an easier processing
$options['myData'][] = array(
'name' => $row_id['name'],
'id' => $row_id['id']
);
}
mysql_close($connection);
echo json_encode($options);
?>
In dev tool script sends a Q value as parameter but in answer field I don't recive a answer: http://prntscr.com/fjo1gf
What is wrong? I think that is fail in while condition.
Related
I want it to be posted as an id in the field that users see, but when posting.
https://prnt.sc/z5Hw61LuKoGy -> the area the user sees
https://prnt.sc/plR-s1eb4OGE -> Id data sent with value tag in background
When I post like this, I see it as 0 in my database.
https://prnt.sc/XjPHKrthej2M
Why not 4?
Can you help me?
I am using jQuery UI Autocomplete.
MY JQUERY CODE
$("#urun_olustur .col-10 input").autocomplete({
source: function(request,response){
$.ajax({
url: 'ajax.php',
type: 'post',
dataType: 'json',
data: {
search: request.term
},
success: function(data){
response(data);
}
});
},
select: function(event,ui){
$(this).val(ui.item.label);
$(this).attr("value",ui.item.value);
return false;
}
});
MY AJAX.PHP CODE
if (isset($_POST["search"])) {
$search = $_POST["search"];
$query = $db->query("SELECT * FROM test WHERE test_name LIKE '%".$search."%'");
$response = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$response[] = array(
"value" => $row["id"],
"label" => $row["test_name"]
);
}
echo json_encode($response);
exit;
}
You can get like this I have add following snippet please check.
I have take the change event you can use any other required event as per your convenience
$("#ac_text_id").on('autocompletechange change', function() {
$('#ac_text_op').html('You selected: ' + this.value);
}).change();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control ui-autocomplete-input" name="ac_text" id="ac_text_id" autocomplete="off" value="4">
<div id="ac_text_op"></div>
I am trying to populate a drop down box depending which county has been selected the second drop down should populate with the provinces of the chosen county.
I don't understand why the second dropdown is not populating. I am getting a JSON response in the console so the PHP is correct. I am sure it is something silly but I just cant see it. Thanks in advance.
index.php page
<?php
include "config.php";
?>
<!doctype html>
<html>
<head>
<title>dropdown</title>
<link href="style.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery-1.12.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready( function () {
$( "#country" ).change( function () {
var countryid = $( this ).val();
$.ajax( {
url: 'getUsers.php',
type: 'POST',
data: {
countryid: countryid
},
dataType: 'json',
success: function ( response ) {
var len = response.length;
$( "#province" ).empty();
for ( var i = 0; i < len; i++ ) {
var id = response[ i ][ 'provinceid' ];
var name = response[ i ][ 'provincename' ];
$( "#province" ).append( "<option value='" + id + "'>" + name + "</option>" );
}
}
} );
} );
} );
</script>
</head>
<body>
<div>Country</div>
<select id="country">
<option value="0">- Select -</option>
<?php
// Fetch Country
$stmt = $conn->prepare('SELECT * FROM countries');
$stmt->execute();
while($countries = $stmt->fetch()) {
$countryid = $countries['id'];
$countryname_en = $countries['countryname_en'];
// Option
echo "<option value='".$countryid."' >".$countryname_en."</option>";
}
?>
</select>
<div class="clear"></div>
<div>Province</div>
<select id="province">
<option value="0">- Select -</option>
</select>
</body>
</html>
PHP
<?php
include "config.php";
var_dump($_POST);
$countryid = $_POST['countryid'];
$countryid = "CA";
$stmt = $conn->prepare('SELECT * FROM provincestates WHERE countryid = :countryid');
$stmt->execute(array(
':countryid' => $countryid
));
/*
echo "<pre>";
echo "prov is:" . $province_array = array();
echo "</pre>";
*/
while ($province = $stmt->fetch(PDO::FETCH_ASSOC)) {
$provinceid = $province['provincestatecode'];
$provincename = $province['provincestatename_en'];
$province_array[] = array(
"provinceid" => $provinceid,
"provincename" => $provincename
);
}
echo json_encode($province_array);
I'm not overly familiar wit jQuery but it seems you need to parse the response using JSON.parse ( or native jQuery method ? ) and then you ought to be able to access the data OK. The following might point you in the right direction - or it might not as it is not tested...
<script>
$( document ).ready( function () {
$( "#country" ).change( function () {
var countryid = $( this ).val();
$.ajax( {
url: 'getUsers.php',
type: 'POST',
data: {
countryid: countryid
},
dataType: 'json',
success: function ( response ) {
var json=JSON.parse( response ); /* PARSE the data */
$( "#province" ).empty();
for( var i in json ){/* access using object notation */
var obj=json[ i ];
var id=obj.provinceid;
var name=obj.provincename;
$( "#province" ).append( new Option(id,name) );
}
}
});
});
});
</script>
I finally got it:
Apparently JSON.parse is depreciated and I had to change it from var json=JSON.parse( response ); to just var response = response
Thanks for all your help!
I have this live search and it works perfectly. What i want to do is I want to get another field. Aside of fetching indcator name i also want to get its ID by assigning it to another input type once I clicked the indicatorname using live search.
Heres the Script :
<script type="text/javascript">
$(document).ready(function() {
$('#indicatorname').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'indicatorname'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
selectFirst: true,
minLength: 0,
focus : function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
select: function( event, ui ) {
$('#indicatorname').html(ui.item.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top");
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
$('#slider').rhinoslider({
effect: 'transfer'
});
});
</script>
Heres the ajax.php :
<?php
$connection = pg_connect("host=localhost dbname=brgy_profiler
user=postgres password=password");
if (!$connection)
{
echo "Couldn't make a connection!";
}
?>
<?php
if($_GET['type'] == 'indicatorname'){
$result = pg_query("SELECT cindicatordesc,nindicatorid from
tbl_indicators where cindicatordesc LIKE
'%".$_GET['name_startsWith']."%'");
$data = array();
while ($row = pg_fetch_array($result))
{
array_push($data, $row['cindicatordesc']);
}
echo json_encode($data);
}
?>
Here's my tbl_indicator :
How can i get also the nindicatorid field and get it together with cindicatordesc using ajax live search?
Note: Only cindicatordesc will be displayed and nindicatorid will be save in an input type.
Not a problem. You can add additional data attributes in your Auto-complete select return as,
$('#indicatorname').autocomplete({
source: function( request, response ) {
...........
success: function( data ) {
response( $.map( data, function( itemList ) {
return {
label: itemList.label,
value: itemList.value,
extraField : itemList.extraField
}
}));
So, Only change you need to accommodate is the Server side where you need to send the extra values to the Auto-complete AJAX.
And , On select event you can fetch the value as ui.item.extraField.
Here is a Sample Demo of using multiple attributes. Although it is not same as you have done, the inner logic is the same.
I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call
I get a random row from a mysql-server using php. I then display some information and would like to let the users give feedback on that specific row. However, I can't seem to transfer the ID correctly to the update.php. (No updating is happening on the server). Can somebody spot out my error?
Mysql-php getting a (ugly) random row:
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$result = mysql_query("SELECT id, username, message, ttime, field1, field2 FROM field WHERE done = 0 ORDER BY RAND() LIMIT 1");
$array = mysql_fetch_row($result);
echo json_encode($array);
Then index.php:
<div id="output">
<div id="username">content</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{ $.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
var message = data[2];
var timestamp = data[3];
$('#output').html(timestamp +message );
$('#username').html( vname );
}
});
});
</script>
<script>
$(document).jkey('a',function() {
$.post("update.php", { id: "id"} )
});
</script>
Then in the update.php:
<?php require_once('Connections/connection.php'); ?>
<?php
$id = $_POST['id'];
$sql = "UPDATE field SET field1 = field1 +1 WHERE id = '$id'";
$result = mysql_query($sql);
?>
Put a global _id in a script tag, then :
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
//...
and
<script>
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} ) // <--- Look here
});
</script>
$.post("update.php", { id: "id"} )
is sending the Stringid to the server as the id. You'll want to replace it with the actual variable that holds the id number based on which row the user selected, for example
$.post("update.php", { id: rowIDNum} )
If you provide some information on how the user is selecting a row, I can provide more details on how to determine the value to put in rowIDNum.