How to find all the children for its parent in Jquery? - javascript

I'm using Codeigniter and Jquery with AJAX method to query data from two tables in my database with select join from table group with table cat.
This is table description
Table1: cat
======c_id======fk_group_id====cat_name===
======1========1==============cat1=======
======2========1==============cat2=======
======3========1==============cat3=======
======4========1==============cat4=======
Table2: cat_group.
======gid=======gname====gstat============
======1========1=========1==============
======2========1=========1==============
======3========1=========1==============
======4========1=========1==============
Here is my Model:
This function will selct from table cat_group join with table Cat on gid = cat.fk_group_id.
public function cat(){
$this->db->select('cat_group.*, cat.*');
$this->db->from('cat_group');
$this->db->join('cat', 'cat.fk_group_id = cat_group.gid','all')->where('cat_group.gstatus = 1');
return $this->db->get()->result();
}
My function in Controller:
I call method cat from Model and echo data as Json_encode to the client browsers
public function select_cat_by_group(){
$this->load->model("main/slide_cat_m");
$val = $this->slide_cat_m->cat();
if(!$val){
return false;
}else{
echo json_encode($val);
}
}
Jquery Ajax
$.ajax({
method: "GET",
url: '<?PHP echo base_url('main/select_cat_by_group');?>',
dataType: "Json",
success: function (data) {
$.each(data, function (i, val) {
if(val.fk_group_id = gid){
//I want to select all the rows in table cat where fk_groupd_id = gid of table cat_group but I can't
}
});
}
})
My Json
[{"gid":"1","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"1","fk_group_id":"1","cat_name":"fuck1","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"5","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"2","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"6","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"7","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"5","gtype":"2","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"8","fk_group_id":"5","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"9","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"10","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"15","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"16","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"17","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"18","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"6","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"1","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"19","fk_group_id":"6","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"20","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"21","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"22","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"23","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"24","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"25","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"},{"gid":"7","gtype":"1","g_name":"a","gstatus":"1","gad_stat":"0","gsrc":"asset\/img\/cat\/","gimg":"cat_ads.jpg","c_id":"26","fk_group_id":"7","cat_name":"cat_name","c_status":"1","type_for_group":"1","img":"9.jpg","src":"asset\/img\/main"}]

You did small mistake in model. However it should be:
$this->db->select('cat_group.*, cat.*');
$this->db->from('cat');
$this->db->join('cat_group', 'cat.fk_group_id = cat_group.gid','all')->where('cat_group.gstatus = 1');
return $this->db->get()->result();
It must return all the rows of cat where fk_groupd_id = gid. Now you should parse the json result.
UPDATE:
$.ajax({
type: "POST",
url: 'YOUR_URL',
dataType:'JSON',
success: function(data) {
$.each(data, function(index, element) {
//console.log(index);
//alert(element.c_id);
console.log(element.c_id);
console.log(element.cat_name); // here console.log() is used to debug the data.
});
}
})
It's up to you now how you will display the data in HTML. You can check this example as how to parse json object and display them into DOM: how to parse json data with jquery / javascript?

Related

Receive php multidimensional array in ajax

I have this php
include_once($preUrl . "openDatabase.php");
$sql = 'SELECT * FROM dish';
$query = mysqli_query($con,$sql);
$nRows = mysqli_num_rows($query);
if($nRows > 0){
$dishes = array();
while($row = $query->fetch_assoc()) {
$dishes[] = $row;
}
}else{
$dishes = "cyke";
}
echo json_encode($dishes , JSON_FORCE_OBJECT);
and this ajax (in framework7)
myApp.onPageInit('dailyMenu',function() {
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.log(data);
});
});
What i get in the ajax data is
{"0":{"idC":"2","title":"helloWorld1","subtitle":"hellsubWorld","price":"16.5","img":"img/testeImg.jpg","soldout":"0"},"1":{"idC":"3","title":"helloworld2","subtitle":"hellosubWorld2","price":"20.5","img":"img/testeImg.jpg","soldout":"1"}}
I already tried data.[0]; data.['0']; data.0; data0 when i use data["0"] just gives me the '{'.
I want to acess the title and the rest inside that 0. to do a cicle for where i will print multiple divs where i only change the array position in a html page.
Exemple
for(...){
innerhtml += <div clas="">
<div class""> data(position i).title </div>
<div> data(position i) subtitle</div>
</div>
}
try this one (after callback add type: json)
$$.post('url', {}, function (data) {
var obj = JSON.parse(data);
console.log(obj);
alert(obj["1"].title);
});
or maybe you can use JSON.parse(data);
Since you are receiving a json data as response, you should use this:
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.dir(data);
},'json');
Pay attention to },'json');on end of the code, now the $$.post is reading the response as a JSON.
If you aren't doing any update to data base, you could use:
$$.getJSON('http://theIP/eatsServer/dailyMenu.php',{}, function (data) {
console.dir(data);
});
This is the way with $$.ajax:
$$.ajax({
url: "url_here",
method: "POST",
dataType:"json",
data: {},
success: function(r){
// response r.
}, error: function(error){
//error
}
});

