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>
Related
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 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);
});
}
});
}
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 use this script to get the markers for Google Maps with JSON.
It is not working because I need to receive the boundary in the Json script like this:
$swLat=$_GET["swLat"];
$swLon=$_GET["swLon"];
$neLat=$_GET["neLat"];
$neLon=$_GET["neLon"];
That is where I need your help.
Google maps script
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="http://skiweather.eu/gmap3/js/jquery.ui.map.js"></script>
<script language="javascript" type="text/javascript">
var map = null;
map = new google.maps.Map(document.getElementById("map"));
var markers = new Array();
var bounds = map.getBounds();
var zoomLevel = map.getZoom();
$(function() {
demo.add(function() {
$('#map').gmap().bind('init', function() {
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
}).load();
});
</script>
</head>
<body>
<div id="map"></div>
The jQuery/gmap-part of your code will not be executed at all.
Fixed code:
<script type="text/javascript">
$(function() {
$('#map').gmap().bind('init', function() {
var markers = new Array();
var bounds = $(this).gmap('get','map').getBounds();
var zoomLevel = $(this).gmap('get','map').getZoom();
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
});
</script>
However, it's sending the data now, but it's still not working, because the server will not give any response(are you sure that there is a webservice that returns JSON-data?)
I've created a controller & view as follows - I am trying to loop through the jSON object - can anyone assist?
Can anyone demonstrate how to loop through the json object in the view?
//Controller PHP function:
public function ajax_get_all()
{
$stockists = $this->stockists_model->get_all();
header('Content-type: application/json');
echo json_encode($stockists);
}
//HTML View
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// Stuff to do as soon as the DOM is ready;
$.getJSON("/stockists/ajax_get_all", function(data) {
var obj = jQuery.parseJSON(data);
//console.log(obj);
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// Stuff to do as soon as the DOM is ready;
$.getJSON("/stockists/ajax_get_all", function(data) {
$.each(data, function(key,value){
console.log(key);
console.log(value);
});
//var obj = jQuery.parseJSON(data);
//console.log(obj);
});
});