How to fill a select box using json? - php

I'm trying to fill a select box in a HTML page using json and PHP, but when I click over the select box it just return a blank option. Whats is wrong?
HTML code:
Choose a problem:
<select name="notification" id="notification" class="form-control">
<option value="00">Select...</option>
</select>
PHP code:
header('Access-Control-Allow-Origin: *');
include 'dbconfig.php';
try{
$results = $DB_con->prepare("SELECT idproblema, tipoproblema FROM problema ORDER BY idproblema");
$results->execute();
$res = $results->fetchAll(PDO::FETCH_ASSOC);
$hold = array();
foreach($res as $reg){
$hold[] = array('idproblema' => $reg['idproblema'], 'tipoproblema' =>$reg['tipoproblema']);
}
}
catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}
echo json_encode($hold);
Jquery code:
$(document).ready(function(){
jQuery.support.cors = true;
$('#notification').click(function(){
$.ajax({
url : 'url.php',
type : 'GET',
data : "json",
crossDomain: true,
success: function (data) {
if (data.length > 0) {
$.each(data, function (index, value) {
$('#notification').append('<option value="' + value.idproblema+ '">' + value.tipoproblema + '</option>');
});
}
else {
var newOption= $('<option value=""></option>');
$('#notification').append(newOption);
}
}
});
});
})
...............................................

You need to add before echo in php
....
header('Content-type: application/json');
....
As jQuery $.ajax set to accepting json data -- you return just text at the moment

Related

Pass array data inside value="" separated with ':' using AJAX/JSON | PHP, HTML

Is it possible to pass data in aray using AJAX/JSON? Like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."?
This is the sample code.
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
echo "<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
I understand that this can work using AJAX, but I don't know how to set it up for array that is only separated with ":"
<script>
$(document).ready(function() {
$("#accounttype").change(function() {
var accounttype = $(this).val();
if(accounttype != "") {
$.ajax({
url:"earnings_amendment-employee_select_title.php",
data:{accounttitleselector:accounttype},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#accounttitleselector").html(resp);
}
});
}
else {
$("#accounttitleselector").html("<option value=''>------- Select --------</option>");
}
});
});
</script>
Thank you.
Add the row data in new array results and return the results in json format using json_encode
if(sqlsrv_num_rows($query) > 0) {
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
$emp=$row['empno'];
$empno = str_pad(++$emp,7,"0",STR_PAD_LEFT);
$array[] ="<option value='".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."".$empno."'>".$row['departmentname']." : ".$row['jobposition']."</option>";
}
}
echo json_encode($array);
In jquery after ajax success parse the response with JSON.parse(), and the data becomes a JavaScript object.
//use each loop to get the option data from response
success:function(response) {
var data = JSON.parse(response);
$("#accounttitleselector").html($.each(data, function(index, value) {
value
}))
}
});

Can not retrieve data json from the server using ajax on cordova

I tried to call / search data by ID , from the server using ajax in cordova , but when I click to display the data " undefined" , what's wrong ???
This my html
<input type="text" id="result" value=""/>
<button>get</button>
<div id="result2"></div>
function get (){
var qrcode = document.getElementById ("result").value;
var dataString="qrcode="+qrcode;
$.ajax({
type: "GET",
url: "http://localhost/book/find.php",
crossDomain: true,
cache: false,
data: dataString,
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id_code=element.id_code;
var qrcode=element.qrcode;
var judul=element.judul;
var hasil2 =
"QR Code: " + qrcode + "<br>" +
"Judul: " + Judul;
document.getElementById("result2").innerHTML = hasil2;
});
}
});
}
This my script on server
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =$row['qrcode'];
$array[] =$row['judul'];
$array[] =$row['jilid'];
}
echo json_encode($array);
}
try to change your parameter in calling ajax
var dataString = {qrcode : qrcode };
Change your php code as below
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =['qrcode'=>$row['qrcode'],'judul'=>$row['judul'],'id_code'=>$row['jilid']];
}
echo json_encode($array);
}
RESOLVED the problem is. I try to replace with this script and the result was the same as I expected.
while ($row = mysql_fetch_object($result)){
$array[]=$row++;
}
echo json_encode($array);

Autofill a select after submission via jQuery