How to append the values in table using AJAX

Here i am passing javascript varaible into PHP function using AJAX ,here it will be working fine,** console.log(fname);** Here i got all values but append the tables means i am getting [object Object],how can solve this error
<script type="text/javascript">
$(document).ready(function(){
$("#reservation").on("change", function() {
var reservation = $(this).val();
$.ajax({
type: 'post',
url: 'date-range.php',
data: {
logindate: reservation,
},
success: function( data ) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
if(res['status']=="success"){
var htmlString='';
$.each( res['data'], function( key, value ) {
htmlString+='<tr>';
var ssm_id = value.ssm_id; // here i got ssmid
htmlString+='<td>'+value.ssm_id+'</td>';
htmlString+='<td>'+ $.ajax({
type: 'post',
url: 'config/functions.php',
data: {
ssm_id: ssm_id,
},
success: function( fname ) {
console.log(fname);//HERE I GOT ALL VALUES
htmlString+='<td>'+fname+'</td>';// BUT HERE I CAN'T APPENT THE VALUES IN TABLE
}
});+'</td>';
htmlString+='<td>'+'Muthuraja'+'</td>';
htmlString+='<td>'+'20-05-2016'+'</td>';
htmlString+='<td>'+'status'+'</td>';
htmlString+='<td>'+value.source+'</td>';
htmlString+='<td>'+ "<span style='color:green'>View Profile</span>"+'</td>';
/* htmlString+='<td>'+ "<span style='color:green'>Completed</span>"+'</td>';*/
htmlString+='</tr>';
});
$('#datatable-editable > tbody').empty().append(htmlString);
}
else{
$('#datatable-editable > tbody').empty().append("<center style='height:100px;padding-top:36px;color:red;font-size:17px;'><b>No matching records found</b></center>");
}
}
});
});
});
</script>
functions.php
<?php
$ssm_id = $_POST['ssm_id'];
if(!empty($ssm_id)){
echo firstname($ssm_id);
}
function firstname($id)
{
$f="SELECT firstname FROM register WHERE matri_id='$id'";
$rr=mysql_query($f);
while($row=mysql_fetch_array($rr)) {
$firstname = $row['firstname'];
}
return $firstname;
}
?>
Without knowing the exact format of your JSON, it's hard to give a definitive answer. However, assuming you have a JSON array of objects that represent your rows, you'd need to iterate over that array and for each object do the following:
Create a new <tr> element - var $tr = $('<tr/>');
For each item of information (I assume one item per <td>), create a <td> element and set its content - var $td = $('<td/>').html(x.y) (x is your current object, y is a field in the object) then append it to the row - $tr.append($td);.
Append the row before the last row in the existing table - $('.list-order tr:last').before($tr);
Following from the additional information provided in the question, the following code should do what you need to do:
success: function(result) {
//result is json format
var $tr = $('<tr/>');
$tr.append($('<td/>').html(result.itemname));
$tr.append($('<td/>').html(result.qty));
$tr.append($('<td/>').html(result.prices));
$('.list-order tr:last').before($tr);
}

Display Json data jQuery PHP MySQL

