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!
Related
I am having trouble with my JSON payload. The success function does not fire.
Thanks in advance for any help that can be provided.
JLS
I get the value in the console so I know the query works okay but it is not in a key/value pair it just echos "VALUE" and does not triggers success.
//JS file ***UPDATED***
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'cif_submit.php',
dataType: "json",
data: dataString,
cache: false,
success: function(data) {
if(data) {
alert(data);
}
}
});
})
});
//Here is the php ***UPDATED***
if($_REQUEST['school']) {
$stmt = $conn->prepare("SELECT streetname FROM schoolinfo WHERE fullschoolname = :schoolname");
$stmt->execute (array(':schoolname' =>$_REQUEST['school']));
while($mydata = $stmt->fetch()) {
echo json_encode($mydata);
} }
}
The JSON RESPONSE is:
{"streetname":"Colbeck Road, PO Bag 7200","0":"Colbeck Road, PO Bag 7200"}
I think changing the schooldata to data will fix the issue.
Don't forget that change() event gets called when you unfocus the input.
https://api.jquery.com/change/
Tried with this code and worked perfectly.
JS
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<input id="school" type="text">
<script>
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'a.php',
dataType: "json",
data: dataString,
cache: false,
success: function(schooldata) {
if(schooldata) {
alert('success');
//$("#streetname").text(schooldata.streetname); TRIED THIS NO JOY
//$("#streetname").hide(); TRIED THIS NO JOY
}
}
});
})
});
</script>
</body>
</html>
PHP
if($_REQUEST['school']) {
$datas = array();
$datas[] = array('streetname' => 'test');
foreach ($datas as $data) {
$data = $data['streetname'];
//$streetname = trim(json_encode($data), '"');
//echo json_encode($data);
echo json_encode($data, true);
}
}
I want to display data from MySQL with vis.js.
I get data with JSON, but I am having this error:
Error: Node must have an id
throw new Error("Node must have an id");
-------^
function tampil()
{
$.ajax({
type:"GET",
cache :false,
dataType: "json",
url:"fetch.php",
success: function(data){
console.log(data);
var vertex = new vis.DataSet([
{id:data[0], label:data[1]}
]);
var hubung = new vis.DataSet([
{from:data[2], to:data[3]}
]);
var myDiv = document.getElementById("media");
var data = {
nodes : vertex,
edges : hubung
}
var options = {};
var network = new vis.Network(myDiv,data,options);
}
});
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/vis.js"></script>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/vis.css" />
</head>
<body>
<button type="button" onclick="tampil()">proses</button>
<div id="media" style="width:500px;height:500px;"></div>
</body>
</html>
and my server sid like this
solved, in JavaScript I've added the following code:
function tampil()
{
$.ajax({
type:"GET",
cache :false,
dataType: "json",
url:"nodes.php",
success: function(data){
console.log(data);
var vertex = new vis.DataSet();
var hubung = new vis.DataSet();
var myDiv = document.getElementById("media");
var data = {
nodes : vertex,
edges : hubung
}
var options = {};
var network = new vis.Network(myDiv,data,options);
$.getJSON('edges.php', function(edges) {
hubung.add(edges);
});
$.getJSON('nodes.php', function(nodes) {
vertex.add(nodes);
});
}
});
}
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.
I am getting the value of a checkbox using jquery. How can I pass that value in another view? I want to use it to access data from the DB. This is how far I've got.
Script
<script type="text/javascript" charset="utf-8">
$(function(){
$('#btnClick').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val[i] = $(this).val();
});
});
});
//SOME CODE
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'submission-form',
'enableAjaxValidation'=>false,
'action'=>Yii::app()->createUrl('submission/create'),
'htmlOptions'=>array('enctype'=>'multipart/form-data'),
));
//SOME CODE
<?php echo CHtml::submitButton('Next', array('id'=>'btnClick','name'=>'btnClick',)); ?>
You can use ajax.
<script type="text/javascript" charset="utf-8">
$(function(){
$('#btnClick').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
val[i] = $(this).val();
$.ajax({
type: "POST",
url: "some.php",
data: { Value: val[i] }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
});
//SOME CODE
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'submission-form',
'enableAjaxValidation'=>false,
'action'=>Yii::app()->createUrl('submission/create'),
'htmlOptions'=>array('enctype'=>'multipart/form-data'),
));
//SOME CODE
<?php echo CHtml::submitButton('Next', array('id'=>'btnClick','name'=>'btnClick',)); ?>
And In Some.php
Get that value in variable like
<?php $Selected_Value = $_POST['Value']; ?>
And Perform any database query here.
I am trying to minimize my code by putting it into an array but nothing happens. I can't figure out what I am doing wrong. Here's the code
<html>
<head>
<title>test</title>
<!-- JavaScript -->
<script src="js/jquery-1.5.2.js" type="text/javascript"></script>
<script type="text/javascript">
var phpfile = new Object();
phpfile["testselect"] = "zoomchange.php";
var elementID = new Object();
elementID["testselect"] = "#testdiv";
$(document).ready(function(){
$("select").change(function() {
$.post(
phpfile[$(this).id()],
$(this).serialize(),
function(data) {
$(elementID[$(this).id()]).html(data)
}
);
});
});
</script>
</head>
<body>
<select id="testselect">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="testdiv"></div>
</body>
</html>
here is the zoomchange.php:
<?PHP echo $_REQUEST['testselect'] ; ?>
Your initializers shouldn't look like this:
var phpfile = new Array();
phpfile["testselect"] = "zoomchange.php";
var elementID = new Array();
elementID["testselect"] = "#testdiv";
A JavaScript Array is indexed by numbers, not strings. You want simple object literals:
var phpfile = { testselect: 'zoomchange.php' };
var elementED = { testselect: '#testdiv' };
Then, your POST callback is confused:
function(data) {
$(elementID[$(this).id()]).html(data)
}
this isn't what you think it is when that function is called. You want something more like this:
$("select").change(function() {
var that = this;
$.post(
phpfile[that.id],
$(this).serialize(),
function(data) {
$(elementID[that.id]).html(data);
}
);
});
This
function(data)
{
$(elementID[$(this).id()]).html(data);
}
instead of this
function(data)
{
$(elementID[$(this).id()]).html(data)
}
Is this the error ?
You should do new Object() instead of new Array().
Edit: There are other mistakes, your js code should be this:
<script type="text/javascript">
var phpfile = {};
phpfile["testselect"] = "zoomchange.php";
var elementID = {};
elementID["testselect"] = "#testdiv";
$(document).ready(function(){
$("select").change(function() {
var $select = $(this);
$.post(
phpfile[$select.attr("id")],
$select.serialize(),
function(data) {
$(elementID[$select.attr("id")]).html(data)
}
);
});
});
</script>