I have two drop-down lists where the second depends on the first drop-down list selection.
I've tested getSalary and getamount and it can fetch the array but cannot be loaded to try.php.
What could have gone wrong? Here are my codes.
try.php:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="jquery-ui.js"></script>
<script src="script.js"></script>
</head>
<body>
Grade and Increment
<select name="salaryid" id="salaryid" ></select>
<br>
Salary Amount:
<select name="salaryamt" id="salaryamt" ></select>
</body>
</html>
script.js:
$(document).ready(function () {
$.getJSON("getSalary.php", success = function(data) {
var options = "";
for (var i = 0; i < data.length; i++)
{
options += "<options value='" + data[i].toLowerCase() + "'>" + data[i] + "</options>";
}
$("#salaryid").append(options);
$("#salaryid").change();
});
$("#salaryid").change(function(){
$.getJSON("getAmount.php?make=" + $(this).val(), success = function(data) {
var options = "";
for (var i = 0; i < data.length; i++)
{
options += "<options value='" + data[i].toLowerCase() + "'>" + data[i] + "</options>";
}
$("#salaryamt").html("");
$("#salaryamt").append(options);
});
});
});
getSalary.php
<?php
include 'pmis_conn.php';
$qrysal = mysql_query("Select grade_incre from salary_ref where year = '2012'") or die(mysql_error());
$makes = array();
while($row = mysql_fetch_array($qrysal))
{
array_push($makes, $row['grade_incre']);
}
echo json_encode($makes);
?>
getamount.php
<?php
if (isset($_GET["make"])) {
include 'pmis_conn.php';
$make = $_GET["make"];
$qrysal = mysql_query("Select amount, year from salary_ref where grade_incre like '{$make}'") or die(mysql_error());
$amount = array();
while($row = mysql_fetch_array($qrysal))
{
//$amt = $row['amount'] + "-" + $row['year']
array_push($amount, $row['amount']);
}
echo json_encode($amount);
}
?>
Check the following things:
the GET php calls are executed as expected
the javascript is triggered as expected
Debug the GET calls:
For debugging try to use in Chrome the Developer tools Ctrl+shift+I.
In there check the Network tab to see what's going on with your ajax call.
Here the manual: https://developer.chrome.com/devtools
here a tutorial: http://discover-devtools.codeschool.com/
Debug the javascript:
Alvways from the Developer tools go on Source and put some break points on script.js.
Here the manual for debug js: https://developer.chrome.com/devtools/docs/javascript-debugging
Additional issue in the javascript:
As you can see here https://jsfiddle.net/86vjfwLe/3/ your $(this).val() is null.
You should try this method instead : jQuery get value of select onChange .
Additional issues with the html and on change:
The html you are injecting is broken. You have to replace options to optionand it should work.
Related
I'm trying to connect my mysql database with an html page using an ajax script. Based on the tutorial from Adnan Afzal (http://adnan-tech.com/tutorial/get-data-from-database-using-ajax-javascript-php-mysql), I coded one php and one html file. However, each time I try to run the page, I get an error telling me that the first character at position 1 is not correct :
Here is a dump of my php (called data.php)
$data = array();
while ($row = mysqli_fetch_object($result))
{
array_push($data, $row);
}
echo json_encode($data);
exit();
Here is a dump of my html page
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<tr>
<th>id_country
<th>Country_name_en
<th>Country_name_fr
</tr>
<tbody id="data"></tbody>
</table>
<script>
var ajax = new XMLHttpRequest();
ajax.open("GET", "data.php", true);
ajax.send();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
var html = "";
for(var a = 0; a < data.length; a++) {
var id_country = data[a]['id_country'];
var Country_name_en = data[a]['country_name_en'];
var Country_name_fr = data[a]['country_name_fr'];
html += "<tr>";
html += "<td>" + id_country + "</td>";
html += "<td>" + Country_name_en + "</td>";
html += "<td>" + Country_name_fr + "</td>";
html += "</tr>";
}
document.getElementById("data").innerHTML += html;
}
};
</script>
</body>
</html>
I hope the way the question is published is acceptable, I am not expecting to have code written on my behalf. I would be very keen on understanding what I am doing wrong here and hopefully, this post could be useful to anyone else.
Edit : Following the reply of Aynber, I have added a screenshot below of the debugging network tab :
Edit 2 : Following the reply of Shivendra Singh, I have corrected the code as follows :
var id_country = data[a]['id_country'];
var Country_name_en = data[a]['country_name_en'];
var Country_name_fr = data[a]['country_name_fr'];
Thanks a lot to the help of the contributors.
It was the syntax of how I was referring the fields which was not correct :
[...]
var Country_name_en = data[a]['country_name_en'];
[...]
I have corrected the code accordingly above to depict the correct situation.
I am attempting to code the following script using jquery / ajax / php.
What happens is the php pulls all the records from the database and puts them into a select dropdown. When I select an item from the dropdown ajax pulls the price from the database and adds it into the span called priceeach1 . Well thats what its supposed to do, but my jquery is useless :-S .
The stockID comes from the select box value.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock1').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
});
});
});
</script>
The HTML :
Price Each : £<span id="priceeach1"></span>
The select2.php :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['stockID'];
$sql = 'SELECT * FROM stock WHERE stockID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'priceeach' => $row['priceeach'],
);
}
echo json_encode($json);
?>
EDIT >> Ok I have now updated the code with the latest edits, this now WORKS.....apart from an odd problem......If I select the first or last item in the list no price is displayed, anything in between appears just fine..........
Try this,
var options = [];
for (var x = 0; x < data.length; x++) {
options = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
It should be like this you have to store price in the array options[] instead of option and then join them by any separator
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options[x] = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
You have to parse your JSON data to actual JSON Object before iterating it.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var jsonParsed = JSON.parse(data);
var options = '';
for (var x = 0; x < jsonParsed.length; x++) {
options[] = jsonParsed[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
Try to use this snipt:
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
I have pasted the code for index.php and jsonPhp.php.I am new to JSON and learning json with ajax.Here,I am trying to get the data from the server using json.When I click on the link SERVER DATA, The data from the server must appear without re-loading the page using jQuery/json.I have written the code but I dont get it working.Please help.
Thanks.
<head>
<title>JSON WITH PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
type="text/javascript"></script>
<script type="text/javascript">
< ![CDATA[
$(function () {
$('#click').click(function () {
$.post('jsonPhp.php', function (data) {
//$("#content").html(data)+'<br>';
var pushedData = jQuery.parseJSON(data);
var htmlData = "";
//loop through using jQuery
$.each(pushedData, function (i, field) {
htmlData = htmlData + '-' + field.id + ',' + field.place + ',' + field.description + '<br>';
});
$('#content').html(htmlData);
});
});
});]] >
</script>
</head>
<body>Click on the link below to get the data from the Server Dynamicallly!
<br
/>
Server Data
<div id="content"></div>
</body>
<?php
$db = mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("places",$db) or die(mysql_error());
if(isset($_POST['place']))
$place=$_POST['place'];
if(isset($_POST['description']))
$description=$_POST['description'];
$myrows = array();
$result = mysql_query("SELECT * FROM search");
while( $row = mysql_fetch_assoc($result) ) {
$myrows[] = $row;
}
echo json_encode($myrows);
?>
Try specifying parameters, that you send with POST request, resulting something like this:
$.post('jsonPhp.php', { place:'myplace', /* other params */ }, function (data) { ...
Your jQuery post doesn't post the necessary items.
Be careful using this code.
I am trying to set a variable $id=$_GET["categoryID"]. I cannot get it to work. I believe it has to do with the the Ajax request. But I don't know how I have to format it so that it will work in conjunction with that request. I need the variable for a mysql query. Any help is greatly appreciated. This is over my head and have been struggling with it for days. I have tried both GET and POST. Thanks.
I have distilled the page down to this...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test $_GET</title>
</head>
<body>
<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$id = $_GET["categoryID"];
//$id=3;
}
?>
print_r($_GET) = <?php print_r($_GET); ?>
<br />
print_r($id) = <?php print_r($id); ?>
</body>
</html>
Here is the resulting page....
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test $_GET</title>
</head>
<body>
print_r($_GET) = Array
(
[categoryID] => 1001
)
<br />
print_r($id) =
</body>
</html>
Here is the whole page....
<?php
if (#$_REQUEST['ajax']) {
$link = $nm33;
if ($link == false)
trigger_error('Connect failed - ' . mysql_error(), E_USER_ERROR);
$connected = mysql_select_db('nm', $link);
if ($connected) {
//How do I set $id = $_GET["categoryID"] It fails to set the variable.
$id =$_GET["categoryID"];
// $id=1;
// It will work as $id=1
$results = mysql_query('select * from selectMenu where categoryID= \'' . $id . '\' AND category="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"');
//////////
$json = array();
while (is_resource($results) && $row = mysql_fetch_object($results)) {
//$json[] = '{"id" : "' . $row->id . '", "label" : "' . $row->label . '"}';
$json[] = '"' . $row->label . '"';
}
echo '[' . implode(',', $json) . ']';
die(); // filthy exit, but does fine for our example.
} else {
user_error("Failed to select the database");
}
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/select-chain.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
<!--
$(function () {
var cat = $('#categorySelect');
var el = $('#elementSelect');
var attr = $('#attributeSelect');
el.selectChain({
target: attr,
url: 'select-menu.php',
data: { ajax: true, anotherval: "anotherAction" }
});
// note that we're assigning in reverse order
// to allow the chaining change trigger to work
cat.selectChain({
target: el,
url: 'select-menu.php',
data: { ajax: true }
}).trigger('change');
});
//-->
</script>
<link href="selectMenu.css" rel="stylesheet" type="text/css" />
<form action="performance-models.php" method="get">
<select name="category" class="dropdown" id="categorySelect">
<option selected="selected">Select Your Vehicle</option>
<?php do { ?>
<option> <?php echo $row_rsMake['make']; ?></option>
<?php } while ($row_rsMake = mysql_fetch_assoc($rsMake)); ?>
</select>
<select name="model" class="dropdown" id="elementSelect">
<option selected="selected">Select Model</option>
<option>[none selected]</option>
</select>
<select name="appYear" class="dropdown" id="attributeSelect" >
<option selected="selected"> </option>
<option>[none selected]</option>
</select>
<input type="submit" value="Go">
</form>
<p><br />
<br />
print_r($_GET) = <?php print_r($_GET); ?> <br />
print_r($_REQUEST) = <?php print_r($_REQUEST); ?><br />
echo $_REQUEST['categoryID'] <?php echo $_REQUEST['categoryID'];?>
</p>
Here is select-chain.js
(function ($) {
$.fn.selectChain = function (options) {
var defaults = {
key: "id",
value: "label"
};
var settings = $.extend({}, defaults, options);
if (!(settings.target instanceof $)) settings.target = $(settings.target);
return this.each(function () {
var $$ = $(this);
$$.change(function () {
var data = null;
if (typeof settings.data == 'string') {
data = settings.data + '&' + this.name + '=' + $$.val();
} else if (typeof settings.data == 'object') {
data = settings.data;
data['category'] = $$.val();
data['model'] = $$.val();
data['year'] = $$.val();
}
settings.target.empty();
$.ajax({
url: settings.url,
data: data,
type: (settings.type || 'get'),
dataType: 'json',
success: function (j) {
var options = [], i = 0, o = null;
for (i = 0; i < j.length; i++) {
// required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
o = document.createElement("OPTION");
o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
settings.target.get(0).options[i] = o;
}
// hand control back to browser for a moment
setTimeout(function () {
settings.target
.find('option:first')
.attr('selected', 'selected')
.parent('select')
.trigger('change');
}, 0);
},
error: function (xhr, desc, er) {
// add whatever debug you want here.
alert("an error occurred here");
}
});
});
});
};
})(jQuery);
A $_GET parameter is passed in the URL so for this;
http://www.google.com/?q=search
The parameter $_GET['q'] would be equal to 'search'
So when you perform your AJAX request you need to specify the parameters in the URL.
EDIT:
Try getting rid of your HTTP_X_REQUESTED_WITH statements. The request is probably safe enough without those kind of checks. Just simplify it to:
if ( isset( $_GET["categoryID"] ) ) {
$id = $_GET["categoryID"];
}
There is no need for:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
You can just use:
$id = isset($_GET["categoryID"]) ? intval($_GET["categoryID"]) : 0;
Which is the same as (but shorter...):
if (isset($_GET["categoryID"]))
{
$id = intval($_GET["categoryID"]);
}
else
{
$id = 0;
}
If you want to check if a request was made via ajax, you would have to rewrite your script as the whole header section would not be needed. Instead you could call this script from your page, set a variable in the page itself and if that variable is not set in the script, it's an ajax call. Obviously this is just a simple example.
Edit: The plugin does not mention what the default type of the request is, but that could very well be POST so you could try to add type: "post" to the options of selectChain.
And to make sure that your response is well-formed json (when you get there...) I would also recommend you use json_encode, so:
echo json_encode($json);
die(); // filthy exit, but does fine for our example.
Edit 2: I just noticed another problem: Nowhere is the categoryID being added to the data section in the ajax:
You are requesting / posting to (???) : select-menu.php (notice, no query string!)
The data you are sending is: { ajax: true, anotherval: "anotherAction" } or { ajax: true}
So there is no way that categoryID is ever going to show up in select-menu.php.
The most logical thing to do, would be to add the selected category to the data section:
data: { "ajax": true, "anotherval": "anotherAction", "categoryID": cat }
and:
data: { "ajax": true, "categoryID": cat }
With jQuery you can use jQuery.get() or add a type='GET' parameter to jQuery.ajax(). Some example:
jQuery(function($) {
$.ajax({
url : 'your-page.php',
type : 'GET',
data : {
'paramName' => 'paramValue',
'foo' => 'bar'
},
success : function(data) {
// do something in the callback function
}
});
});
You need to pass the value in the jQuery.get():
$.get('yourphppage.php', { categoryID : 1234 }, function(data) {
alert(data);
});
In your php just echo right back your cateogryId to see if it is working
<?php echo $_GET['categorID'] ?>
Im creating pie charts on google visualization using pulled data from PHP/MySQL.
The chart seems nice, but I wanted to add a calendar (date picker) to make the pie chart dynamic.
My date range picker seems to be working. It pulls the right data from my database.
SELECT DATE:
AFTER SUBMITTING QUERY:
It returns this string: (overall_ban_pos_pie_date.php)
{"cols":[{"id":"0","label":"Column 1","type":"string"},{"id":"1","label":"Count","type":"number"}],"rows":[{"c":[{"v":"String Value 1"},{"v":6}]},{"c":[{"v":"String Value 2"},{"v":4}]}]}
This string is readable by google visualization. If I used this PHP page as my Data Table source for my Pie Chart, It will display its values.
MY PROBLEM/QUESTION IS:
After I clicked on "Submit Query" button, it directs me to the php string page. What I want to happen is when the user selects Start and End dates and clicks on submit query, the pie chart that I have needs to change based on the dates queried from the database and not directed to the overall_ban_pos_pie_date.php (which I used for my Pie chart as data table using JSON string). I want this to redirect me to my
Pie Chart Page: (calendar_test.html)
Can someone tell me how to do that? Thanks in advance.
PHP CODE: (overall_ban_pos_pie_date.php)
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("db_campanaltest", $con);
$j=0;
$k=1;
$l=0;
$label = array("String Value 1","String Value 2");
$cols = '{"cols":[{"id":"'.$j.'","label":"Column 1","type":"string"},{"id":"'.$k.'","label":"Count","type":"number"}],';
$field1 = $_POST['startdate'];
$field2 = $_POST['enddate'];
$query = mysql_query("SELECT fk_IntCampID, COUNT( * ) AS count
FROM tbl_trans2
WHERE date
BETWEEN '".$field1."'
AND '".$field2."'
AND fk_IntCampID = '1'
AND eventScored = 'Y'
AND scoreQuoteSent = 'Y'
OR date
BETWEEN '".$field1."'
AND '".$field2."'
AND fk_IntCampID = '5'
AND eventScored = 'Y'
AND scoreQuoteSent = 'Y'
GROUP BY fk_IntCampID");
while($r = mysql_fetch_assoc($query)){
$rows[] = '{"c":[{"v":'.'"'. $label[$l].'"},{"v":'. $r['count'].'}]}';
$l++;
}
$google_JSON_row =implode(",",$rows);
echo $cols . '"rows":[',$google_JSON_row ."]}";
?>
HTML PAGE: Displays the calendar and pie chart (hopefully)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart','table','piechart']}]}">
</script>
<script type="text/javascript">
google.setOnLoadCallback(pieChart);
function pieChart() {
var startdate = "";
var enddate = "";
if ($("#datepicker").hasClass('hasDatepicker')) {
startdate = $("#datepicker").datepicker('getDate');
}
if ($("#datepicker2").hasClass('hasDatepicker')) {
enddate = $("#datepicker2").datepicker('getDate');
}
var pieJsonData = $.ajax({
url: "overall_ban_pos_pie_date.php?startdate=" + startdate + "&enddate=" + enddate,
dataType:"json",
async: false
}).responseText;
var pieData = new google.visualization.DataTable(pieJsonData);
var pieChartWrapper = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'pie_div',
'dataTable':pieData,
'options': {
chartArea:{left:10,top:40,height:200,width:360},
width:300,
height:260,
title: "Neutral Percentage",
titleTextStyle:{fontSize:12},
tooltip:{showColorCode:true},
legend:{textStyle:{fontSize: 10},position:'left'},
pieSliceTextStyle:{fontSize: 10}
}
});
pieChartWrapper.draw();
}
</script>
<script>
$(document).ready(function() {
$("#datepicker").datepicker({dateFormat: "yy-mm-dd"});
});
$(document).ready(function() {
$("#datepicker2").datepicker({dateFormat: "yy-mm-dd"});
});
$("#pieChart").click(function(e) {
e.preventDefault();
pieChart();
});
</script>
</head>
<body style="font-size:62.5%;">
<form action="overall_ban_pos_pie_date.php" method="post">
Start Date: <input type="text" name="startdate" id="datepicker"/>
End Date: <input type="text" name="enddate" id="datepicker2"/>
<input type="submit" id="pieChart"/>
</form>
<div id="pie_div"></div>
</body>
</html>
Try like this :
$("#pieChart").click(function(e) {
e.preventDefault();
pieChart();
});
This will disable the form submit and call the pichart() function. Now modify the var pieJsonData = ... line of pieChart() like this:
var startdate = "";
var enddate = "";
if ($("#datepicker").hasClass('hasDatepicker')) {
startdate = $("#datepicker").datepicker('getDate');
}
if ($("#datepicker2").hasClass('hasDatepicker')) {
enddate = $("#datepicker2").datepicker('getDate');
}
var pieJsonData = $.ajax({
url: "overall_ban_pos_pie_date.php?startdate=" + startdate + "&enddate=" + enddate,
dataType:"json",
async: false
}).responseText;