Refresh getJSON in PHP with new data from datepicker - php

I have two files, index.php, and showday.php.
index.php is supposed to display a graph with help of canvasjs
The data for canvasjs comes from showday.php, which runs MySQL queries to extract data
The files shown here do show a proper graph when Year, Month, and Day variables have hard coded values in showday.php, therefore I know that the concept works.
My questions are:
- How to load index.php with current date sent to showday.php, and
- How to refresh $.getJSON with new date selected by the datepicker
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="jqueryui/themes/sunny/jquery-ui.css">
<link rel="stylesheet" href="jqueryui/style.css">
<script src="jquery/jquery-3.1.0.js"></script>
<script src="jqueryui/jquery-ui.js"></script>
<script src="canvas/jquery.canvasjs.min.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
} );
I guess that changedate function goes here with new date.
But how to put that date in the call to:
$.getJSON("showday.php", function (result) ???
Also, I would like that the page loads with current date,
and then a user can refresh the graph with a chosen date
with help of datepicker. How to do that?
$(document).ready(function ()
{
$.getJSON("showday.php", function (result)
{
var chart = new CanvasJS.Chart("chartContainer",
{
zoomEnabled: true,
axisY:{
title: "Power",
includeZero: false,
suffix : " kW",
},
axisX: {
title: "Time",
},
data: [
{
type: "spline",
lineColor: "#FFAA00",
lineThickness: 2,
markerColor: "#007700",
dataPoints: result
}
]
}
);
chart.render();
}
);
}
);
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 400px;"></div>
<form action="">
Date: <input type="text" id="datepicker" onchange="changedate(this.value)">
</form>
</body>
</html>
showday.php
<?php
$con = mysqli_connect('localhost', 'db', 'password', 'table');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
**How the new date vlues coming from index.php can be plugged in here?**
$query = "SELECT Hour, Minute, PAC as kW FROM `logdata` WHERE (Year=?) AND (Month=?) AND (Day=?)";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
$Time = $row['Hour'].":".$row['Minute'];
$point = array("label" => $Time , "y" => $row['kW']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>

Create a function:
function updateChart() {
$.getJSON("showday.php", {date: $('#datepicker').datepicker('getDate')}, function (result)
{
var chart = new CanvasJS.Chart("chartContainer",
{
zoomEnabled: true,
axisY:{
title: "Power",
includeZero: false,
suffix : " kW",
},
axisX: {
title: "Time",
},
data: [
{
type: "spline",
lineColor: "#FFAA00",
lineThickness: 2,
markerColor: "#007700",
dataPoints: result
}
]
}
);
chart.render();
}
);
}
Call updateChart() on datepicker select, and $(document).ready(). Pass data through $.getJSON by passing an object as the second parameter.
Access the date with php (In your showday.php) by using $_GET['date']. See this post on how to extract the year/date/month from the string provided.

Related

How to filter a JSON page feeding data to Select2?

I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});

JSON, PHP & SQL implementation error

