Loading JSON data with jQuery, PHP and MySQL for radio buttons - php

I'm trying to populate a third set of radiobuttons as an addition to the following script: http://www.electrictoolbox.com/json-data-jquery-php-radio-buttons/
For some reason I cannot seem to fill the third set with the corresponding data. It just stays blank :(
Calling the populateFruittype() function only gives back [ ], while populateFruitVariety() returns the json data correctly.
getdata.php (DB connection / fetching data)
<?php
$dsn = "mysql:host=localhost;dbname=mydb";
$username = "username";
$password = "password";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['fruitName'])) {
$stmt = $pdo->prepare("SELECT DISTINCT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['fruitName']));
$rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_GET['fruitVariety'] )) {
$stmt = $pdo->prepare("SELECT DISTINCT fruittype FROM fruit WHERE variety = ? ORDER BY fruittype");
$stmt->execute(array($_GET['fruitVariety']));
$rows[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);
?>
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Toevoegen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function populateFruitVariety() {
var fruitName = $('input[name=fruitName]:checked').val();
$.getJSON('getdata.php', {fruitName: fruitName}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitVariety" value="' + array['variety'] + '" />' + array['variety'] + '</label> ';
});
$('#varieties').html(html);
});
}
function populateFruittype() {
var fruitVariety = $('input[name=fruitVariety]:checked').val();
$.getJSON('getdata.php', {fruitVariety: fruitVariety}, function(fruit) {
var html = '';
$.each(fruit, function(index, array) {
html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> ';
});
$('#fruittype').html(html);
});
}
$(function() {
$('input[name=fruitName]').change(function() {
populateFruitVariety();
});
});
$(function() {
$('input[name=fruitVariety]').change(function() {
populateFruittype();
});
});
</script>
</head>
<body>
<form>
<div>
<strong>Fruit:</strong>
<label><input type="radio" name="fruitName" value="Apple"/>Apple</label>
<label><input type="radio" name="fruitName" value="Banana"/>Banana</label>
<label><input type="radio" name="fruitName" value="Orange"/>Orange</label>
<label><input type="radio" name="fruitName" value="Pear"/>Pear</label>
</div>
<div>
<strong>Variety:</strong>
<span id="varieties"></span>
</div>
<div>
<strong>Type:</strong>
<span id="fruittype"></span>
</div>
</form>
</body>
</html>
The DB query and content can be found here: http://www.electrictoolbox.com/mysql-example-table/
Just add:
`fruittype` varchar(50) NOT NULL
and fill it with some custom values.

Problem solved.
.change(function() had to be .live('click', function()

Related

The PHP don't add the value to an external file

I write this little script of PHP but when I press the button "Add" it don't add the value to the json.json file, can you tell me what is wrong? The objective is take the values introduced by user on the box add.name and add-link and save it to the json.json file. Have I to call the php script on a html line?
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
<?php
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($json, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $jsonString);
?>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" name="addname" id="add-name" placeholder="Name"></input>
<input type="text" name="addlink" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Box/Table Configuration (Sites/edit/delete)
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
var el1 = document.getElementById('edit-name1');
el.value = Checker[item].name;
el1.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
var url1 = el1.value;
if (url) {
Checker[item].url = url1.trim();
Checker[item].name = url.trim();
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
//Close button (Edit bar)
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
I think you are not using your variables in the right way. json_decode should use $jsonContents and file_put_contents should use $json
Since you are using post variables, you might want to check if it is a post first.
Try it like this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$jsonContents = file_get_contents('js/json.json');
$name = $_POST['addname'];
$url = $_POST['addlink'];
$data = json_decode($jsonContents, true);
$data[] = array("'name':'.$name.', 'url':'.$url.'");
$json = json_encode($data);
file_put_contents('js/json.json', $json);
}

AJAX: How do I get the label and value of a field to be different?

I have the below two files.
How do I get AJAX to populate a label and a value
For example if value is Chicago, IL. How do I get the value to be only Chicago on Submitting the form?
Below the field populates as, for example, Chicago, IL
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center"></h2>
<br /><br />
<label>Search Country</label>
<input type="text" name="city" id="city" class="form-control input-lg" autocomplete="off" placeholder="Type City Name" />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result)
{
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
Below is file TypeaheadTest2.php
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row['city'] . ' ' . $row['state'];
}
echo json_encode($data);
}
?>
If I am getting you right, you are so close to what you are expecting.
I see that you are concatenating the city and state name on the server side. But you want to display only city name on typeahead options.
I would suggest you pass on the city name and state name as separate attributes of an object from PHP and then use them as you want on Javascript side.
Here is the sample code,
PHP:
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$data[] = array('city'=>$row['city'], 'state'=>$row['state']);
}
echo json_encode($data);
}
?>
Javascript:
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result) {
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data) {
result($.map(data, function(item){
return item.city;
}));
}
});
}
});
});

