Adding table rows based on JSON - javascript

I'm new with JSON. I have a select box and JavaScript change() trigger on it. I execute MySQL query with Ajax based on selected value. Query results will be printed as a new row in HTML table.
But the new row isn't appending. What am I doing wrong?
HTML
<select id="orderAddProduct">
<option value=""></option>
<option value="0001">Product 1</option>
<option value="0002">Product 2</option>
</select>
<table id="orderTable">
<tr><th>ID</th><th>Name</th></tr>
</table>
JavaScript
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "POST",
url: "orderAddProduct.php",
data: {option: selectedValue},
datatype: "json",
success: function (data) {
alert("OK");
orderAddRow(data);
},
error: function () {
alert("ERROR");
}
});
});
function orderAddRow($item) {
$.each($item,function(index,value) {
var row = '<tr><td>'+value.id+'</td>'
+'<td>'+value.name+'</td></tr>';
$('#orderTable').append(row);
)};
}
PHP
try {
$pdo = new PDO(DB_TYPE . ':host=' . DB_HOST . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("SET NAMES utf8");
$productId = $_REQUEST['option'];
$sql = $pdo->prepare("SELECT * FROM products_view WHERE id = ?");
$sql->execute(array($productId));
$row = $sql->fetch(PDO::FETCH_ASSOC);
$json_array = array("ID" => $row['id'], "name" => $row['name']);
echo json_encode($json_array);

Variable names?
function orderAddRow($item) {
^^^^^^----
var row = '<tr><td>'+value.id+'</td>'
^^^^^----
You define a $item parameter, but never use it in the function. Instead there's this mysterious/undefined value.

Ok, the master problem is that I didn't have JSON.parse() function in my code. Below is my finally working code.
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "GET",
url: "orderAddProduct.php",
data: {option : selectedValue},
datatype: "json",
success: function (response) {
response = JSON.parse(response);
if(response === undefined) {
alert("undefined");
} else {
orderAddRow(response);
}
},
error: function () {
alert("ERROR");
}
});
return false;
});
function orderAddRow($data) {
$.each($data,function(index,value) {
var row = '<tr><td>' + value.ID + '</td>'
+ '<td>' + value.name + '</td></tr>';
$('#orderTable').append(row);
});
}

success: function (data) {
alert("OK");
orderAddRow(data);
},
You are missing out the returned value.

Related

Update select options based on other selected option from database