I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $_POST['brand_car']);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
echo json_encode($model);
}
jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
}}
});
});
XHTML + PHP
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
getModels(id, 0);
}
function getModels(id, select) {
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="0">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
$('#model_car').val(select);
}}
});
}
This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
Tag this at the end:
<?php
echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>
This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
// I know nothing about your design, but globals are no good
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $brand_car);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
return $model;
}
AJAX.php
if ($_POST['brand_car']) {
echo json_encode(getModels($dbh, $_POST['brand_car']));
}
In your XHTML + PHP
<select id="model_car" name="model_car">
<?php
foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
}
?>
</select>
PS. It looks like your $_SESSION['brand_car'] is never updated.

How to pass mysql result as jSON via ajax

I'm not sure how to pass the result of mysql query into html page via ajax JSON.
ajax2.php
$statement = $pdo - > prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement - > execute(array(':key2' => $key2, ':postcode2' => $postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while ($row = $statement - > fetch()) {
echo $row['Name']; //How to show this in the html page?
echo $row['PostUUID']; //How to show this in the html page?
$row2[] = $row;
}
echo json_encode($row2);
How to pass the above query result to display in the html page via ajax below?
my ajax
$("form").on("submit", function () {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
//how to retrieve the php mysql result here?
console.log(data); // this shows nothing in console,I wonder why?
}
});
return false;
});
Your json encoding should be like that :
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array($row['Name'], $row['PostUUID']));
}
header('Content-Type: application/json');
echo json_encode($json);
And in your javascript part, you don't have to do anything to get back your data, it is stored in data var from success function.
You can just display it and do whatever you want on your webpage with it
header('Content-Type: application/json');
$row2 = array();
$result = array();
$statement = $pdo->prepare("SELECT * FROM posts WHERE subid IN (:key2) AND Poscode=:postcode2");
$statement->execute(array(':key2' => $key2,':postcode2'=>$postcode));
// $row = $statement->fetchAll(PDO::FETCH_ASSOC);
while( $row = $statement->fetch())
{
echo $row['Name'];//How to show this in the html page?
echo $row['PostUUID'];//How to show this in the html page?
$row2[]=$row;
}
if(!empty($row2)){
$result['type'] = "success";
$result['data'] = $row2;
}else{
$result['type'] = "error";
$result['data'] = "No result found";
}
echo json_encode($row2);
and in your script:
$("form").on("submit",function() {
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
if(data.type == "success"){
for(var i=0;i<data.data.length;i++){
//// and here you can get your values //
var db_data = data.data[i];
console.log("name -- >" +db_data.Name );
console.log("name -- >" +db_data.PostUUID);
}
}
if(data.type == "error"){
alert(data.data);
}
}
});
return false;
});
In ajax success function you can use JSON.parse (data) to display JSON data.
Here is an example :
Parse JSON in JavaScript?
you can save json encoded string into array and then pass it's value to javascript.
Refer below code.
<?php
// your PHP code
$jsonData = json_encode($row2); ?>
Your JavaScript code
var data = '<?php echo $jsonData; ?>';
Now data variable has all JSON data, now you can move ahead with your code, just remove below line
data = $(this).serialize() + "&" + $.param(data);
it's not needed as data variable is string.
And in your ajax2.php file you can get this through
json_decode($_REQUEST['data'])
I would just..
$rows = $statement->fetchAll(FETCH_ASSOC);
header("content-type: application/json");
echo json_encode($rows);
then at javascript side:
xhr.addEventListener("readystatechange",function(ev){
//...
var data=JSON.parse(xhr.responseText);
var span=null;
var i=0;
for(;i<data.length;++i){span=document.createElement("span");span.textContent=data[i]["name"];div.appendChild(span);/*...*/}
}
(Don't rely on web browsers parsing it for you in .response because of the application/json header, it differs between browsers... do it manually with responseText);

How to make second autocomplete options dependent on first autocomplete selection using jQuery?

I have a form with a text input and select option box. The text field uses an autosuggest to allow users to pick options from a list. Once a a value is selected from the autosuggest, the select option box is populated with options dependent on the selection.
I am working to change the code over so that the second box is a text input as well, so as not to limit the users choices (i.e. both fields should allow free text entries if the user does not want to select from the available choices).
I think I've stared at this code too long, and would love some help. Clearly the changes need to come in the loadCountry, populateSelect and loadcountrySelect functions.
I am using PHP, jQuery and jQuery UI Autocomplete.
Any help you could provide would be very much appreciated!
Scripts:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function guess(value){
var oldValue = $('.continent_autocomplete').val();
if (oldValue == value)
return;
$('.continent_autocomplete').val(value);
$('.continent_autocomplete').caret(oldValue.length, value.length);
}
function clearGuess(){
var field = $('.continent_autocomplete');
field.val(field.val().substring(0, field.caret().start));
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(handler) {
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
handler(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
function populateSelect(select, options) {
select.html('');
if (options.length) {
enableSelect();
for (i in options){
var option = options[i];
select.append($('<option></option>').val(option).html(option));
}
} else {
disableSelect('Country');
}
}
function loadcountrySelect(continentObj){
disableSelect('Loading...');
loadcountry(function(options){
populateSelect($('.country_autocomplete'), options);
});
}
function disableSelect(message){
var select = $('.country_autocomplete');
select.html("<option>" + message + "</option>");
select.attr('disabled', true);
}
function enableSelect(){
var select = $('.country_autocomplete');
select.attr('disabled', false);
}
populateSelect($(".country_autocomplete"), []);
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
loadcountrySelect(event.target);
}
});
$("input.continent_autocomplete").keyup(function (event){
var code = (event.keyCode ? event.keyCode : event.which);
if (code == 8) { // Backspace
clearGuess();
}
event.target.value = event.target.value.titleCase();
loadcountrySelect(event.target);
});
});
</script>
HTML:
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name" name="continent_name" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete" name="country_autocomplete" class="country_autocomplete" />
</div>
continent.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['startkey'])) {
$mysearchString = $db->real_escape_string($_GET['startkey']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT DISTINCTROW Continent
FROM locations
WHERE Continent
LIKE '$mysearchString%'
LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Continent))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
country.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['key'])) {
$mysearchString = $db->real_escape_string($_GET['key']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent
LIKE '$mysearchString%'
ORDER BY Country
LIMIT 20");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Country))."/".
ucwords(strtolower(strtok($result->Abbrev,";")))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
You're going to need to modify your PHP to get this to work optimally (filtering occurring on the server). I would update your PHP so that it queries your database with two parameters (one for country, one for continent):
$continent = $db->real_escape_string($_GET['continent']);
$country = $db->real_escape_string($_GET['country']);
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent ='$continent' and Country like '$country%'
ORDER BY Country
LIMIT 20");
(Please take with a grain of salt; I don't know PHP)
Basically, pass a continent (which was selected in the first input) along with the country search string (which was typed in the second input).
Next, you're going to need to apply the autocomplete widget to the second input. Something like:
$("#country_autocomplete").autocomplete({
source: function (request, response) {
var continent = $("#continent_autocomplete").val()
, country = request.term;
$.ajax({
url: '/db/country.php?continent=' + continent + "&country=" + country,
success: function(data) {
response(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
});
Just for some polish, you'll probably want to clear #country_autocomplete when #continent_autocomplete changes. You can do that by adding an event handler for autocomplete's change event:
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
change: function () {
$("#country_autocomplete).val('');
}
});
Lastly, you'll want to remove any code that has to do with populating the country select, since you no longer need it.
The jQuery plugin Autocomplete like Google supports such functionality:
autocomplete.php (agly style, the whole logic at one place -- just to show the principle)
if(!empty($_GET['foo_name']) && !empty($_GET['bar_number'])) {
$sql = 'SELECT ... FROM ... WHERE';
$db = new MySQLi(...);
$db->query($sql);
$numbers = [];
while($row = $result->fetch_assoc()){
$numbers[] = $row['bar_number'];
}
}
echo json_encode($numbers);
autocomplete.html
<link href="/components/autocompletelikegoogle/jquery.autocomplete.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/components/autocompletelikegoogle/jquery.autocomplete.js"></script>
<script type="text/javascript" src="/js/autocomplete.js"></script>
<input type="text" name="foo_name" id="foo-name" value="">
<input type="text" name="bar_number" id="bar-number" value="">
autocomplete.js
$(function() {
$("#foo").autocomplete({
minLength: 3,
limit: 5,
source : [{
url:"/my/ajax/controller/foo?data[foo_name]=%QUERY%",
type:'remote'
}],
});
});
$(function() {
$("#bar").autocomplete({
minLength: 3,
limit: 5,
appendMethod:'replace',
source : [
function(query, add) {
fooName = $('#foo-name').val();
$.getJSON("/my/ajax/controller/bar?data[bar_number]=" + query + "&data[foo_name]=" + fooName, function(response) {
add(response);
})
}],
});
});

Categories