JSON for loop through array shows only last value

I am trying mas a simple HTTP post request using AXIOS.Its like an Ajax request to retrieve the data . Here is the HTML. Its sends a post request to the getData.php.
<!doctype html>
<html>
<head>
<title>axios - post example</title>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
</head>
<body class="container">
<h1>Axios.post</h1>
<form role="form" class="form" onsubmit="return false;">
<div class="form-group">
<label for="data">Output</label>
<textarea id="data" class="form-control container" rows="5"></textarea>
</div>
<button id="post" type="button" class="btn btn-primary">POST</button>
</form>
<!--<div id="output" class=""></div>-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
(function () {
document.getElementById('post').onclick = function () {
var output = document.getElementById('data');
axios.post('getData.php')
.then(function (res) {
// console.log(res.data);
output.className = 'container';
for (i = 0; i < res.data.length; i++) {
output.innerHTML = res.data[i].id + "\n" + res.data[i].name;
}
})
.catch(function (err) {
output.className = 'container text-danger';
output.innerHTML = err.message;
});
};
})();
</script>
</body>
</html>`
In the getData.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password,"db_test");
$sql = "SELECT * FROM user";
$result = $conn->query($sql);
$resultArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
return;
} else {
echo "0 results";
}
$conn->close();
?>
But when i am trying to for loop through the array it returns only the last row.It fetches the data from the table and create an array. Whats wrong with the for loop ?
output.innerHTML = res.data[i].id + "\n" + res.data[i].name;
will just replace everything previously added.
output.innerHTML += res.data[i].id + "\n" + res.data[i].name;
would fix your problem.
Because your overwriting output.innerHTML In for loop so last value only exists .
use appendChild()
output.appendChild(res.data[i].id + "\n" + res.data[i].name);

How to insert into MySQL HTML Form data?

I checked a lot of articles and I don't understand it how to insert data into a MySQL table. What is wrong? I guess that my Ajax request is already wrong.
I would be happy to get help!!!
I did not write programs since 20 years. My coding is for sure not good, but I need to get it running.
Any help would be very appreciated!
The code that follows does not INSERT INTO and does not UPDATE. Why?
Here is the source:
articles.php
<!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" dir="ltr" lang="en-US">
<head>
<meta charset="UTF-8" />
<title>SoB - Administration</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/scroll.js"></script>
<script type="text/javascript" src="js/producttemplate.js"></script>
<script type="text/javascript" src="js/jquery.js" ></script>
<style type="text/css">.buttonarea: (\a)</style>
<script type="text/javascript">
<!--
var js_string;
document.getElementById("recordWrite").disabled = true;
var lastPreviousNext = "";
var date = new Date();
var mysqlDateTime;
var yyyy = date.getFullYear();
var mm = date.getMonth() + 1;
var dd = date.getDate();
var hh = date.getHours();
var min = date.getMinutes();
var ss = date.getSeconds();
mysqlDateTime = yyyy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// No submit by onclick
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
elem = document.getElementById('buttonID');
function stop(e) {
e.preventDefault(); // browser - don't act!
e.stopPropagation(); // bubbling - stop
return false; // added for completeness
}
elem.addEventListener('click', stop, false);
// this handler will work
elem.addEventListener('click', function() { alert('I still work') }, false);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function jsRecordInsertWrite()
{
document.getElementById('formheadline').innerHTML = 'Article Database - I save the new item';
document.getElementById("recordWrite").disabled = true;
js_articles[0]=""; // set auto increment id to NULL
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
var ajaxOptions = {
url: 'writearticle.php',
dataType: 'json',
success: updatePage,
error: printError
};
// Initiate the request!
$.ajax(ajaxOptions);
}
// -->
</SCRIPT>
</head>
<body class="page page-id-11505 page-template-default" onload="jsRecordCurrent();">
<div id="page-wrap">
<?php
include('includes/header.html');
?>
<div id="container-main">
<div id="main-content">
<div class="post" id="post-11505">
<title>SoB - Administration</title>
<div class="entry">
<form id="form_articles" method="post" action="<?= $_SERVER['PHP_SELF'] ?>" name="form_articles">
<table border="0" cellpadding="0" cellspacing="5">
<tr>
<td align="right">
<span style="padding-right:20px">Item</span>
</td>
<td>
<input id="Item" name="Item" type="text" maxlength="100" size="25"/>
</td>
</tr>
<tr>
<td align="right">
<span style="padding-right:20px">Item Category</span>
</td>
<td>
<input name="ItemCategory" type="text" maxlength="100" size="25" />
</td>
</tr>
<tr id="buttonarea">
<td align="right" colspan="2">
<hr noshade="noshade" />
<input id="recordInsertWrite" type="button" name="recordInsertWrite" value=" Save New Record " onclick="jsRecordInsertWrite()" />
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
<div id="aside">
</div>
</div> <!-- End of main container -->
</div><!-- END Page Wrap -->
</body>
</html>
writearticle.php
<?php
$link = mysql_connect('test.test.com:3306', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
// Escape user inputs for security
$ID = mysql_real_escape_string($_POST['ID']);
$Item = mysql_real_escape_string($_POST['Item']);
$ItemCategory = mysql_real_escape_string($_POST['ItemCategory']);
if('$ID' == '')
{
$sql = "INSERT into articles values(NULL,'$Item','$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("error");</script>';
}
else
{
echo '<script type="text/javascript">alert("ok");</script>';
}
}
else
{
$sql = "UPDATE articles SET Item='$Item',ItemCategory='$ItemCategory')";
$query = mysql_query($sql);
if(!$query)
{
echo '<script type="text/javascript">alert("update error");</script>';
}
else
{
echo '<script type="text/javascript">alert("update ok");</script>';
}
}
?>

Auto Populating a php form

I am trying to create a form with an auto-populate feature where a user enters an employee ID, and fields like name, job title, status, etc populate when they leave the employee ID field, similar to the function of the table in http://www.crackajax.net/popform.php#. The data will later be submitted into another database to track other user-entered information. However, when I assemble the files, I can't seem to get the onchange feature to work. Here are the forms:
The form itself:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<meta charset="utf-8" />
</head>
<body>
<form id="entry" name="entry" method="post">
<label for="employeeid" class="stdlabel">Employee ID:</label>
<input type="text" id="employeeID" name="employeeID" onchange="geteedata()">
<br>
<label for="employeename" class="stdlabel">Employee Name:</label>
<input id ="employeename" type="text" name="employeename">
<br>
<label for="employeestatus "class="stdlabel">Status:</label>
<input type="text" name="employeestatus" >
<br>
<label for="employeetitle"class="stdlabel">Job Title:</label>
<input type="text" name="employeetitle" >
<br>
<label for="loccode" class="stdlabel">Employee Loc Code:</label>
<input type="text" name="loccode" >
<input type="submit" name ="submit" value="Submit" style="margin-right:10px">
</form>
<?php
if(isset($_POST['submit'])){
$con = mysql_connect("localhost", "root", "xxx");
if(!$con) {
die("Cannot connect to database:" . mysql_error());
}
mysql_select_db("mydb", $con);
$sql = "INSERT INTO casetracker (emplid,empname,empjobtitle,status, loccode) VALUES ('$_POST[employeeid]','$_POST[employeename]','$_POST[employeetitle]','$_POST[employeestatus]','$_POST[loccode]')";
mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
?>
</body>
</html>
The following is the javascript file:
function geteedata() {
var url = "search.inc.php?param=";
var idValue = document.getElementById("employeeID").value;
var myRandom = parseInt(Math.random() * 99999999); // cache buster
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('employeename').value = results[0];
document.getElementById('employeestatus').value = results[1];
document.getElementById('employeetitle').value = results[2];
document.getElementById('loccode').value = results[3];
}
}
And here is search.inc.php:
if(strlen($param)>0){
$result = mysql_query("SELECT * FROM employee_data WHERE Pernr ='$param'");
if(mysql_num_rows($result)==1) {
while($myrow = mysql_fetch_array($result)){
$employeename = $myrow["Last_First"];
$employeestatus = $myrow["Emp_Status"];
$employeetitle = $myrow["Position_Text"];
$loccode = $myrow["loccode"];
$textout .= $employeename.",".$employeestatus.",".$employeetitle.",".$loccode;
}
} else {
$textout=" , , ,".$param;
}
}
echo $textout;
Does anyone have thoughts on what I'm forgetting, missing or doing incorrectly?
Thanks in advance!
It looks like you're not creating an instance of the XMLHttpRequest object before sending off the request.
Try the following:
function geteedata() {
var url = "search.inc.php?param=";
var idValue = document.getElementById("employeeID").value;
var myRandom = parseInt(Math.random() * 99999999); // cache buster
var http = new XMLHttpRequest();
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
Have a look at MDN Using XMLHttpRequest for more information.

Categories