I cant find answer to my problem...the truth is im new to jQuery and JSON.
On login page i want to display top customers and top tracks, when page loads.
Iv displyed them via echo from php, but i want to create JSON object and send it to login ...loop there and display it in unordered list.
Can you guys help me with creating JSON and displaying it in jquery.
Here's my code:
jQuery:
/* Function to load top Customers */
function loadCustomers() {
/* Create data string to call functions in php*/
var dataString ="function1=loadCustomers&function2=loadTracks";
$.ajax({
type:"GET",
url: "login.php",
data: dataString,
dataType: "json",
success: function(data) {
$("#error").show();
$("#errormsg").html(data.FirstName);
//how can i display Json data in unordered list ? #customerList
},
error: function() {
$("#error").show();
$("#errormsg").text("cant display data");
}
});
}
PHP :
}else if ($_SERVER["REQUEST_METHOD"] == "GET") {
//JSON customers array
$customers = array();
if ($_GET["function1"] == "loadCustomers") {
try {
$customerStmt = $conn->prepare("Select customer.FirstName, customer.LastName, customer.City, sum(invoice.Total) from invoice INNER JOIN customer on invoice.CustomerId = customer.CustomerId group by invoice.CustomerId order by sum(invoice.total) DESC LIMIT 5");
$customerStmt->execute();
$customerRows = $customerStmt->fetchAll();
//how to create JSON data to send it
header("Content-type: application/json");
echo json_encode($customerRows);
}catch (PDOException $e) {
$e->getMessage();
}
}
Well, from the code it looks like you are responding with multiple customers, but in jQuery you are accessing the data directly without accessing the array. So it should look like this
$.ajax({
type:"GET",
url: "login.php",
data: dataString,
dataType: "json",
success: function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#customerList" );
},
error: function() {
$("#error").show();
$("#errormsg").text("cant display data");
}
});
The problem was i couldn't recive JSON data from PHP.
After hours of googling and trying diffrent solutions i finally found an error..
When you read from database you have to set it to utf-8 charset.
I was fixing this problem in code with utf8_encode function...
You have to set it in new definition of PDO object :
$conn= new PDO("mysql:host=$server;dbname=$database;charset=utf8", $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
After this change im sending JSON data .

Ajax request return empty array

I am trying to get the id, where the user clicked, and pass it to my controller via AJAX.
For some reason, when i try to show what i am receiving in my controller, it show an empty array.
Any idea why my alert return an empty Array?
JS Function:
function categorySelected(elem) {
$.ajax({
url: "/newgallery/creative-fields-click",
type: "POST",
data: elem.id
}).done(function (response) {
alert(response);
});
}
PHP:
public function creativeFieldsClickAction()
{
$idSelected = $this->_request->getPost();
print_r( $idSelected );
exit();
}
Data should be JSON, not integer.
data: { elemid : elem.id }
Then in PHP data can be found from $_POST['elemid']. In your code it could be like
$this->_request->getPost()['elemid'];
Or something like that.
Try by changing
In ajax
data: { id : elem.id }
And in action of controller
$ids = $_POST;
print_r($ids);

Binding json string with drop-down using jquery

I am new to jQuery. I am creating the json string in my servlet using gson-2.2.3.jar:
Gson gs = new Gson();
String json = gs.toJson(names);
System.out.println(json);
PrintWriter out = resp.getWriter();
out.println(json);
out.close();
Below are the two commented codes I tried for binding the json string with drop-down but none of them works:
$.ajax({
type:"POST",
url: "DropDownController",
success: function(result){
alert(result);
/* for (var id in result) {
$("#drpDown").append('<option value="'+id+'">'+id+'</option>');
} */
/* $.each(result, function (index, value) {
$("#drpDown").append('<option value="'+value.id+'">'+value.name+'</option>');
}); */
}
});
The alert message box present in the success displays the json string in below format:
["Alabama","California","Alaska","Ohio"]
Kindly let me know how to bind the above json string data with the drop-down.
Try like this:
$.ajax({
type: 'POST',
url: 'DropDownController',
dataType: 'json',
success: function(result) {
$.each(result, function() {
$("#drpDown").append(
$('<option/>', {
value: this,
html: this
})
);
});
}
});
Try this
var jso=["Alabama","California","Alaska","Ohio"]
for (var i in jso) {
$("#test").append('<option value="'+jso[i]+'">'+jso[i]+'</option>');
}
DEMO

Categories