append result arrays in php codeigniter using ajax - php

The below is the json result I got in the console. But, appending it to my dropdown, shows only Physics,Chemistry and test subject. How to get Biology also.
[
[
{"id":"1","subject_name":"Physics"},
{"id":"2","subject_name":"Chemistry"},
{"id":"9","subject_name":"test subject"}
],
[
{"id":"7","subject_name":"Biology"}
]
]
Below is my ajax code
$.ajax({
type: 'POST',
dataType:"json",
// url:'<?php echo base_url()."SchoolAdmin/delete_electricUsage";?>',
url: '<?php echo base_url('SchoolAdmin/getclass_id'); ?>',
data: { class_std : class_std},
success: function (result) {
var listItems= "";
listItems+= "<option value='" + 'select' + "'>" +'Select' + "</option>";
for (var i = 0; i < result[0].length; i++){
listItems+= "<option value='" + result[0][i].id+ "'>" + result[0][i].subject_name + "</option>";
}
$("#subject").html(listItems);
}
});
Below is my controller function,
public function getclass_id()
{
$school_id = $this->session->userdata('school_id');
$sess_id = $this->session->userdata('userid');
$user_id = $this->session->userdata('user_id');
if(($sess_id))
{
$class_id=$this->security->xss_clean($this->input->post('class_std'));
$this->load->model('School_Model');
$cid=$this->School_Model->getclass_id($class_id,$school_id);
foreach ($cid as $r)
{
$rr=$r->id;
$data[]=array_merge($this->School_Model->getSubject($rr,$school_id));
}
echo json_encode($data);
}
else
{
redirect('admin');
}
}
Here is my model,
public function getclass_id($class_id,$school_id)
{
return $this->db->select('id')->from('class_table')->where('standard',$class_id)->where('school_id',$school_id)->
get()->result();
//echo $this->db->last_query();
}
public function getSubject($cid,$school_id)
{
return $this->db->select('id,subject_name')->
from('subject')->where('school_id',$school_id)->
where('class_id',$cid)->get()->result_array();
}

Your result is an array of arrays. You need to loop everything!
Biology is in result[1], but you're only looping result[0]
You could do it manually, like this:
for (var i = 0; i < result[0].length; i++){
listItems+= "<option value='" + result[0][i].id+ "'>" + result[0][i].subject_name + "</option>";
}
for (var i = 0; i < result[1].length; i++){
listItems+= "<option value='" + result[1][i].id+ "'>" + result[1][i].subject_name + "</option>";
}
Or, in one go:
for (var j = 0; j < result.length; j++){
// loops through all result arrays;
for (var i = 0; i < result[j].length; i++){
// loops the `j`th result for entries;
listItems+= "<option value='" + result[j][i].id+ "'>" + result[j][i].subject_name + "</option>";
}
}

Related

Dynamically form not submitting properly AJAX PHP

