I am dynamically adding table rows by selecting options from dropdown and then I am trying to send html table rows to php function using ajax as array in json format. However php function does not print all rows in the console log, when I am submitting more than one row. I got the desired output like once or twice. I think I am missing something in the php function. Please check once. If anymore information about the code is required, let me know, I will update.
Javascript:
function storeClgValues() {
var CollegeData= new Array();
$('#collegetable tr').each(function(row, tr){
CollegeData[row]={
"college" : $(tr).find('td:eq(0)').text()
}
});
CollegeData.shift();
return CollegeData;
}
$('#submit').click(function() {
CollegeData=storeClgValues();
CollegeData=$.toJSON(CollegeData);
$.ajax({
type:"POST",
url: '<?php echo base_url();?>ajaxController/insertcollege',
data: "CollegeData=" + CollegeData,
success: function(msg) {
console.log(CollegeData);
console.log(msg);
}
});
});
PHP function in AjaxController class:
public function insertcollege()
{
$data=array();
$data=stripcslashes($_POST['CollegeData']);
$data=json_decode($data, TRUE);
//echo $data[0]['college'].'<br>';
//echo $data[1]['college'].'<br>';
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
echo $item['college'].'<br>';
}
}
}
Output in console in three tries:
[{"college":"College of Agriculture"}]
College of Agriculture
[{"college":"College of Agriculture"},{"college":"College of Business"}]
College of Agriculture
College of Business
[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]
<!--nothing gets printed-->
Try like this...
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
$output[]=$item['college'].'<br>';
}
}
echo json_encode($output);
?>
OR
<?php
$json = '[{"college":"College of Agriculture"},{"college":"College of Business"}, {"college":"College of Comm & Educati"}]';
$data = json_decode($json,TRUE);
//print_r($data);
if (is_array($data) || is_object($data))
{
foreach ($data as $key => $item) {
foreach($item as $value){
$output[] = $value."</br>";
}
}
}
echo json_encode($output);
?>
Related
I'm trying to connect the bootstrap treeview but the json script is not working. here is the fetch.php source code: `
$sub_data["id"] = $row["id"];
$sub_data["invited"] = $row["invited"];
$sub_data["text"] = $row["invited"];
$sub_data["caller_id"] = $row["caller_id"];
$data[] = $sub_data;
foreach ($data as $key => &$value)
{
$output[$value["id"]] = &$value;
}
foreach ($data as $key => &$value)
{
if ($value["caller_id"] && isset($output[$value["caller_id"]]))
{
$output[$value["caller_id"]]["nodes"][] = &$value;
}
}
foreach ($data as $key => &$value)
{
if ($value["caller_id"] && isset($output[$value["caller_id"]]))
{
unset($data[$key]);
}
}
echo json_encode($data);`
and this is the treeshow.php script code:
$(document).ready(function(){
$.ajax({
url: "fetch.php",
method:"POST",
dataType: "json",
success: function(data)
{
$('#treeview').treeview({data: data});
}
});
});
and mysql db fields: id, invited, caller_id what is wrong with this codes?
I have categories and I want to display the categories with my dropdown when I click on the dropdown.
This approach does'nt work. What are the elements than I need to change inside the code ?
Thank you
my ajax php
$Qcheck = $OSCOM_Db->prepare('select distinct categories_id as id,
categories_name as name
from :table_catogories
');
$Qcheck->execute();
$list = $Qcheck->rowCount() ;
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
now my files
<?php
$categories_ajax = OSCOM::link('categories_ajax.php');
?>
<script type="text/javascript">
function myAjax() {
$("#myAjax").on('click', function(){
$.ajax({
url: '<?php echo $categories_ajax; ?>',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
</script>
// my dropdown
<?php echo HTML::selectMenu('move_to_category_id', CategoriesAdmin::getCategoryTree(), 'onclick="myAjax()"') . HTML::hiddenField('current_category_id', $current_category_id); ?>
note CategoriesAdmin::getCategoryTree() display the categories name. it's an array
my dropdown function element
public static function selectMenu($name, array $values, $default = null, $parameters = '', $required = false, $class = 'form-control') {}
how to retrieve much data in view (codeigniter) using while(). if I use foreach, I can't get the desired result. this is my code:
//my view home.php
$(document).ready(function(){
$('#check').click(function(event){
event.preventDefault();
var form_data = {
name: "xxxx"
};
$.ajax({
url: 'http://localhost:8000/jqjx/index.php/cont/getname',
type: 'POST',
async : false,
data: form_data,
dataType: 'html',
success: function(resp){
$('#content').html(resp);
}
});
return false;
});
});
//my controller cont.php
public function getname()
{
$data = array();
$namex = $this->input->post('name');
if($q = $this->my_model->detail_data($namex))
{
$data['data_detail'] = $q;
$this->load->view('tamp_page', $data);
}
}
my helper page (view) tamp_page.php
<?php
if(isset($data_detail))
{
foreach ($data_detailas $row) {
echo $row['name']."<br/>";
echo $row['birthday']."<br/>";
}
}
?>
if I use :
<?php
if(isset($data_detail))
{
echo $name_data['id_transactions'] . "<br/>";
echo $name_data['goods'] . "<br/>";
}
?>
it's still work but just for 1 data result. so how I can loop more much data.. thanks..
<?php
if(isset($data_detail))
{
foreach ($data_detail as $row)
{
echo $row['name']."<br/>"; //$row['name] was not properly closed. single quote(') was missing
echo $row['birthday']."<br/>";
}
}
?>
Just basic use of foreach:
if(isset($data_detail)){
foreach ($data_detailas as $row) {
echo $row['name'] . "<br/>";
echo $row['birthday'] . "<br/>";
}
}
I'm screen scraping a site with a php script which creates an array in the end that I want to send back to the javascript caller function. In the code below I've tried to print it out with 'print_r', which doesn't give me any results at all (?). If I echo out on of the elements (e.g $addresses[1]) the element is shown.
So, why ain't I getting anything out from the php function, and what is really the best way to send back the array to the calling js function?
Thanks a lot in advance!
js:
$.post(
"./php/foo.php",
{
zipcode: zipcode
},
function(data) {
$('#showData').html(data);
}
);
php:
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
array_push($addresses, $address);
}
print_r($addresses);
You can use JSON to return an array back to the client-side, it can be send by AJAX same what you are doing on your existing code.
Use json_encode() of PHP, this function will make your PHP array into a JSON string and you can use it to send back to your client by using AJAX
In your PHP code(Just for demonstration how it works)
json.php
<?php
$addresses['hello'] = NULL;
$addresses['hello2'] = NULL;
if($_POST['zipcode'] == '123'){ //your POST data is recieved in a common way
//sample array
$addresses['hello'] = 'hi';
$addresses['hello2'] = 'konnichiwa';
}
else{
$addresses['hello'] = 'who are you?';
$addresses['hello2'] = 'dare desu ka';
}
echo json_encode($addresses);
?>
then in your client script(much better you use the Jquery's long AJAX way)
$.ajax({
url:'http://localhost/json.php',
type:'post',
dataType:'json',
data:{
zipcode: '123' //sample data to send to the server
},
//the variable 'data' contains the response that can be manipulated in JS
success:function(data) {
console.log(data); //it would show the JSON array in your console
alert(data.hello); //will alert "hi"
}
});
references
http://api.jquery.com/jQuery.ajax/
http://php.net/manual/en/function.json-encode.php
http://json.org/
js should be
$.ajax({
url:'your url',
type:'post',
dataType:'json',
success:function(data) {
console.log(JSON.stringify(data));
}
});
server
$tempAddresses = array();
$addresses = array();
$url = 'http://www.foo.com/addresses/result.jspv?pnr=' . $zipcode;
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
array_push($tempAddresses, $cell);
}
$tempAddresses = array_unique($tempAddresses);
foreach ($tempAddresses as $address) {
$arr_res[] =$address;
}
header('content-type:application/json');
echo json_encode($arr_res);
I'm currently working with the jQuery Autocomplete Plugin.
The code they provided in the demonstration is:
<?php
$q = strtolower($_GET["q"]);
$items = array(
"Peter Pan"=>"peter#pan.de",
"Molly"=>"molly#yahoo.com",
);
$result = array();
foreach ($items as $key) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key
));
}
}
echo json_encode($result);
?>
I'd like to know how I can modify this code to output my own array from my MySQL database.
I've tried on my own modification, but I'm not doing it correctly. This is what I am trying:
$q = strtolower($_GET["q"]);
$sql = "SELECT name from user_info";
require("connection.php");
$result = mysql_db_query($DBname,$sql,$link) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
foreach ($rows as $key) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
$key
));
}
}
}
print json_encode($rows);
And this is my jQuery/Javascript:
$("#email").autocomplete('emails.php', {
multiple: false,
dataType: "json",
parse: function(data) {
return $.map(data, function(row) {
return {
data: row,
value: row.name,
result: row.name
}
});
},
formatItem: function(item) {
return format(item);
}
}).result(function(e, item) {
$("#content").append("<p>selected " + format(item) + "</p>");
});
});
As a result, Firebug shows that it throws the following error:
value is undefined
Any help on getting my query setup properly would be greatly aprpeciated. Thanks!
I think that this occurs because you using a array converted in json, then you need to use how an array too in jquery result. Or you can do a json string without using json, in the format: '[{"name":"john","year":2009},{"name":"tom","year":2000},...]'.
Your jquery is fine. After several hours I found out that it was the formatting in the 'format' function that was triggering the error.
If you look at the source code at
http://jquery.bassistance.de/autocomplete/demo/json.html
You'll see the following, seemingly inconsequential function
function format(mail) {
return mail.name + " <" + mail.to + ">";
}
If you're leaving out the 'less than' and 'greater than' representations, then you're probably getting the
value is undefinded
error after the first record is looped through in your console. For some strange reason the less than and greater than symbols are significant. Make sure you keep them in your format function.