I'm trying to work out how to use JSON, php and SQL (initially MSSQL) to populate a type-ahead field of names and, once the name is selected, to also populate a job title and department. This is my first time to use JSON, so I'm starting a bit from scratch here.
I got a partial solution from Experts Exchange (see Fiddle) using static data, but I'm having trouble converting the data I'm pulling from the database to what is being shown in the fiddle.
The code for the fiddle is:-
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = [{
empName: "A1",
empTitle: "AAA1 AAAAA"
}, {
empName: "A2",
empTitle: "AAA2 AAAAA"
}, {
empName: "B",
empTitle: "AAA AAAAA"
}, {
empName: "C",
empTitle: "AAA AAAAA"
}];
var empNames = [];
var empTitles = [];
$(availableTags).each(function(ix, v) {
empNames.push(v.empName);
empTitles.push(v.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
I'm stuck now on implementing the results returned from the database query to work with the fiddle. I believe I've to the data correctly formatted but it's wrong somewhere and I'm not sure where that is.
I'm getting the data from an SQL table with a separate php page called fetchEmpName.php:-
<?php
require('i_PDOConnection.php');
$query = "SELECT empFName + ' ' + empLName as [empName], empTitle, empDept FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
$stmt = $dbh->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll();
$return_arr = array();
$return_arr['contacts'] = array();
foreach ($data as $row) {
$dataArray['empName'] = $row['empName'];
$dataArray['empTitle'] = $row['empTitle'];
array_push($return_arr['contacts'],$dataArray);
}
echo json_encode($return_arr);
?>
Which (according to the Chrome console log, produces an array like:
{empName: "Bob Smith", empTitle: "Chief Cook and Bottle Washer"}
Which works properly when I replace the fiddle data with the generated data but fails once the static data is replaced by the sql code. So that tells me that the problem lies in the script. At this point, the page has morphed into:
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fetchEmpName2.php'); ?>;
var empNames = [];
var empTitles = [];
$(availableTags).each(function(x, y) {
empNames.push(y.empName);
empTitles.push(y.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
// console.log(event);
// console.log(ui);
// console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
console.log(availableTags);
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
When I run the page, the jquery library throws an error saying
jquery-ui.min.js:8 Uncaught TypeError: Cannot read property 'label' of undefined"
I hope this is enough for someone to sort out where I'm off track - or if there is a better way to solving the problem of filling additional fields from a type-ahead field.
Thanks in advance - any assistance offered would be greatly appreciated.

Highcharts doesn't update from file

I use Highcharts and when I update the site it doesn't update the data from which it constructs the graph.
I take the data from mysql, save it in a .csv file and open the .csv in highcharts. It seems to save the old values in the graph even if the .csv file is updated.
<?php
unlink('column-data.csv'); //This file must exist or else it gives error
include 'database.php';
$result = mysql_query("SELECT
value
FROM
data
INTO OUTFILE 'C:/xampp/htdocs/arduinoproj/test3/column-data.csv'
FIELDS ENCLOSED BY '\,'
TERMINATED BY ';'
ESCAPED BY '\"'
")
or die("Could not issue MySQL query");
include 'highcharts.php'
?>
..and the highcharts code is more or less unchanged.
The changed code from the original is in bold.
Highcharts code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My first column chart by Highcharts</title>
<!-- 1. Add JQuery and Highcharts in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<!-- 2. You can add print and export feature by adding this line -->
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- 3. Add the JavaScript with the Highchart options to initialize the chart -->
<script type="text/javascript">
jQuery(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
**type: 'line'**
},
title: {
text: 'Tiny Tool Monthly Sales'
},
subtitle: {
text: '2014 Q1-Q2'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Sales'
}
},
series: []
};
// JQuery function to process the csv data
$.get(**'column-data.csv'**, function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains names of categories
if (lineNo == 0) {
$.each(items, function(itemNo, item) {
//skip first item of first line
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first position
else {
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
}
});
//putting all together and create the chart
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 600px; height: 400px; margin: 0 auto"></div>
</body>
</html>

Not able to export jqgrid table as excel/pdf.

I successfully created a small jqgrid table. I'm trying to export this table to an excel or pdf file using Jquery. I am new to jquery and jqgrid. Could someone please let me know what is wrong in the code? I would really appreciate some help or suggestions.
I found the export function online. It said I have to just call this function with the grid id. Am I doing something wrong?
export.php file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="CSS/CalibrationKit.css" rel="stylesheet" type="text/css">
<!-- ------------------------JQGRID files-------------------------------- -->
<link rel="stylesheet" type="text/css" media="screen" href="jquery/css/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="jquery/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="jquery/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="jquery/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
/*jqgrid*/
var mydata = [{
head_mean_volume: "50",
head_std_dev: "2",
head_cv: "3",
offset_factor: "4",
scaling_factor: "5"
}];
$("#projectSpreadsheet").jqGrid({
data: mydata,
datatype: "local",
colNames: ["Head Mean Volume Dispensed", "Head Standard Deviation", "Head %CV", "Whole Head Offset Factor", "Whole Head Scaling Factor"],
colModel: [{
name: 'head_mean_volume',
index: 'head_mean_volume',
editable: false,
}, {
name: 'head_std_dev',
index: 'head_std_dev',
editable: false,
}, {
name: 'head_cv',
index: 'head_cv',
editable: false,
}, {
name: 'offset_factor',
index: 'offset_factor',
editable: false,
}, {
name: 'scaling_factor',
index: 'scaling_factor',
editable: false,
}],
'cellEdit': false,
'cellsubmit' : 'clientArray',
editurl: 'clientArray'
}); /*jqGrid close */
/* createExcelFromGrid */
$('#btnSun').click(function() {
$.fn.myFunction("projectSpreadsheet");
});
$.fn.myFunction = function(gridID,filename) {
var grid = $('#' + gridID);
var rowIDList = grid.getDataIDs();
var row = grid.getRowData(rowIDList[0]);
var colNames = [];
var i = 0;
for(var cName in row) {
colNames[i++] = cName; // Capture Column Names
}
var html = "";
for(var j=0;j<rowIDList.length;j++) {
row = grid.getRowData(rowIDList[j]); // Get Each Row
for(var i = 0 ; i<colNames.length ; i++ ) {
html += row[colNames[i]] + ';'; // Create a CSV delimited with ;
}
html += '\n';
}
html += '\n';
var a = document.createElement('a');
a.id = 'ExcelDL';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename ? filename + ".xls" : 'DataList.xls';
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('ExcelDL').remove();
}
}); /* function close */
</script>
</head>
<body>
<table id="projectSpreadsheet" class="fixed_headers" style="width:875px"></table>
<br><br>
<button id="btnSun">Export Table data into Excel</button>
</body>
</html>
Replace your function with this one and let me know if it works for you.
function(gridID,filename) {
var html = $('#gview_' + gridID).html();
var a = document.createElement('a');
a.id = 'tempLink';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename + ".xls";
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('tempLink').remove();
}

javascript code is not being executed

I am working on this project in which I am trying to get a returned value so I can autofill my input boxes according to what the client selects.
This code however is not executing and I do not know why. When I remove the src="jquery area" $(#dropdown).on is an undefined method; not to sure what to do.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
Here's my full code
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//$DBH->prepare('SELECT first FROM contacts');
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
//get query
$FNresult=$DBH->query('SELECT first FROM contacts');
//set fetch mode
$FNresult->setFetchMode(PDO::FETCH_ASSOC);
$dropdown = "<select name='contacts' id='contacts' >";
while($row =$FNresult->fetch()) {
$dropdown .= "\r\n<option value='{$row['first']}'>{$row['first']}</option>";
// echo getLN();
}
$dropdown .= "\r\n</select>";
echo $dropdown;
//}
/*
// Get last name
function getLN(){
$query = "SELECT last FROM contacts";
$LNresult=mysql_query($query);
$last;
while($row = mysql_fetch_assoc($LNresult)) {
$last = "{$row['last']}";
}
echo $last;
}//end getLN
*/
$DBH = null;
?>
<!-- javascript on client-side -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
/*("#dropdown").on('connection', function (stream) {
console.log('Ah, we have our first user!');
});*/</script>
<form action="insert.php" method="post">
First Name: <input type="text" id="first" name="first"><br>
Last Name: <input type="text" id="last"><br>
Phone: <input type="text" id="phone"><br>
Mobile: <input type="text" id="mobile"><br>
Fax: <input type="text" id="fax"><br>
E-mail: <input type="text" id="email"><br>
Web: <input type="text" id="web"><br>
<input type="Submit">
</form>
here is my new edited script on output page =
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$("#contacts").on('change','#dropdown', function() {
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
here is the php file for backgroundScript.php =
<?
// background script
// retrieve data based on $_POST variable, set to $returnArray
$returnArray = $_POST[array(
'first' => firstName,
'last' => lastName,
)];
/****************************
* the structure of returnArray should look something like
array(
'first' => firstName,
'last' => lastName,
)*/
echo json_encode($returnArray);
?>
this file will send in info so the javascript will then replace form fields with what ever is held in the areas appointed
It would appear that your PHP script is returning some formatted html, which you then try to insert into the dom via .val(). That method is used to set the values of form fields, not insert entire chunks of html. Try using .append() or .html() instead, plus do what Phil suggested above - split your script into multiple blocks.
You need to include your jQuery prior to using it:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Your Code Here
</script>
Better yet would be to use external JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/site.js"></script>
And if you're using HTML5 the type="text/javascript" isn't even needed so:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/site.js"></script>
Even better still would be to use a jQuery CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/site.js"></script>
Also, as others have noted, be sure to use $ at the beginning of your jQuery factories. i.e. $('#dropdown')
-- Update --
Further clarification on project tree, most basic project trees look like this:
root/
|--css/
|--images/
|--js/
|--site.js
|--index.html
-- Update 2 --
Example of a $.post
$.post({
'somescript.php', // Script your posting to
{
someParam1: someData1, // $_POST['someParam1']
someParam2: someData2
// etc etc
},
function(response){
// Do something with JSON response upon successful post
alert(response);
},
'json' // Tells the script that JSON will be returned
});
-- Update 3 --
Okay so basically you want to do is...
Javascript:
var dropdown = $('#dropdown');
dropdown.bind('change', function(){
$post.(
'backgroundScript.php',
{
first: dropdown.val()
},
function(response) {
$('#first').val(response.first);
$('#last').val(response.last);
// Repeat for all of your form fields
},
'json'
);
});
Receive POST param:
$firstName = $_POST['first'];
MySQL query would be something like the following:
$sth = $dbh->prepare('SELECT *
FROM contacts
WHERE first = :first');
$sth->bindParam(':first', $first, PDO::PARAM_STR);
$sth->execute();
Then add all of your MySQL fields into associative array array(key => value) and then json_encode and return array.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
<script>
In your PHP you should have something like this
echo json_encode(array('first' => $some_value, 'last' => "Other value"));
Shouldn't
("#dropdown").on('change', function() {
be
$("#contacts").on('change', function() {

Categories