I am trying to generate dynamically form in table and submit but there is problem in my code which is difficult for me solve,
$(document).ready(function() {
$('#btnsummary').on('click', function() {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
$.ajax({
url: "tblsum.php",
method: "POST",
dataType: 'JSON',
data:
"&date=" +
date +
"&soid=" +
soid,
success: function(response) {
if ( response.length == 0 ) {
alert("NO DATA FOUND!");
}
else{
$("#tblsum tbody").empty();
var len = response.length;
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var shopname = response[i].shopname;
var paymentmode = response[i].paymentmode;
var finalamount = response[i].finalamount;
if (finalamount==0){
return false
}
else if (paymentmode=="Credit"){
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='0'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
else{
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='" + finalamount + "'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
}
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
})
There is two problem if final amount is 0 then save button did not appear, when I submit form first field which is invoiceno don't submit on next page,
below is submit function
function summary(){
$(document).ready(function(e) {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
var form = $('#formsum').serialize();
$.ajax({
url: "test.php",
method: "POST",
data:
"&date=" +
date +
"&soid=" +
soid+
"&form=" +
form,
success: function(data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
}
})
})
}
Below is my PHP code.
for($count = 0; $count<count($_POST['invoiceno']); $count++){
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO ".$invoiceno." Amount ".$amount.'<br>';
}
sorry for bad english.
I told you before return STOPS executing a function, so all code after it is obsolete. In this case, when finalamount == 0 you stop executing the function and return to the place where it started. So the code to create the submit button never will be reached. With some proper indentation, you could see that:
$(document).ready(function() {
//<< ===== START START START of onclick function
$('#btnsummary').on('click', function() {
....
$.ajax({
url: "tblsum.php",
....
success: function(response) {
if ( response.length == 0 ) { .... }
else{
$("#tblsum tbody").empty();
....
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var finalamount = response[i].finalamount;
....
if (finalamount==0){
return false
// STOP EXECUTING THIS FUNCTION
// AND GO DIRECTLY TO END OF FUNCTION ================= >>
// code after this will NOT be executed
}
else if (paymentmode=="Credit"){....}
else{....}
}
// if finalamount == 0, this will never be executed
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
// ===== END END END of onclick function << ===============
// continue executing script from here
})
So you could use continue instead of return to skip only one itteration in the for loop.

How to change Dynamic dropdown list to have different value for options?

In my dynamic dropdown list, how would I change the option value ='" + data[i].toLowerCase() + to be a value of different column from database table? My PHP is returning two jsonencode values, "ID" and "Outcome." JSQuery works when it is just "Outcome" return but not when both "ID" and "Outcome." I have tried.
options += '"<option value ="+ value[i] + "'>" + data[i] + "</option>";
Below is my code.
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data, value)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += '"<option value ="+ value[i] + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctOutcome").change(); //<-Here
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
You have to return in your values from php in json array so you can use it like data[i].id and data[i].outcome, Or you can use $ajax instead of $getJSON and you use the succes function to display result.

Option list showing undefined values on ajax output

this is my code to show values in list box.
$.ajax({
type: "POST",
data: queryvalue,
url: "inputaction.php",
success: function (data) {
switch (action) {
case "GetMake":
console.log(data);
var select = $("#promake");
select.empty();
for (var i = 0; i < data.length; i++)
{
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
break;
}
}
});
i get the result of lot of undefined values in select field. and i have attached an console result in image file, in console output is correct how to rectify this problem.
Console Output
Page Output
$type = mysqli_real_escape_string($conn, $_POST['type']);
$make = mysqli_real_escape_string($conn, $_POST['make']);
$query = "select * from assetmodel where typeid = '".$type."' AND makeid = '".$make."' ORDER by model ASC";
$result = RunQuery($query, $conn);
while($row = mysqli_fetch_array($result)){
$re = array(
'id' => $row['id'],
'model' => $row['model']
);
}
echo json_encode($re);
this is my action page
You have to use "JSON.parse":
var select = $("#promake");
select.empty();
var parse = JSON.parse(json);
for (var i = 0; i < parse.length; i++)
{
select.append('<option value="' + parse[i].id + '">' + parse[i].make + '</option>');
}
decode the json in success
success: function (data) {
var data = $.parseJSON(data);
switch (action) {
case "GetMake":
console.log(data);
var select = $("#promake");
select.empty();
for (var i = 0; i < data.length; i++)
{
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
break;
}
}
You have to specify the dataType as json
$.ajax({
type: "POST",
data: queryvalue,
url: "inputaction.php",
dataType: "json",
success: function (data) {
switch (action) {
and set the MIME type of your response to application/json before sending the data:
header('Content-Type: application/json');
echo json_encode($re);
Simple fix in client-side is as below. Just a condition check inside your loop.
for (var i = 0; i < data.length; i++)
{
if (typeof data[i].id != "undefined" && typeof data[i].make != "undefined" ) {
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
}
If you want to have clean data from DB itself, you have to repair your query. That will eliminate the root cause.

Use ajax to get json data from a php file

Right Im using php to generate a json file
<?PHP
header('Content-type: application/json');
include 'includes/db/connect.php';
$category = $_REQUEST['catname'];
$sql = "SELECT `CDID`, `CDTitle`, `CDYear`, `pubID`, `CDPrice` FROM `tiptop_cd` INNER JOIN tiptop_category ON tiptop_cd.catID=tiptop_category.catID WHERE catDesc = '{$category}'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
$returned[] = $row;
}
echo json_encode($returned);
?>
and I want my php page to use a select box that gets the categories from the database
<?php
$result = mysqli_query($con,"SELECT * FROM tiptop_category");
// echo "<table>";
echo "<select id=\"catname\">";
while($row = mysqli_fetch_array($result))
{
?>
<option name="<?=$row['catDesc']?>"><?=$row['catDesc']?></option>
<?php
}
echo "</select>";
?>
now im trying to use this ajax to output my data
<script type="text/javascript">
var catname = "Classical";
$.ajax({
type: "GET",
url: "./json.php?catname=" + catname,
accepts: "json",
dataType: "json",
success: function(data, status, jqXHR){
someFunction(data);
},
error: function(jqXHR, status, HTTPerror){
alert(HTTPerror);
}
});
function someFunction(data){
console.log(data);
var list = "<ul>";
for (var i = 0; i < data.length; i++) {
list += "<li><ul>";
for (var j = 0; j < data[i].length; j++) {
list += "<li>" + data[i][j] + "</li>";
};
list += "</ul></li>";
};
list += "</ul>";
$('#wrapper').append(list);
}
</script>
<div id="wrapper">
</div>
but all i get is an empty bulleted list
From how the db query looks like, you should get a list of associative arrays, which are encoded as objects:
var list = "<ul>";
for (var i = 0; i < data.length; i++) {
list += "<li><ul>";
for(var key in data[i])
if(data[i].hasOwnProperty(key))
list += "<li>" + data[i][key] + "</li>";
list += "</ul></li>";
};
list += "</ul>";

php json jquery and select box

I have this php code
$jsonArray = array();
$sql = "SELECT ID,CLIENT FROM PLD_SERVERS";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$jsonArray[] = array('id'=>$row['ID'],'client'=>$row['CLIENT']);
}
echo json_encode($jsonArray);
And this js
function autosearchLoadServers()
{
$.post("php/autosearch-load-servers.php",function(data){
var toAppend = "";
for(var i = 0; i < data.length; i++){
toAppend += '<option value = \"' + data[i].id + '\">' + data[i].client + '</option>';
}
$("#serverSelect").empty();
$("#serverSelect").html(toAppend);
});
}
The problem is that i get only undefined values. How can this be? The values are in the JSON, i checked using firebug in mozilla so there has to be something with the data variable but i can't understand what. I tried different ways and no results.
Try specifying the datatype in the post call like this:
$.post("php/autosearch-load-servers.php",function(data){
var toAppend = "";
for(var i = 0; i < data.length; i++){
toAppend += '<option value = \"' + data[i].id + '\">' + data[i].client + '</option>';
}
$("#serverSelect").empty();
$("#serverSelect").html(toAppend);
}, "json");

Categories