I have a form which selects regions, provinces, and cities. The select options for provinces depends on the selected region and the options for cities depends on the selected province. All the options are from the database
I have already made the region show up with this code.
<select class="form-control" id="region" name="region">
<?php
if( isset($Region) && count($Region)>0 ){
foreach($Region as $Region){
echo '
<option>'.$Region['region'].'</option>
';
}
}else{
echo '
<option>NO RECORDS FOUND</option>
';
}
?>
</select>
Could you please help me on my next step which is to display the options for provinces?
<select class="form-control" id="province" name="province">
</select>
I believe after achieving this step I would be able to do the same for displaying cities. Thank you!
Database name: patrol
table name: geography
>id
>region
>province
>city
I've tried the same as this one by putting this script
<script>
$(function() {
$(document).ready(function () {
$('#region').change(function() {
var select = $('#province').empty();
$.get('script.php', {region: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
});
</script>
and having this script.php
<?php
if (isset($_GET['region'])) {
$sql = new mysqli('localhost','root','','patrol');
$region = mysqli_real_escape_string($sql,$_GET['region']);
$query = "SELECT * FROM geography WHERE region = $region";
$ret = $sql->query($query);
$result = array();
while ($row = $ret->fetch_assoc()) {
$result[] = array(
'value' => $row['id'],
'name' => $row['province']
);
}
echo json_encode($result);
}
?>
<option>'.$Region['region'].'</option>
You did not set any value in region select option.
It should be like below:
<option value="'.$Region['region'].'">'.$Region['region'].'</option>
also use console.log(result) to see you are getting expected data back or not.
Thank you for answering guys. However, I have found an answer and it did the fix. I'll post the script for others who have the same question as mine
<script type="text/javascript">
$(document).ready(function()
{
$("#region").change(function()
{
var region= document.getElementById("region").value;
var dataString = 'region='+ region;
$.ajax
({
type: "POST",
url: "get_province.php",
data: dataString,
cache: false,
success: function(html)
{
$("#province").html(html);
}
});
});
$("#region").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
$("#province").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
});
</script>

Populate select box when document load

im trying to populate a select box from values in my database after the document load, or ready. I'm new to ajax and jquery, Can someone help find what's wrong to my code?
<select class="form-control sec" id="sec" name="sec">
<option value="sec">Section</option>
</select>
here's my ajax code.
function loadselectbox(){
var fac_code = $("#faculty_code").val();
$.ajax({
type: 'POST',
url: 'getrecords.php',
data: {
"load": 1,
"fac_code": fac_code
},
dataType: 'json',
success: function(data)
{
var select = $("#sec"), options = '';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'>";
}
select.append(options);
}
});
}
here's my getrecords.php
if (isset($_POST['load'])) {
$fac_code = $_POST['fac_code'];
$select = mysqli_query($con,"SELECT * FROM tfile WHERE faculty_code = '$fac_code'");
while ($row = mysql_fetch_array($select)) {
$result[] = array(
'section' => $row['section'],
'subj_descr' => $row['subj_descr']
);
}
echo json_encode($result);
}
i call the function in document.ready
$(document).ready(function() {
loaddata();
loadselectbox();
});
Try this:
$(document).ready(function(){
var fac_code = $("#faculty_code").val();
$.ajax({
url: 'getrecords.php',
type: 'POST',
data: {
"load": 1,
"fac_code": fac_code
},
success: function(response){ // response contains json object in it
var data = JSON.parse(response);
var options = '<option value=""></option>';
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].section+"'> +data[i].subj_descr+ </option>";
}
$("#sec").html(options); // It will put the dynamic <option> set into the dropdown
}
});
});

jquery call other self-declared function in autocomplete select event

Can I call a function in autocomplete select event?
I have a function call getResult() which will retrieve data from database, the function is working smooth, just I fail to call this function in autocomplete's select event. Below is my code:
Auto-complete code:
$(function()
{
//auto complete for facultyID
var availableTags = <?php
$sql = "SELECT FacultyID from tblfaculty";
$result = mysql_query($sql, $DBLink) or die("Error " . mysql_error($DBLink));
$id_list = array();
while($row = mysql_fetch_array($result))
{
$id_list[] = $row['FacultyID'];
}
echo json_encode($id_list); ?>;
$("#FacultyID").autocomplete(
{
source: availableTags,
autoFocus:true,
select: function(event, ui)
{
getResult();
}
});
});
getResult() function:
function getResult()
{
$(function()
{
var Semester = $('#Semester').val();
var Year = $('#Year').val();
var Course = $('#Course').find(":selected").val();
var Subject = $('#Subject').find(":selected").val();
var FacultyID = $('#FacultyID').val();
var TimeSlot = $('#TimeSlot').val();
var Location = $('#Location').val();
$.ajax(
{
type: 'POST',
url: 'ajax_get_time_table.php',
data: {Semester:Semester+", "+Year, Course:Course, SubjectID:Subject, FacultyID:FacultyID, TimeSlot:TimeSlot, Location:Location},
dataType: 'json',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
//do something
}
else
{
//do something
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
}
Is there any wrong with my code?
You don't have to put everything in a doc ready block in getResult() function:
$(function(){});
because the DOM is already loaded and you are able to call this function inside autocomplete's select event.

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

how to use javascript this keyword with change function

I'm having a trouble using change function. I have a 2 different dropdowns attached to each other. When the first one is changes, the second one changes too. I did it using jquery ajax. But when i use ID's jquery can only work one time. So i did a research about javascript's this,parent and children keyword but i can't find the suitable way.
so my javascript is like below :
<script>
$(document).ready(function() {
// alert('js working');
$(".catSelectedClass").change(function() {
// alert('i'm inside the function dude');
function ustCat() {
alert(this);
var mainCatID = $(this).val();
alert('mainCatID captured');
var id = $(this).parent().$(".catIDClass").val();
// alert(id);
// alert(mainCatID);
$.ajax({
type: "POST",
url: "panel/catGroupPost.php",
data: {id: id, mainCatID: mainCatID}
}).done(function(data) {
var responseData = data;
alert(responseData);
$('#subCat').html($(data));
});
}
ustCat();
});
$(".subCatClass").change(function() {
function subCat() {
var mainCatID = $(this).val();
var id = $('#catID').val();
$.ajax({
type: "POST",
url: "panel/subCatPost.php",
data: {id: id, mainCatID: mainCatID}
}).done(function() {
alert('its done. its gone. Yes Mr.Frodo. Its all over now !!');
});
}
subCat();
});
});
</script>
And this is how a fill dropdowns :
while ($cat = mysql_fetch_array($cat_query)) {
$catTable.= '<label>' . $cat['name'] . '</label>';
$catTable.= '<div class="catContainer"><div id="catPost" class="catPostClass">';
$catTable.= '<input type="text" id="catID" class="catIDClass" value="' . $cat['id'] . '"><select id="catSelected" class="catSelectedClass" name="catSelected"><option value="0">Seçiniz...</option>' . catOption($cat['mainCatID']) . '</select></div>';
$kategoriTablosu.= '<div id="subCat"><select id="subCatID" class="SubCatClass"><option value="0">Seçiniz...</option>' . subCatOption($cat['mainCatID']) . '</select></div></div>';
}
My both functions:
function catOption($id) {
$query = mysql_query("SELECT * FROM mainCats WHERE id=mainCatID") or die(mysql_error());
$arrCat = "";
while ($row = mysql_fetch_array($query)) {
$arrCat .= '<option value="' . $row['mainCatID'] . '"';
if ($row['id'] == $id) {
$catSelected = 'selected="selected"';
} else {
$catSelected = "";
}
$arrCat .= '' . $catSelected . '>' . $row['name'] . '</option>';
}
return $arrCat;
}
And :
function subCatOption($subID) {
$subCat = mysql_query("SELECT * FROM mainCats WHERE mainCatID='$subID' ORDER BY id ") or die(mysql_error());
$subArrCat = "";
while ($row = mysql_fetch_array($subCat)) {
$subArrCat .= '<option value="' . $row['mainCatID'] . '"';
if ($row['mainCatID'] == $subID) {
$catSelected = 'selected="selected"';
} else {
$catSelected = "";
}
$subArrCat .= '' . $catSelected . '>' . $row['name'] . '</option>';
}
return $subArrCat;
}
Thanks for any help !
You need to change your code as
$(".catSelectedClass").change(function() {
var mainCatID = $(this).val();
//Rest of code....
});
Instead of
$(".catSelectedClass").change(function() {
// alert('i'm inside the function dude');
function ustCat() {
var mainCatID = $(this).val();
//Rest of code....
}
});
Same with $(".subCatClass").change(function() {
General Syntax
$(selector).change(function() {
//do something
});
If you have already defined function use
$(selector).change(your_defined_function);
in your case you can use
$(".catSelectedClass").change(ustCat);
the problem is that you call a function in the event handler. If you instead put the code inside the event handler or you turn the function in the handler it should fix your problem. I suggest to make the function the event handler. So just put the ustCat on its own and use the following to make the function the handler
$(".catSelectedClass").change(ustCat);
You don't need the functions inside the change function. You can simply do:
$(".catSelectedClass").change(function () {
// alert('i'm inside the function dude');
alert(this);
var mainCatID = $(this).val();
alert('mainCatID captured');
var id = $(this).parent().$(".catIDClass").val();
// alert(id);
// alert(mainCatID);
$.ajax({
type: "POST",
url: "panel/catGroupPost.php",
data: {
id: id,
mainCatID: mainCatID
}
}).done(function (data) {
var responseData = data;
alert(responseData);
$('#subCat').html($(data));
});
});
$(".subCatClass").change(function () {
var mainCatID = $(this).val();
var id = $('#catID').val();
$.ajax({
type: "POST",
url: "panel/subCatPost.php",
data: {
id: id,
mainCatID: mainCatID
}
}).done(function () {
alert('its done. its gone. Yes Mr.Frodo. Its all over now !!');
});
});
The way you did it this was in the wrong scope. this would be window.
Several ways to do it.
You don't really need to define ustCat, you can just put the code inside the change function :
$(".catSelectedClass").change(function() {
var mainCatID = $(this).val();
....
});
Or assign the parent before you call your inner function :
$(".catSelectedClass").change(function() {
(function ustCat(self){
var mainCatID = self.val();
......
})($(this));
});
Or put the ustCat function elsewere and just pass it to the change handler :
function ustCat(){ var mainCatID = $(this).val(); ...... };
$(".catSelectedClass").change(ustCat);

Categories

Resources